branch_name
stringclasses 15
values | target
stringlengths 26
10.3M
| directory_id
stringlengths 40
40
| languages
sequencelengths 1
9
| num_files
int64 1
1.47k
| repo_language
stringclasses 34
values | repo_name
stringlengths 6
91
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
| input
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|
refs/heads/main | <repo_name>CipherX1-ops/MegatronFileStream<file_sep>/Megatron/server/__init__.py
from aiohttp import web
from .stream_routes import routes
def web_server():
web_app = web.Application(client_max_size=30000000)
web_app.add_routes(routes)
return web_app
<file_sep>/README.md
# MegatronFileStream
Megatron File Stream Telegram Bot
# Deploy Megatron to Heroku
<p align="center"><a href="https://heroku.com/deploy?template=https://github.com/CipherX1-ops/MegatronFileStream"> <img src="https://img.shields.io/badge/Deploy%20To%20Heroku-black?style=for-the-badge&logo=heroku" width="220" height="38.45"/></a></p>
<file_sep>/Megatron/utils/broadcast_helper.py
import asyncio
import traceback
from pyrogram.errors import FloodWait, InputUserDeactivated, UserIsBlocked, PeerIdInvalid
async def send_msg(user_id, message):
try:
await message.forward(chat_id=user_id)
return 200, None
except FloodWait as e:
await asyncio.sleep(e.x)
return send_msg(user_id, message)
except InputUserDeactivated:
return 400, f"{user_id} : deactivated\n"
except UserIsBlocked:
return 400, f"{user_id} : blocked the bot\n"
except PeerIdInvalid:
return 400, f"{user_id} : user id invalid\n"
except Exception as e:
return 500, f"{user_id} : {traceback.format_exc()}\n"
<file_sep>/Megatron/bot/plugins/stream.py
import asyncio
import logging
from urllib.parse import quote_plus
from pyrogram import filters, Client
from pyrogram.errors import FloodWait, UserNotParticipant
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.enums import ParseMode
from Megatron.bot import StreamBot
from Megatron.utils import get_hash, get_name
from Megatron.utils.database import Database
from Megatron.handlers.fsub import force_subscribe
from Megatron.vars import Var
from Megatron.utils.human_readable import humanbytes
from Megatron.utils.antispam import check_spam
db = Database(Var.DATABASE_URL, Var.SESSION_NAME)
def detect_type(m: Message):
if m.document:
return m.document
elif m.video:
return m.video
elif m.photo:
return m.photo
elif m.audio:
return m.audio
else:
return
@StreamBot.on_message(
filters.private
& (
filters.document
| filters.video
| filters.audio
| filters.animation
| filters.voice
| filters.video_note
| filters.photo
| filters.sticker
),
group=4,
)
async def media_receive_handler(c: Client, m: Message):
if not await db.is_user_exist(m.from_user.id):
await db.add_user(m.from_user.id)
await c.send_message(
Var.BIN_CHANNEL,
f"#NEW_USER: \n\nNew User [{m.from_user.first_name}](tg://user?id={m.from_user.id}) Started the bot."
)
if Var.UPDATES_CHANNEL:
fsub = await force_subscribe(c, m)
if fsub == 400:
return
file_size = None
if m.video:
file_size = f"{humanbytes(m.video.file_size)}"
elif m.document:
file_size = f"{humanbytes(m.document.file_size)}"
elif m.audio:
file_size = f"{humanbytes(m.audio.file_size)}"
elif m.photo:
file_size = f"{humanbytes(m.photo.file_size)}"
file_name = None
if m.video:
file_name = f"{m.video.file_name}"
elif m.document:
file_name = f"{m.document.file_name}"
elif m.audio:
file_name = f"{m.audio.file_name}"
elif m.photo:
file_name = f"{m.photo.file_id}"
try:
file = detect_type(m)
file_name = ''
if file and "GiB" in str(file_size) and not m.from_user.id in Var.PRO_USERS:
await c.send_message(m.chat.id, "⚜️ Files with size more than 1GiB need premium subscription. For purchasing premium subscription press /upgrade command.\n\n⚜️ امکان دریافت لینک فایل هایی با حجم بیشتر از 1 گیگ فقط برای کاربران پریمیوم امکان پذیر است. جهت خرید اشتراک پریمیوم و برداشته شدن محدودیت ها کامند /upgrade را وارد نمایید.")
else:
is_spam, sleep_time = await check_spam(m.from_user.id)
if is_spam:
if m.from_user.id in Var.PRO_USERS:
await m.reply_text(f"⚠️ Don't spam premium user\n\n✨ As you're a premium user you have to wait for `{str(sleep_time)}` seconds. Usual users have to wait for 120 seconds.\n\n⚠️ اسپم نزنید کاربر پریمیوم\n✨ با وجود کاربر پریمیوم بودن، شما باید `{str(sleep_time)}` ثانیه صبر کنید. کاربران عادی 120 ثانیه محدودیت دارند.", quote=True)
else:
await m.reply_text(f"⚠️ Don't spam!\n\n✨ You have to wait for `{str(sleep_time)}` seconds or purchasing premium subscription via /upgrade command.\n\n⚠️ اسپم نزنید!\n✨ شما باید `{str(sleep_time)}` ثانیه صبر کنید و یا اشتراک پریمیوم از طریق کامند /upgrade اشتراک پریمیوم تهیه نمایید.", quote=True)
else:
u = await c.get_chat_member(int(Var.UPDATES_CHANNEL), m.from_user.id)
if u.status == "kicked" or u.status == "banned":
await c.send_message(
chat_id=m.from_user.id,
text="✨ You're Banned due not to pay attention to the [rules](https://t.me/FutureTechnologyOfficial/1257). Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8) if you think you've banned wrongly.\n\n✨ شما به علت عدم رعایت [قوانین](https://t.me/FutureTechnologyOfficial/1257) بن شده اید. اگر فکر میکنید بن شدن شما اشتباه بوده و قوانین را رعایت کرده اید می توانید با [گروه پشتیبانی](https://t.me/joinchat/riq-psSksFtiMDU8) در ارتباط باشید.",
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True
)
else:
file_name = file.file_name
user_type = "#Pro_User" if m.from_user.id in Var.PRO_USERS else "#Ordinary_User"
log_msg = await m.forward(chat_id=Var.BIN_CHANNEL)
stream_link = f"{Var.URL}{log_msg.id}/{quote_plus(str(get_name(m)))}?hash={get_hash(log_msg)}"
short_link = f"{Var.URL}{get_hash(log_msg)}{log_msg.id}"
logging.info(f"Generated link: {stream_link} for {m.from_user.first_name}")
msg_text = f"Your Link Generated! 😄\n\nلینک پر سرعت شما ایجاد شد! 😄\n\n📂 **File Name:** `{file_name}`\n\n**✨ File Size:** `{file_size}`\n\n📥 **Direct/Stream Link:** `{stream_link}`\n\n📥 **Short Link:** `{short_link}`"
await c.send_message(chat_id=Var.BIN_CHANNEL, text=f"✨ **Requested by:** [{m.from_user.first_name}](tg://user?id={m.from_user.id})\n✨ **User ID:** `{m.from_user.id}`\n✨ **User Type:** `{user_type}`\n✨ **Download Link:** {stream_link}\n✨ **Short Link:** {short_link}", disable_web_page_preview=True, reply_to_message_id=log_msg.id, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("࿋ Ban User ࿋", callback_data=f"ban_{m.from_user.id}")]]))
await m.reply_text(
text=msg_text,
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("࿋ Direct/Stream Link ࿋", url=stream_link)],
[InlineKeyboardButton("࿋ Short Link ࿋", url=short_link)],
],
),
quote=True,
parse_mode=ParseMode.MARKDOWN
)
except FloodWait as e:
print(f"Sleeping for {str(e.x)}s")
await asyncio.sleep(e.x)
await c.send_message(chat_id=Var.BIN_CHANNEL, text=f"Got FloodWait of {str(e.x)}s from [{m.from_user.first_name}](tg://user?id={m.from_user.id})\n\n**User ID:** `{str(m.from_user.id)}`", disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN)
@StreamBot.on_message(filters.channel & (filters.document | filters.video | filters.photo) & ~filters.forwarded, group=-1)
async def channel_receive_handler(bot, broadcast):
if int(broadcast.chat.id) in Var.BANNED_CHANNELS:
await bot.leave_chat(broadcast.chat.id)
return
try:
log_msg = await broadcast.forward(chat_id=Var.BIN_CHANNEL)
stream_link = f"{Var.URL}{log_msg.id}/{quote_plus(str(get_name(broadcast)))}?hash={get_hash(log_msg)}"
await log_msg.reply_text(
text=f"**Channel Name:** `{broadcast.chat.title}`\n**Channel ID:** `{broadcast.chat.id}`\n**Link:** {stream_link}",
quote=True,
parse_mode=ParseMode.MARKDOWN
)
await bot.edit_message_reply_markup(
chat_id=broadcast.chat.id,
message_id=broadcast.id,
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("࿋ Direct Download Link ࿋", url=f"{stream_link}")]
]
)
)
except FloodWait as w:
print(f"Sleeping for {str(w.x)}s")
await asyncio.sleep(w.x)
await bot.send_message(chat_id=Var.BIN_CHANNEL,
text=f"Got FloodWait of {str(w.x)}s from {broadcast.chat.title}\n\n**Channel ID:** `{str(broadcast.chat.id)}`",
disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN)
except Exception as e:
await bot.send_message(chat_id=Var.BIN_CHANNEL, text=f"#ERROR_TRACEBACK: `{e}`", disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN)
<file_sep>/Megatron/utils/file_properties.py
from typing import Any, Optional
from pyrogram import Client
from pyrogram.types import Message
from pyrogram.file_id import FileId
from pyrogram.raw.types.messages import Messages
from Megatron.server.exceptions import FIleNotFound
async def parse_file_id(message: "Message") -> Optional[FileId]:
media = get_media_from_message(message)
if media:
return FileId.decode(media.file_id)
async def parse_file_unique_id(message: "Messages") -> Optional[str]:
media = get_media_from_message(message)
if media:
return media.file_unique_id
async def get_file_ids(client: Client, chat_id: int, message_id: int) -> Optional[FileId]:
message = await client.get_messages(chat_id, message_id)
if message.empty:
raise FIleNotFound
media = get_media_from_message(message)
file_unique_id = await parse_file_unique_id(message)
file_id = await parse_file_id(message)
setattr(file_id, "file_size", getattr(media, "file_size", 0))
setattr(file_id, "mime_type", getattr(media, "mime_type", ""))
setattr(file_id, "file_name", getattr(media, "file_name", ""))
setattr(file_id, "unique_id", file_unique_id)
return file_id
def get_media_from_message(message: "Message") -> Any:
media_types = (
"audio",
"document",
"photo",
"sticker",
"animation",
"video",
"voice",
"video_note",
)
for attr in media_types:
media = getattr(message, attr, None)
if media:
return media
def get_hash(media_msg: Message) -> str:
media = get_media_from_message(media_msg)
return getattr(media, "file_unique_id", "")[:6]
def get_name(media_msg: Message) -> str:
media = get_media_from_message(media_msg)
return getattr(media, "file_name", "")
<file_sep>/Megatron/utils/config_parser.py
from os import environ
from typing import Dict, Optional
class TokenParser:
def __init__(self, config_file: Optional[str] = None):
self.tokens = {}
self.config_file = config_file
def parse_from_env(self) -> Dict[int, str]:
self.tokens = dict(
(c + 1, t)
for c, (_, t) in enumerate(
filter(
lambda n: n[0].startswith("MULTI_TOKEN"), sorted(environ.items())
)
)
)
return self.tokens
<file_sep>/Megatron/utils/database.py
import datetime
import motor.motor_asyncio
class Database:
def __init__(self, uri, database_name):
self._client = motor.motor_asyncio.AsyncIOMotorClient(uri)
self.db = self._client[database_name]
self.col = self.db.users
self.trans = self.db.lang
def new_user(self, id):
return dict(
id=id,
join_date=datetime.date.today().isoformat()
)
async def add_user(self, id):
user = self.new_user(id)
await self.col.insert_one(user)
async def is_user_exist(self, id):
user = await self.col.find_one({'id': int(id)})
return True if user else False
async def total_users_count(self):
count = await self.col.count_documents({})
return count
async def get_all_users(self):
all_users = self.col.find({})
return all_users
async def delete_user(self, user_id):
await self.col.delete_many({'id': int(user_id)})
async def add_trans(self, lang):
language = self.new_user(lang)
await self.trans.insert_one(language)
async def is_trans_exist(self, lang):
language = await self.trans.find_one({'lang': str(lang)})
return True if language else False
async def delete_trans(self, trans_lang):
await self.trans.delete_many({'lang': str(trans_lang)})
async def update_trans(self, update_lang):
await self.trans.update_one(language, {"$set": {'lang': str(update_lang)}})
<file_sep>/Megatron/__init__.py
import time
from .vars import Var
from Megatron.bot.clients import StreamBot
#print("\n")
#print("------------------- Initializing Telegram Bot -------------------")
#StreamBot.start()
#bot_info = StreamBot.get_me()
__version__ = 3
StartTime = time.time()
<file_sep>/requirements.txt
aiohttp<=3.8.1
aiofiles
dnspython
motor
pyrogram<=2.0.33
pyromod==1.5
python-dotenv<=0.20.0
requests
tgcrypto<=1.2.3
<file_sep>/Megatron/utils/callbacks.py
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from pyrogram.errors.exceptions.bad_request_400 import UserNotParticipant, MessageNotModified
from Megatron.bot import StreamBot
from Megatron.vars import Var
@StreamBot.on_callback_query()
async def button(bot, cmd: CallbackQuery):
cb_data = cmd.data
if "refreshmeh" in cb_data:
if Var.UPDATES_CHANNEL:
invite_link = await bot.create_chat_invite_link(int(Var.UPDATES_CHANNEL))
try:
user = await bot.get_chat_member(int(Var.UPDATES_CHANNEL), cmd.message.chat.id)
if user.status == "kicked":
await cmd.message.edit(
text="**✨ You are Banned due not to pay attention to the rules. Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8) for further information if interested.\n\n✨ شما به علت عدم رعایت قوانین بن شده اید. جهت اطلاع بیشتر در صورت تمایل می توانید با [گروه پشتیبانی](https://t.me/joinchat/riq-psSksFtiMDU8) در ارتباط باشید.",
parse_mode="markdown",
disable_web_page_preview=True
)
return
except UserNotParticipant:
await cmd.message.edit(
text="**✨ You still haven't joined the updates channel. Only channel subscribers can use the bot.**\n\nAfter joining tap refresh button.\n\n**✨شما هنوز عضو چنل نشدید. تنها اعضای چنل می توانند از بات استفاده کنند.**\n\nپس از عضویت بر روی دکمه refresh کلیک کنید.",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton("✵ Join Updates Channel ✵", url=invite_link.invite_link)
],
[
InlineKeyboardButton("🔄 Refresh 🔄", callback_data="refreshmeh")
]
]
),
parse_mode="markdown"
)
return
except Exception:
await cmd.message.edit(
text="Something went Wrong. Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8).",
parse_mode="markdown",
disable_web_page_preview=True
)
return
await cmd.message.edit(
text=f"""Hey Dear {cmd.from_user.mention(style="md")} 🙋🏻♂️\nI'm Telegram File to Link Generator Bot.\n\nSend me any file & get the fast direct download link!\n\nسلام {cmd.from_user.mention(style="md")} عزیز 🙋🏻♂️\nمن بات تبدیل فایل به لینک هستم\nفایل تلگرامی خود را ارسال کنید تا لینک دانلود پر سرعت آن را دریافت نمایید\n\nهمچنین با زدن دستور /nim میتوانید لینک های دریافتی خود را نیم بها نمایید.""",
parse_mode="Markdown",
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton('✵ Updates Channel ✵', url='https://t.me/FutureTechnologyOfficial'), InlineKeyboardButton('✵ Support Group ✵', url='https://t.me/joinchat/riq-psSksFtiMDU8')],
[InlineKeyboardButton('✵ Developer ✵', url='https://t.me/CipherXBot')]
]
),
disable_web_page_preview=True
)
elif cb_data.startswith("ban_"):
if Var.UPDATES_CHANNEL is None:
await cmd.answer("You didn't Set any Updates Channel", show_alert=True)
return
try:
user_id = cb_data.split("_", 1)[1]
await bot.ban_chat_member(chat_id=Var.UPDATES_CHANNEL, user_id=int(user_id))
await cmd.answer("User Banned from Updates Channel", show_alert=True)
except Exception as e:
await cmd.answer(f"Can't Ban Him!\n\nError: {e}", show_alert=True)
<file_sep>/Megatron/vars.py
from os import environ
from dotenv import load_dotenv
load_dotenv()
class Var(object):
MULTI_CLIENT = False
API_ID = int(environ.get("API_ID"))
API_HASH = str(environ.get("API_HASH"))
SESSION_NAME = str(environ.get('SESSION_NAME', 'Megatron'))
BOT_TOKEN = str(environ.get("BOT_TOKEN"))
BROADCAST_AS_COPY = bool(environ.get("BROADCAST_AS_COPY", False))
SLEEP_THRESHOLD = int(environ.get("SLEEP_THRESHOLD", "60")) # 1 minte
WORKERS = int(environ.get("WORKERS", "6")) # 6 workers = 6 commands at once
BIN_CHANNEL = int(
environ.get("BIN_CHANNEL", None)
) # you NEED to use a CHANNEL when you're using MULTI_CLIENT
PORT = int(environ.get("PORT", 8080))
BIND_ADDRESS = str(environ.get("WEB_SERVER_BIND_ADDRESS", "0.0.0.0"))
PING_INTERVAL = int(environ.get("PING_INTERVAL", "1200")) # 20 minutes
HAS_SSL = environ.get("HAS_SSL", False)
HAS_SSL = True if str(HAS_SSL).lower() == "true" else False
OWNER_ID = int(environ.get('OWNER_ID'))
PRO_USERS = list(set(int(x) for x in str(environ.get("PRO_USERS", "")).split()))
NO_PORT = environ.get("NO_PORT", False)
NO_PORT = True if str(NO_PORT).lower() == "true" else False
if "DYNO" in environ:
ON_HEROKU = True
APP_NAME = str(environ.get("APP_NAME"))
else:
ON_HEROKU = False
DATABASE_URL = str(environ.get('DATABASE_URL'))
UPDATES_CHANNEL = environ.get("UPDATES_CHANNEL", None)
BANNED_CHANNELS = list(set(int(x) for x in str(environ.get("BANNED_CHANNELS", "-100")).split()))
FQDN = (
str(environ.get("FQDN", BIND_ADDRESS))
if not ON_HEROKU or environ.get("FQDN")
else APP_NAME + ".herokuapp.com"
)
if ON_HEROKU:
URL = f"https://{FQDN}/"
else:
URL = "http{}://{}{}/".format(
"s" if HAS_SSL else "", FQDN, "" if NO_PORT else ":" + str(PORT)
)
<file_sep>/Megatron/utils/custom_dl.py
import math
import asyncio
import logging
from typing import Dict, Union
from pyrogram import Client, utils, raw
from pyrogram.session import Session, Auth
from pyrogram.errors import AuthBytesInvalid
from pyrogram.file_id import FileId, FileType, ThumbnailSource
from .file_properties import get_file_ids
from Megatron import Var
from Megatron.bot import work_loads
from Megatron.server.exceptions import FIleNotFound
async def chunk_size(length):
return 2 ** max(min(math.ceil(math.log2(length / 1024)), 10), 2) * 1024
async def offset_fix(offset, chunksize):
offset -= offset % chunksize
return offset
class ByteStreamer:
def __init__(self, client: Client):
"""A custom class that holds the cache of a specific client and class functions.
attributes:
client: the client that the cache is for.
cached_file_ids: a dict of cached file IDs.
cached_file_properties: a dict of cached file properties.
functions:
generate_file_properties: returns the properties for a media of a specific message contained in Tuple.
generate_media_session: returns the media session for the DC that contains the media file.
yield_file: yield a file from telegram servers for streaming.
This is a modified version of the <https://github.com/eyaadh/megadlbot_oss/blob/master/mega/telegram/utils/custom_download.py>
Thanks to Eyaadh <https://github.com/eyaadh>
"""
self.clean_timer = 30 * 60
self.client: Client = client
self.cached_file_ids: Dict[int, FileId] = {}
asyncio.create_task(self.clean_cache())
async def get_file_properties(self, message_id: int) -> FileId:
"""
Returns the properties of a media of a specific message in a FIleId class.
if the properties are cached, then it'll return the cached results.
or it'll generate the properties from the Message ID and cache them.
"""
if message_id not in self.cached_file_ids:
await self.generate_file_properties(message_id)
logging.debug(f"Cached file properties for message with ID {message_id}")
return self.cached_file_ids[message_id]
async def generate_file_properties(self, message_id: int) -> FileId:
"""
Generates the properties of a media file on a specific message.
returns ths properties in a FIleId class.
"""
file_id = await get_file_ids(self.client, Var.BIN_CHANNEL, message_id)
logging.debug(f"Generated file ID and Unique ID for message with ID {message_id}")
if not file_id:
logging.debug(f"Message with ID {message_id} not found")
raise FIleNotFound
self.cached_file_ids[message_id] = file_id
logging.debug(f"Cached media message with ID {message_id}")
return self.cached_file_ids[message_id]
async def generate_media_session(self, client: Client, file_id: FileId) -> Session:
"""
Generates the media session for the DC that contains the media file.
This is required for getting the bytes from Telegram servers.
"""
media_session = client.media_sessions.get(file_id.dc_id, None)
if media_session is None:
if file_id.dc_id != await client.storage.dc_id():
media_session = Session(
client,
file_id.dc_id,
await Auth(
client, file_id.dc_id, await client.storage.test_mode()
).create(),
await client.storage.test_mode(),
is_media=True,
)
await media_session.start()
for _ in range(6):
exported_auth = await client.invoke(
raw.functions.auth.ExportAuthorization(dc_id=file_id.dc_id)
)
try:
await media_session.invoke(
raw.functions.auth.ImportAuthorization(
id=exported_auth.id, bytes=exported_auth.bytes
)
)
break
except AuthBytesInvalid:
logging.debug(
f"Invalid authorization bytes for DC {file_id.dc_id}"
)
continue
else:
await media_session.stop()
raise AuthBytesInvalid
else:
media_session = Session(
client,
file_id.dc_id,
await client.storage.auth_key(),
await client.storage.test_mode(),
is_media=True,
)
await media_session.start()
logging.debug(f"Created media session for DC {file_id.dc_id}")
client.media_sessions[file_id.dc_id] = media_session
else:
logging.debug(f"Using cached media session for DC {file_id.dc_id}")
return media_session
@staticmethod
async def get_location(file_id: FileId) -> Union[raw.types.InputPhotoFileLocation,
raw.types.InputDocumentFileLocation,
raw.types.InputPeerPhotoFileLocation,]:
"""
Returns the file location for the media file.
"""
file_type = file_id.file_type
if file_type == FileType.CHAT_PHOTO:
if file_id.chat_id > 0:
peer = raw.types.InputPeerUser(
user_id=file_id.chat_id, access_hash=file_id.chat_access_hash
)
else:
if file_id.chat_access_hash == 0:
peer = raw.types.InputPeerChat(chat_id=-file_id.chat_id)
else:
peer = raw.types.InputPeerChannel(
channel_id=utils.get_channel_id(file_id.chat_id),
access_hash=file_id.chat_access_hash,
)
location = raw.types.InputPeerPhotoFileLocation(
peer=peer,
volume_id=file_id.volume_id,
local_id=file_id.local_id,
big=file_id.thumbnail_source == ThumbnailSource.CHAT_PHOTO_BIG,
)
elif file_type == FileType.PHOTO:
location = raw.types.InputPhotoFileLocation(
id=file_id.media_id,
access_hash=file_id.access_hash,
file_reference=file_id.file_reference,
thumb_size=file_id.thumbnail_size,
)
else:
location = raw.types.InputDocumentFileLocation(
id=file_id.media_id,
access_hash=file_id.access_hash,
file_reference=file_id.file_reference,
thumb_size=file_id.thumbnail_size,
)
return location
async def yield_file(
self,
file_id: FileId,
index: int,
offset: int,
first_part_cut: int,
last_part_cut: int,
part_count: int,
chunk_size: int,
) -> Union[str, None]:
"""
Custom generator that yields the bytes of the media file.
Modded from <https://github.com/eyaadh/megadlbot_oss/blob/master/mega/telegram/utils/custom_download.py#L20>
Thanks to Eyaadh <https://github.com/eyaadh>
"""
client = self.client
work_loads[index] += 1
logging.debug(f"Starting to yielding file with client {index}.")
media_session = await self.generate_media_session(client, file_id)
current_part = 1
location = await self.get_location(file_id)
try:
r = await media_session.invoke(
raw.functions.upload.GetFile(
location=location, offset=offset, limit=chunk_size
),
)
if isinstance(r, raw.types.upload.File):
while current_part <= part_count:
chunk = r.bytes
if not chunk:
break
offset += chunk_size
if part_count == 1:
yield chunk[first_part_cut:last_part_cut]
break
if current_part == 1:
yield chunk[first_part_cut:]
if 1 < current_part <= part_count:
yield chunk
r = await media_session.invoke(
raw.functions.upload.GetFile(
location=location, offset=offset, limit=chunk_size
),
)
current_part += 1
except (TimeoutError, AttributeError):
pass
finally:
logging.debug("Finished yielding file with {current_part} parts.")
work_loads[index] -= 1
async def clean_cache(self) -> None:
"""
function to clean the cache to reduce memory usage
"""
while True:
await asyncio.sleep(self.clean_timer)
self.cached_file_ids.clear()
logging.debug("Cleaned the cache")
<file_sep>/Megatron/utils/__init__.py
from .keepalive import ping_server
from .config_parser import TokenParser
from .time_format import get_readable_time
from .file_properties import get_hash, get_name
from .custom_dl import ByteStreamer, offset_fix, chunk_size
<file_sep>/Megatron/utils/human_readable.py
def humanbytes(size):
# https://stackoverflow.com/a/49361727/4723940
# 2**10 = 1024
if not size:
return ""
power = 2**10
n = 0
Dic_powerN = {0: ' ', 1: 'Ki', 2: 'Mi', 3: 'Gi', 4: 'Ti'}
while size > power:
size /= power
n += 1
return str(round(size, 2)) + " " + Dic_powerN[n] + 'B'
<file_sep>/Megatron/bot/__init__.py
from os import getcwd
from pyromod import listen
from pyrogram import Client
from ..vars import Var
StreamBot = Client(
"Megatron",
api_id=Var.API_ID,
api_hash=Var.API_HASH,
workdir="Megatron",
plugins={"root": "Megatron/bot/plugins"},
bot_token=Var.BOT_TOKEN,
sleep_threshold=Var.SLEEP_THRESHOLD,
workers=Var.WORKERS,
)
multi_clients = {}
work_loads = {}
<file_sep>/Megatron/__main__.py
import os
#import signal
import sys
import asyncio
import logging
from .vars import Var
from aiohttp import web
from pyrogram import idle
from Megatron import utils
from Megatron import StreamBot
from Megatron.server import web_server
from Megatron.bot.clients import initialize_clients
logging.basicConfig(
level=logging.INFO,
datefmt="%d/%m/%Y %H:%M:%S",
format="[%(asctime)s][%(levelname)s] => %(message)s",
handlers=[logging.StreamHandler(stream=sys.stdout),
logging.FileHandler("streambot.log", mode="a", encoding="utf-8")],)
logging.getLogger("pyrogram").setLevel(logging.ERROR)
logging.getLogger("aiohttp").setLevel(logging.ERROR)
logging.getLogger("aiohttp.web").setLevel(logging.ERROR)
server = web.AppRunner(web_server())
if sys.version_info[1] > 9:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
else:
loop = asyncio.get_event_loop()
async def start_services():
print()
print("-------------------- Initializing Telegram Bot --------------------")
await StreamBot.start()
bot_info = await StreamBot.get_me()
StreamBot.username = bot_info.username
print("------------------------------ DONE ------------------------------")
print()
print(
"---------------------- Initializing Clients ----------------------"
)
await initialize_clients()
print("------------------------------ DONE ------------------------------")
if Var.ON_HEROKU:
print("------------------ Starting Keep Alive Service ------------------")
print()
asyncio.create_task(utils.ping_server())
print("--------------------- Initalizing Web Server ---------------------")
await server.setup()
bind_address = "0.0.0.0" if Var.ON_HEROKU else Var.BIND_ADDRESS
await web.TCPSite(server, bind_address, Var.PORT).start()
print("------------------------------ DONE ------------------------------")
print()
print("------------------------- Service Started -------------------------")
print(" bot =>> {}".format(bot_info.first_name))
if bot_info.dc_id:
print(" DC ID =>> {}".format(str(bot_info.dc_id)))
print(" server ip =>> {}".format(bind_address, Var.PORT))
if Var.ON_HEROKU:
print(" app running on =>> {}".format(Var.FQDN))
print("------------------------------------------------------------------")
await idle()
#async def cleanup():
#await server.cleanup()
#if StreamBot.is_connected:
#await StreamBot.stop()
#async def handle_termination(signum, frame):
#print("Received termination signal")
#await cleanup()
#sys.exit(0)
if __name__ == "__main__":
#signal.signal(signal.SIGINT, lambda s,f: asyncio.ensure_future(handle_termination(s,f)))
#signal.signal(signal.SIGTERM, lambda s,f: asyncio.ensure_future(handle_termination(s,f)))
try:
loop.run_until_complete(start_services())
#loop.run_forever()
except KeyboardInterrupt:
print("------------------------ Stopped Services ------------------------")
<file_sep>/Megatron/server/stream_routes.py
import re
import time
import math
import logging
import secrets
import mimetypes
from aiohttp import web
from aiohttp.http_exceptions import BadStatusLine
from Megatron.bot import multi_clients, work_loads
from Megatron.server.exceptions import FIleNotFound, InvalidHash
from Megatron import Var, utils, StartTime, __version__
routes = web.RouteTableDef()
@routes.get("/", allow_head=True)
async def root_route_handler(_):
return web.json_response(
{
"⁂ Server Status": "running",
"⁂ Uptime": utils.get_readable_time(time.time() - StartTime),
"⁂ Telegram Bot": "@FiletoLinkTelegramBot",
"⁂ Connected_ Bots": len(multi_clients),
"⁂ Loads": dict(
("bot" + str(c + 1), l)
for c, (_, l) in enumerate(
sorted(work_loads.items(), key=lambda x: x[1], reverse=True)
)
),
"⁂ Version": __version__,
"⁂ Developed by": "CipherX",
"⁂ Channel": "@FutureTechnologyOfficial",
}
)
@routes.get(r"/{path:\S+}", allow_head=True)
async def stream_handler(request: web.Request):
try:
path = request.match_info["path"]
match = re.search(r"^([a-zA-Z0-9_-]{6})(\d+)$", path)
if match:
secure_hash = match.group(1)
message_id = int(match.group(2))
else:
message_id = int(re.search(r"(\d+)(?:\/\S+)?", path).group(1))
secure_hash = request.rel_url.query.get("hash")
return await media_streamer(request, message_id, secure_hash)
except InvalidHash as e:
raise web.HTTPForbidden(text=e.message)
except FIleNotFound as e:
raise web.HTTPNotFound(text=e.message)
except (AttributeError, BadStatusLine, ConnectionResetError):
pass
except Exception as e:
logging.critical(e.with_traceback(None))
raise web.HTTPInternalServerError(text=str(e))
class_cache = {}
async def media_streamer(request: web.Request, message_id: int, secure_hash: str):
range_header = request.headers.get("Range", 0)
index = min(work_loads, key=work_loads.get)
faster_client = multi_clients[index]
if Var.MULTI_CLIENT:
logging.info(f"Client {index} is now serving {request.remote}")
if faster_client in class_cache:
tg_connect = class_cache[faster_client]
logging.debug(f"Using cached ByteStreamer object for client {index}")
else:
logging.debug(f"Creating new ByteStreamer object for client {index}")
tg_connect = utils.ByteStreamer(faster_client)
class_cache[faster_client] = tg_connect
logging.debug("before calling get_file_properties")
file_id = await tg_connect.get_file_properties(message_id)
logging.debug("after calling get_file_properties")
if file_id.unique_id[:6] != secure_hash:
logging.debug(f"Invalid hash for message with ID {message_id}")
raise InvalidHash
file_size = file_id.file_size
if range_header:
from_bytes, until_bytes = range_header.replace("bytes=", "").split("-")
from_bytes = int(from_bytes)
until_bytes = int(until_bytes) if until_bytes else file_size - 1
else:
from_bytes = request.http_range.start or 0
until_bytes = request.http_range.stop or file_size - 1
req_length = until_bytes - from_bytes
new_chunk_size = await utils.chunk_size(req_length)
offset = await utils.offset_fix(from_bytes, new_chunk_size)
first_part_cut = from_bytes - offset
last_part_cut = (until_bytes % new_chunk_size) + 1
part_count = math.ceil(req_length / new_chunk_size)
body = tg_connect.yield_file(
file_id, index, offset, first_part_cut, last_part_cut, part_count, new_chunk_size
)
mime_type = file_id.mime_type
file_name = file_id.file_name
disposition = "attachment"
if mime_type:
if not file_name:
try:
file_name = f"{secrets.token_hex(2)}.{mime_type.split('/')[1]}"
except (IndexError, AttributeError):
file_name = f"{secrets.token_hex(2)}.unknown"
else:
if file_name:
mime_type = mimetypes.guess_type(file_id.file_name)
else:
mime_type = "application/octet-stream"
file_name = f"{secrets.token_hex(2)}.unknown"
if "video/" in mime_type or "audio/" in mime_type:
disposition = "inline"
return_resp = web.Response(
status=206 if range_header else 200,
body=body,
headers={
"Content-Type": f"{mime_type}",
"Range": f"bytes={from_bytes}-{until_bytes}",
"Content-Range": f"bytes {from_bytes}-{until_bytes}/{file_size}",
"Content-Disposition": f'{disposition}; filename="{file_name}"',
"Accept-Ranges": "bytes",
},
)
if return_resp.status == 200:
return_resp.headers.add("Content-Length", str(file_size))
return return_resp
<file_sep>/Megatron/bot/plugins/start.py
from pyrogram import filters
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton, Message
from pyrogram.errors import UserNotParticipant
from pyrogram.enums import ParseMode
from Megatron.bot import StreamBot
from Megatron.vars import Var
from Megatron.utils.human_readable import humanbytes
from Megatron.utils.database import Database
from Megatron.handlers.fsub import force_subscribe
db = Database(Var.DATABASE_URL, Var.SESSION_NAME)
@StreamBot.on_message(filters.command('start') & filters.private)
async def start(b, m : Message):
if not await db.is_user_exist(m.from_user.id):
await db.add_user(m.from_user.id)
await b.send_message(
Var.BIN_CHANNEL,
f"#NEW_USER: \n\nNew User [{m.from_user.first_name}](tg://user?id={m.from_user.id}) Started the bot."
)
firstname = m.from_user.first_name
usr_cmd = m.text.split("_")[-1]
if usr_cmd == "/start":
if Var.UPDATES_CHANNEL:
fsub = await force_subscribe(b, m)
if fsub == 400:
return
await m.reply(
text=f"""Hey Dear {m.from_user.mention(style="md")} 🙋🏻♂️\nI'm Telegram File to Link Generator Bot.\n\nSend me any file & get the fast direct download link!\n\n⚠ **Don't forget to read the [rules](https://t.me/FutureTechnologyOfficial/1257) first!**\n\nسلام {m.from_user.mention(style="md")} عزیز 🙋🏻♂️\nمن بات تبدیل فایل به لینک هستم\nفایل تلگرامی خود را ارسال کنید تا لینک دانلود پر سرعت آن را دریافت نمایید\n\n**⚠ لطفا قبل از استفاده از بات [قوانین](https://t.me/FutureTechnologyOfficial/1257) را مطالعه نمایید!**\n\nهمچنین با زدن دستور /nim میتوانید لینک های دریافتی خود را نیم بها نمایید.""",
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton('✵ Updates Channel ✵', url='https://t.me/FutureTechnologyOfficial'), InlineKeyboardButton('✵ Support Group ✵', url='https://t.me/joinchat/riq-psSksFtiMDU8')],
[InlineKeyboardButton('✵ Developer ✵', url='https://t.me/CipherXBot')]
]
),
disable_web_page_preview=True
)
else:
if Var.UPDATES_CHANNEL:
fsub = await force_subscribe(b, m)
if fsub == 400:
return
u = await b.get_chat_member(int(Var.UPDATES_CHANNEL), m.from_user.id)
if u.status == "kicked" or u.status == "banned":
await b.send_message(
chat_id=m.from_user.id,
text="✨ You're Banned due not to pay attention to the [rules](https://t.me/FutureTechnologyOfficial/1257). Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8) if you think you've banned wrongly.\n\n✨ شما به علت عدم رعایت [قوانین](https://t.me/FutureTechnologyOfficial/1257) بن شده اید. اگر فکر میکنید بن شدن شما اشتباه بوده و قوانین را رعایت کرده اید می توانید با [گروه پشتیبانی](https://t.me/joinchat/riq-psSksFtiMDU8) در ارتباط باشید.",
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True
)
@StreamBot.on_message(filters.command('upgrade') & filters.private)
async def upgrade(b, m : Message):
await m.reply(
text=f"""─────────────\n➰ **Daily Plan :**\n✗ 5 days - 5 dollar\n✗ 10 days - 10 dollar\n✗ 20 days - 20 dollar\n••••••••••••••••\n➰ **Monthly Plan :**\n✗ 1 month - 30 dollar\n✗ 3 months - 80 dollar\n✗ 6 months - 150 dollar\n••••••••••••••••\n➰ **Annual Plan :**\n✗ 1 year - 290 dollar\n─────────────\n─────────────\n➰ **پلن ماهانه :**\n✗ 3 ماهه - 80000 تومان\n✗ 6 ماهه - 150000 تومان\n••••••••••••••••\n➰ **پلن سالانه :**\n✗ 1 ساله - 290000 تومان\n─────────────\n✨ برای خرید روی دکمه زیر کلیک کنید""",
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton('✨ Buy & Contact ✨', url='https://t.me/CipherXBot')]
]
),
disable_web_page_preview=True
)
@StreamBot.on_message(filters.command('help') & filters.private)
async def help_handler(b, m : Message):
if not await db.is_user_exist(m.from_user.id):
await db.add_user(m.from_user.id)
await b.send_message(
Var.BIN_CHANNEL,
f"#NEW_USER: \n\nNew User [{m.from_user.first_name}](tg://user?id={m.from_user.id}) Started !!"
)
if Var.UPDATES_CHANNEL:
fsub = await force_subscribe(b, m)
if fsub == 400:
return
u = await b.get_chat_member(int(Var.UPDATES_CHANNEL), m.from_user.id)
if u.status == "kicked" or u.status == "banned":
await b.send_message(
chat_id=m.from_user.id,
text="✨ You're Banned due not to pay attention to the [rules](https://t.me/FutureTechnologyOfficial/1257). Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8) if you think you've banned wrongly.\n\n✨ شما به علت عدم رعایت [قوانین](https://t.me/FutureTechnologyOfficial/1257) بن شده اید. اگر فکر میکنید بن شدن شما اشتباه بوده و قوانین را رعایت کرده اید می توانید با [گروه پشتیبانی](https://t.me/joinchat/riq-psSksFtiMDU8) در ارتباط باشید.",
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True
)
else:
await m.reply_text(
text="✨ Send me any file, I'll give you its direct download link\n\nAlso I'm supported in channels. Add me to channel as admin to make me workable\n\n✨ فایل تلگرامی خود را برای من بفرستید تا لینک دانلود مستقیم آن را برای شما بفرستم\n\nهمچنین با ارتقای من به عنوان ادمین در چنل خود می توانید از امکانات من استفاده کنید، بدین صورت که در زمان پست فایل جدید در چنل دکمه شیشه ای دریافت لینک مستقیم فایل پست شده در زیر پست ایجاد می گردد.",
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True,
reply_markup=InlineKeyboardMarkup(
[
[InlineKeyboardButton("✵ Support Group ✵", url="https://t.me/joinchat/riq-psSksFtiMDU8"), InlineKeyboardButton("✵ Update Channel ✵", url="https://t.me/FutureTechnologyOfficial")],
[InlineKeyboardButton("✵ Developer ✵", url="https://t.me/CipherXBot")]
]
)
)
<file_sep>/Megatron/handlers/fsub.py
#ToxygenX
import asyncio
from pyrogram.errors import FloodWait, UserNotParticipant
from pyrogram.types import InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.enums import ParseMode
from Megatron.vars import Var
from Megatron.utils.callbacks import *
async def force_subscribe(bot, cmd):
try:
invite_link = await bot.create_chat_invite_link(int(Var.UPDATES_CHANNEL))
except FloodWait as e:
await asyncio.sleep(e.x)
return 400
try:
user = await bot.get_chat_member(int(Var.UPDATES_CHANNEL), cmd.from_user.id)
if user.status == "kicked":
await bot.send_message(
chat_id=cmd.from_user.id,
text="✨ You are Banned due not to pay attention to the [rules](https://t.me/FutureTechnologyOfficial/1257). Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8) if you think you've banned wrongly.\n\n✨ شما به علت عدم رعایت [قوانین](https://t.me/FutureTechnologyOfficial/1257) بن شده اید. اگر فکر میکنید بن شدن شما اشتباه بوده و قوانین را رعایت کرده اید می توانید با [گروه پشتیبانی](https://t.me/joinchat/riq-psSksFtiMDU8) در ارتباط باشید.",
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True
)
return 400
except UserNotParticipant:
await bot.send_message(
chat_id=cmd.from_user.id,
text="**✨ Please join updates channel to use me. Only channel subscribers can use the bot.**\n\nAfter joining tap refresh button.\n\n**✨لطفا در چنل عضو شوید. تنها اعضای چنل می توانند از بات استفاده کنند.**\n\nپس از عضویت بر روی دکمه refresh کلیک کنید.",
reply_markup=InlineKeyboardMarkup(
[
[
InlineKeyboardButton("✵ Join Updates Channel ✵", url=invite_link.invite_link)
],
[
InlineKeyboardButton("🔄 Refresh 🔄", callback_data="refreshmeh")
]
]
),
parse_mode=ParseMode.MARKDOWN
)
return 400
except Exception:
await bot.send_message(
chat_id=cmd.from_user.id,
text="Something went Wrong. Contact [Support Group](https://t.me/joinchat/riq-psSksFtiMDU8).",
parse_mode=ParseMode.MARKDOWN,
disable_web_page_preview=True
)
return 400
<file_sep>/Megatron/utils/antispam.py
import time
from Megatron.vars import Var
INTERVAL = {}
async def check_spam(user_id: int):
if str(user_id) in INTERVAL:
now_time = time.time()
last_time = INTERVAL[str(user_id)]
if round(now_time - last_time) < 120 and user_id not in Var.PRO_USERS:
return True, round(last_time - now_time + 120)
elif round(now_time - last_time) >= 120 and user_id not in Var.PRO_USERS:
del INTERVAL[str(user_id)]
return False, None
elif round(now_time - last_time) < 10 and user_id in Var.PRO_USERS:
return True, round(last_time - now_time + 10)
elif round(now_time - last_time) >= 10 and user_id in Var.PRO_USERS:
del INTERVAL[str(user_id)]
return False, None
elif str(user_id) not in INTERVAL:
INTERVAL[str(user_id)] = time.time()
return False, None
<file_sep>/Megatron/bot/clients.py
import asyncio
import logging
from pyrogram import Client
from ..vars import Var
from Megatron.utils import TokenParser
from . import multi_clients, work_loads, StreamBot
async def initialize_clients():
multi_clients[0] = StreamBot
work_loads[0] = 0
all_tokens = TokenParser().parse_from_env()
if not all_tokens:
print("No additional clients found, using default client")
return
async def start_client(client_id, token):
try:
print(f"Starting - Client {client_id}")
if client_id == len(all_tokens):
await asyncio.sleep(2)
print("This will take some time, please wait...")
client = await Client(
name=str(client_id),
api_id=Var.API_ID,
api_hash=Var.API_HASH,
bot_token=token,
sleep_threshold=Var.SLEEP_THRESHOLD,
no_updates=True,
in_memory=True
).start()
work_loads[client_id] = 0
return client_id, client
except Exception:
logging.error(f"Failed starting Client - {client_id} Error:", exc_info=True)
clients = await asyncio.gather(*[start_client(i, token) for i, token in all_tokens.items()])
multi_clients.update(dict(clients))
if len(multi_clients) != 1:
Var.MULTI_CLIENT = True
print("Multi-Client Mode Enabled")
else:
print("No additional clients were initialized, using default client")
<file_sep>/Dockerfile
FROM python:3.9.5-buster
WORKDIR /Megatron
RUN chmod 777 /Megatron
RUN apt-get update -y
RUN pip3 install -U pip
COPY requirements.txt .
RUN pip3 install --no-cache-dir -U -r requirements.txt
COPY . .
CMD python3 -m Megatron
<file_sep>/Megatron/utils/keepalive.py
import asyncio
import logging
import aiohttp
import traceback
from Megatron import Var
async def ping_server():
sleep_time = Var.PING_INTERVAL
while True:
await asyncio.sleep(sleep_time)
try:
async with aiohttp.ClientSession(
timeout=aiohttp.ClientTimeout(total=10)
) as session:
async with session.get(Var.URL) as resp:
logging.info("Pinged server with response: {}".format(resp.status))
except TimeoutError:
logging.warning("Couldn't connect to the site URL..!")
except Exception:
traceback.print_exc()
<file_sep>/Megatron/strings/strings.py
import sys
import logging
from os import listdir, path
from typing import Any, Dict, List, Union
from Megatron.vars import Var
from Megatron.utils.database import Database
db = Database(Var.DATABASE_URL, Var.SESSION_NAME)
try:
from google_trans_new import google_translator
Trs = google_translator()
except ImportError:
LOGS.info("'google_trans_new' not installed!")
Trs = None
try:
from yaml import safe_load
except ModuleNotFoundError:
logging.info("'pyYaml' not installed!\nPlease install it.")
sys.exit()
language = [db.is_trans_exist("language") or "en"]
languages = {}
strings_folder = path.join(path.dirname(path.realpath(__file__)), "strings")
for file in listdir(strings_folder):
if file.endswith(".yml"):
code = file[:-4]
try:
languages[code] = safe_load(
open(path.join(strings_folder, file), encoding="UTF-8"),
)
except Exception as er:
logging.info(f"Error in {file[:-4]} language file")
logging.exception(er)
def get_string(key: str) -> Any:
lang = language[0]
try:
return languages[lang][key]
except KeyError:
try:
en_ = languages["en"][key]
if not Trs:
return en_
tr = Trs.translate(en_, lang_tgt=lang).replace("\ N", "\n")
if en_.count("{}") != tr.count("{}"):
tr = en_
if languages.get(lang):
languages[lang][key] = tr
else:
languages.update({lang: {key: tr}})
return tr
except KeyError:
return f"Warning: could not load any string with the key `{key}`"
except TypeError:
pass
except Exception as er:
logging.exception(er)
return languages["en"].get(key) or f"Failed to load language string '{key}'"
def get_languages() -> Dict[str, Union[str, List[str]]]:
return {
code: {
"name": languages[code]["name"],
"natively": languages[code]["natively"],
"authors": languages[code]["authors"],
}
for code in languages
}
<file_sep>/Megatron/server/exceptions.py
class InvalidHash(Exception):
message = "Invalid hash"
class FIleNotFound(Exception):
message = "File not found"
| b5c211ac731a1a9d0c84202d01284bc49e45b22c | [
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 25 | Python | CipherX1-ops/MegatronFileStream | 8676cf91d8538cb7a562cc4601218f6f0651cf4f | be92192700bf1fc37196a64efb3de1847a597301 | |
refs/heads/master | <file_sep>//
// ViewController.swift
// Calculator
//
// Created by ezios on 15/11/28.
// Copyright (c) 2015年 ezios. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var display: UILabel!
@IBOutlet weak var displayOperation: UILabel!
var isUserIsInTypeing = false
var brain = CalculatorBrain()
//数字键
@IBAction func appendDigit(sender: UIButton) {
var digit = sender.currentTitle!
switch(digit) {
case ".":
//已输入一个小数点将退出
if (display.text!.rangeOfString(digit) != nil) {
return
}
//输入第一个小数点自动在前面加零
if isUserIsInTypeing == false {
digit = "0."
}
default:
break
}
if isUserIsInTypeing {
display.text = display.text! + digit
}else {
display.text = digit
isUserIsInTypeing = true
}
}
//回车键
@IBAction func enter() {
if isUserIsInTypeing {
var displayText = display.text!
//检测是否为负数
if displayText.hasPrefix("-") {
display.text = dropFirst(displayText)
brain.pushOperand(displayValue)
showResult(brain.performOperation("±"))
} else {
showResult(brain.pushOperand(displayValue))
}
}
}
//变量压入键
@IBAction func pushVariable(sender: UIButton) {
showResult(brain.pushOperand(sender.currentTitle!))
}
//变量赋值键
@IBAction func assignmentVariableValue() {
if isUserIsInTypeing {
showResult(brain.pushVariableValue(displayValue))
}
}
//运算符键
@IBAction func operation(sender: UIButton) {
let operatorType = sender.currentTitle!
if isUserIsInTypeing {
enter()
}
showResult(brain.performOperation(operatorType))
}
//正负操作键
@IBAction func negation(sender: UIButton) {
if isUserIsInTypeing {
if display.text!.hasPrefix("-") {
display.text = dropFirst(display.text!)
} else {
display.text = "-" + display.text!
}
} else {
operation(sender)
}
}
//退格键
@IBAction func backspace() {
if isUserIsInTypeing {
display.text = dropLast(display.text!)
if count(display.text!) == 0 {
isUserIsInTypeing = false
displayValue = nil
}
} else {
showResult(brain.undo())
}
}
//运算符键
@IBAction func showOperator(sender: UIButton) {
displayOperation.text = sender.currentTitle!
}
//非运算符键
@IBAction func hideOperator() {
displayOperation.text = ""
}
//清除键 回归初始状态
@IBAction func clear() {
displayValue = nil
brain.reset()
}
//显示结果
func showResult(result: Double?) {
displayValue = result
display.text = brain.description + " = " + display.text!
}
//display的计算属性
var displayValue: Double? {
//get 转换标签显示的文本为double
get {
if let number = NSNumberFormatter().numberFromString(display.text!)?.doubleValue {
return number
}
return nil
}
set {
isUserIsInTypeing = false
if newValue != nil {
display.text = "\(newValue!)"
} else {
display.text = " "
}
}
}
}
<file_sep>//
// CalculatorBrain.swift
// Calculator
//
// Created by ezios on 15/12/5.
// Copyright (c) 2015年 ezios. All rights reserved.
//
import Foundation
class CalculatorBrain {
//存储操作数和操作符的枚举
private enum Op: Printable{
case Operand(Double)
case Variable(String)
case UnitaryOperation(String, Double -> Double)
case BinaryOperation(String, (Double, Double) -> Double)
var description: String {
get {
switch self {
case .Operand(let value):
return "\(value)"
case .Variable(let symbol):
return symbol
case .UnitaryOperation(let symbol, _):
return symbol
case .BinaryOperation(let symbol, _):
return symbol
}
}
}
}
//计算栈
private var opStack = [Op]()
//计算函数字典
private var knownsOps = [String: Op]()
//变量字典
private var variableValues = [String: Double]()
//描述算式
var description: String {
get {
if !opStack.isEmpty {
var (describe, remainder) = evalcuteDescribe(opStack, operation: "first")
println("\(opStack) = \(describe) with \(remainder) left over")
return describe!
}
return ""
}
}
//构造器
init() {
func learnOp(op: Op) {
knownsOps[op.description] = op
}
learnOp(Op.BinaryOperation("×", *))
learnOp(Op.BinaryOperation("÷") { $1 / $0 })
learnOp(Op.BinaryOperation("+", +))
learnOp(Op.BinaryOperation("−") { $1 - $0 })
learnOp(Op.UnitaryOperation("√", sqrt))
learnOp(Op.UnitaryOperation("sin", sin))
learnOp(Op.UnitaryOperation("cos", cos))
learnOp(Op.UnitaryOperation("±", -))
variableValues["π"] = M_PI
}
//递归计算栈中元素
private func evalcuate(ops: [Op]) -> (result: Double?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
switch op {
case .Operand(let result):
return (result, remainingOps)
case .Variable(let symbol):
return (variableValues[symbol], remainingOps)
case .UnitaryOperation(_, let operationFunc):
let operand = evalcuate(remainingOps)
if let result = operand.result {
return (operationFunc(result), operand.remainingOps)
}
case .BinaryOperation(_, let operationFunc):
let operand1 = evalcuate(remainingOps)
if let result1 = operand1.result {
let operand2 = evalcuate(operand1.remainingOps)
if let result2 = operand2.result {
return (operationFunc(result1, result2), operand2.remainingOps)
}
}
}
}
return (nil, ops)
}
//计算栈
func evalcuate() -> Double? {
if !opStack.isEmpty {
let (result, remainder) = evalcuate(opStack)
println("\(opStack) = \(result) with \(remainder) left over")
return result
}
return nil
}
//计算表达式
private func evalcuteDescribe(ops: [Op], operation: String?) -> (describe: String?, remainingOps: [Op]) {
if !ops.isEmpty {
var remainingOps = ops
let op = remainingOps.removeLast()
//最后剩余的栈
var lastOps = remainingOps
//最后输出的描述
var describe: String
switch op {
case .Operand(let value): //操作数直接返回值
describe = "\(value)"
case .Variable(let symbol): //变量直接返回名字
describe = "\(symbol)"
case .UnitaryOperation(let symbol, _): //一元运算符递归出一个操作数后用()包裹并返回
let operand = evalcuteDescribe(remainingOps, operation: "unitary")
if let result = operand.describe {
describe = "\(symbol)(\(result))"
lastOps = operand.remainingOps
} else { //如果没有获取到值使用?来代替
describe = "\(symbol)(?)"
lastOps = operand.remainingOps
}
case .BinaryOperation(let symbol, _): //二元运算符递归出两个操作数 并返回(1 + 2)的格式
let operand1 = evalcuteDescribe(remainingOps, operation: symbol)
//可否优化括号
let isOptimizable = {
() -> Bool in
//第一次计算和一元运算符以及满足结合律的等式无需括号
if operation == "+" || operation == "-" || operation == "unitary" || operation == "first" {
return true
} else if (operation == "×" || operation == "÷") && (symbol == "×" || symbol == "÷") {
return true
} else {
return false
}
}()
if let result1 = operand1.describe {
let operand2 = evalcuteDescribe(operand1.remainingOps, operation: symbol)
if let result2 = operand2.describe {
if isOptimizable {
describe = "\(result2) \(symbol) \(result1)"
} else {
describe = "(\(result2) \(symbol) \(result1))"
}
lastOps = operand2.remainingOps
} else { //如果没有获取到值使用?来代替
if isOptimizable {
describe = "? \(symbol) \(result1)"
} else {
describe = "(? \(symbol) \(result1))"
}
lastOps = operand2.remainingOps
}
} else { //如果没有获取到值使用?来代替
if isOptimizable {
describe = "? \(symbol) ?"
} else {
describe = "(? \(symbol) ?)"
}
lastOps = operand1.remainingOps
}
}
if lastOps.isEmpty { //如果栈已取尽返回结果
return (describe, lastOps)
} else if operation != nil && operation != "first" { //操作符不为空且不是第一次计算时直接返回结果
return (describe, lastOps)
} else { //否则继续递归,并用 , 隔开之前的结果
let (remainingDescrible, remainLastOps) = evalcuteDescribe(lastOps, operation: "first")
return (remainingDescrible! + ", " + describe, remainLastOps)
}
}
return (nil, ops)
}
//操作数入栈
func pushOperand(operand: Double?) -> Double? {
if operand != nil {
opStack.append(Op.Operand(operand!))
return evalcuate()
}
return nil
}
//变量入栈
func pushOperand(symbol: String) -> Double? {
opStack.append(Op.Variable(symbol))
return evalcuate()
}
//变量赋值
func pushVariableValue(operand: Double?) -> Double? {
if operand != nil {
variableValues["M"] = operand!
}
return evalcuate()
}
//运算符入栈
func performOperation(op: String) -> Double? {
if let opertion = knownsOps[op] {
opStack.append(opertion)
}
return evalcuate()
}
//撤销
func undo() -> Double? {
if !opStack.isEmpty {
opStack.removeLast()
}
return evalcuate()
}
//重置计算器 返回初始状态
func reset() {
if !opStack.isEmpty {
opStack.removeAll()
}
if variableValues["M"] != nil {
variableValues["M"] = nil
}
}
}
| eac9884814a4f6b5a0d582d5290b65735c901a04 | [
"Swift"
] | 2 | Swift | linayanse/Calculator | f818ca61304dc4bbe4a60c006a1591b57b0582fe | 75fbeb9cfdff13ad2adac442e8fb0d7d67afaff8 | |
refs/heads/main | <file_sep># NZXT H1 OpenCore
Hackintosh EFI/Kexts for NZXT-H1 AMD Ryzen 5 3600 Mhz/AsRock X570 Phantom Gaming/3600 Mhz DDR4 32GB with NVidia Titan Black Kepler GPU for Apple Big Sur.
### Hardware
Aforementioned SSDT/Kexts installer for the following hardware.
* AMD Ryzen 5 3600 6-Core Processor
* X570 Phantom Gaming-ITX/TB3
* SMBIOS 3.2.0
* Intel Wi-Fi 6 AX200
* Intel I211 Gigabit Network Connection
* ADATA XPG SX8200 Pro PCIe Gen3x4 M.2 2280 Solid State Drive, ADATA SX8200PNP
* ALC1220 Analog [ALC1220 Analog]
* ALC1220 Digital [ALC1220 Digital]
* AMD FCH SATA Controller [AHCI mode]
* NVidia Titan Black (Kepler)
### Linux Commands
Summary of system hardware prior to the install.
```bash
#!/usr/bin/env bash
hw=(
"cat /proc/cpuinfo | grep 'model name'"
"lspci | grep -i --color 'vga\|3d\|2d'"
"dmidecode -t baseboard"
"dmesg |grep -i 'input'"
"aplay -l"
"lspci | grep -i 'network'"
"lshw -class network"
"lshw -class disk -class storage"
)
for i in "${hw[@]}"
do
$i >> '\n' >> open-core-hw-output.txt
done
```
### Disclaimer
`It works swell, and it is possible to use this config blindly. However, this comes with no-tech support.`
<file_sep>#!/usr/bin/env bash
hw=(
"cat /proc/cpuinfo | grep 'model name'"
"lspci | grep -i --color 'vga\|3d\|2d'"
"dmidecode -t baseboard"
"dmesg |grep -i 'input'"
"aplay -l"
"lspci | grep -i 'network'"
"lshw -class network"
"lshw -class disk -class storage"
)
for i in "${hw[@]}"
do
$i >> '\n' >> open-core-hw-output.txt
done
| 1e2874dc3a27b5f4a418606b3af7a82681c32072 | [
"Markdown",
"Shell"
] | 2 | Markdown | pleasemarkdarkly/OpenCore-AMD-5-3600-AsRock-X570-Phantom-Gaming | 1b9e18ef24279d8173de6cddb822b47ac81e87e6 | 1c2a2794c7c7b56100379d9b9ab4c806d28973b7 | |
refs/heads/master | <file_sep># Przykładowa aplikacja z użyciem AngularJS
Przykładowa aplikacja w stylu: `Single Page Application`.<br />
Demonstracja jak łatwo stworzyć aplikację SPA.
## Budowa aplikacji
```
.
├── README.md
├── app
│ ├── index.html
│ └── scripts
│ ├── bootstrap.js
│ ├── main.js
│ ├── modules
│ │ └── simpleAngularApp
│ │ ├── controller
│ │ │ └── MainController.js
│ │ ├── index.js
│ │ ├── module.js
│ │ └── views
│ │ ├── about.html
│ │ ├── contact.html
│ │ └── home.html
│ └── vendor
│ ├── angular
│ │ ├── angular-ui-router.js
│ │ └── angular.js
│ └── require
│ ├── domReady.js
│ └── require.js
└── package.json
9 directories, 15 files
```
## Biblioteki
* [Angular.js](https://angularjs.org/)
* [Require.js](http://requirejs.org/)
<file_sep>define(function (require) {
'use strict';
var ng = require('angular');
require('uiRouter');
var simpleAngularApp = ng.module('simpleAngularApp', [
'ui.router'
]);
simpleAngularApp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/home',
templateUrl: './scripts/modules/simpleAngularApp/views/home.html'
})
.state('about', {
url: '/about',
templateUrl: './scripts/modules/simpleAngularApp/views/about.html'
})
.state('contact', {
url: '/contact',
templateUrl: './scripts/modules/simpleAngularApp/views/contact.html'
});
$urlRouterProvider.otherwise('home');
});
return simpleAngularApp;
});
| 25a148ac73d220a9171513e287c600258f4236cc | [
"Markdown",
"JavaScript"
] | 2 | Markdown | piecioshka/sample-angular-app | fe0fab5b7d46462f9730fd152e1f8f247655143d | 279392394b1fc30dca3a2e222764047f750d6c10 | |
refs/heads/master | <repo_name>cavigna/CheckApartment_Kotlin<file_sep>/app/src/main/java/com/example/checkapartmentkt/model/Departamento.kt
package com.example.checkapartmentkt.model
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
@Entity(tableName = "departamentos")
data class Departamento(
@PrimaryKey(autoGenerate = true)
var id: Int = 1,
val nombre : String,
val unidad : String,
val direccion : String,
val urlFoto : String,
val luces :Int,
val bath : Int,
val cocina: Int,
val dormitorio : Int,
val terminaciones : Int,
var puntaje : Int ,
){
//constructor():this(id=0)
fun calcularPuntaje(){
this.puntaje = (this.luces + this.bath + this.cocina + this.dormitorio) * this.terminaciones
}
//(luces + bath + cocina + dormitorio) * terminaciones
}
<file_sep>/app/src/main/java/com/example/checkapartmentkt/fragments/ui/ListFragment.kt
package com.example.checkapartmentkt.fragments.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.checkapartmentkt.R
import com.example.checkapartmentkt.adapter.DeptoListAdapter
import com.example.checkapartmentkt.databinding.FragmentListBinding
import com.example.checkapartmentkt.viewmodel.DeptoViewModel
class ListFragment : Fragment() {
private lateinit var binding: FragmentListBinding
//private val viewModel:DeptoViewModel = ViewModelProvider(requireActivity()).get(DeptoViewModel::class.java)
private val viewModel: DeptoViewModel by activityViewModels()
val adapter = DeptoListAdapter()
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentListBinding.inflate(inflater, container, false)
val recyclerView = binding.recyclerView
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(this.requireContext())
viewModel.allDepartamento.observe(viewLifecycleOwner){ departamentos ->
departamentos.let { adapter.submitList(departamentos) }
}
return binding.root
}
// override fun onCreate(savedInstanceState: Bundle?) {
// super.onCreate(savedInstanceState)
// //viewModel = ViewModelProvider(requireActivity()).get(DeptoViewModel::class.java)
//
// }
}
<file_sep>/app/src/main/java/com/example/checkapartmentkt/dao/DepartamentoDao.kt
package com.example.checkapartmentkt.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Update
import com.example.checkapartmentkt.model.Departamento
import kotlinx.coroutines.flow.Flow
@Dao
interface DepartamentoDao {
@Insert
suspend fun agregarDeaprtamento(dpto :Departamento)
@Update
suspend fun actualizarDepartamento(depto: Departamento)
@Query("SELECT * FROM departamentos")
fun allDeptos() : Flow<List<Departamento>>
}<file_sep>/app/src/main/java/com/example/checkapartmentkt/db/BaseDeDatos.kt
package com.example.checkapartmentkt.db
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import com.example.checkapartmentkt.dao.DepartamentoDao
import com.example.checkapartmentkt.model.Departamento
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Database(entities = [Departamento::class], version = 1, exportSchema = false)
abstract class BaseDeDatos : RoomDatabase() {
abstract fun dao(): DepartamentoDao
companion object {
@Volatile
private var INSTANCE: BaseDeDatos? = null
fun getBaseDeDatos(context: Context, scope: CoroutineScope): BaseDeDatos {
return INSTANCE ?: synchronized(this) {
val instance = Room.databaseBuilder(
context.applicationContext,
BaseDeDatos::class.java,
"db_deparamentods"
)
.addCallback(DeptoCallback(scope))
.build()
INSTANCE = instance
instance
}
}
}
private class DeptoCallback(private val scope: CoroutineScope) : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
INSTANCE?.let { baseDeDatos ->
scope.launch {
popularBaseDatos(baseDeDatos.dao())
}
}
}
suspend fun popularBaseDatos(dao: DepartamentoDao) {
val listado = listOf(
Departamento(
nombre = "<NAME>",
unidad = "505",
direccion = "San Martín 970",
urlFoto = "https://http2.mlstatic.com/D_NQ_NP_927221-MLC45497689153_042021-O.webp",
bath = 0, luces = 0, cocina = 0, dormitorio = 0, terminaciones = 0, puntaje = 0
),
Departamento(
nombre = "<NAME>",
unidad = "709",
direccion = "Zeneto 1252",
urlFoto = "https://http2.mlstatic.com/D_NQ_NP_852648-MLC41532980127_042020-O.webp",
bath = 0, luces = 0, cocina = 0, dormitorio = 0, terminaciones = 0, puntaje = 0
),
Departamento(
nombre = "<NAME>",
unidad = "312",
direccion = "Santa Isabel 330",
urlFoto = "https://http2.mlstatic.com/D_NQ_NP_787028-MLC41467659060_042020-O.webp",
bath = 0, luces = 0, cocina = 0, dormitorio = 0, terminaciones = 0, puntaje = 0
),
Departamento(
nombre = "<NAME>",
unidad = "404",
direccion ="Eyzaguirre 771",
urlFoto = "https://http2.mlstatic.com/D_NQ_NP_940668-MLC45093828481_032021-O.webp",
bath = 0, luces = 0, cocina = 0, dormitorio = 0, terminaciones = 0, puntaje = 0
),
)
for(depto in listado){
dao.agregarDeaprtamento(depto)
}
}
}
}
<file_sep>/app/src/main/java/com/example/checkapartmentkt/adapter/DeptoListAdapter.kt
package com.example.checkapartmentkt.adapter
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.example.checkapartmentkt.R
import com.example.checkapartmentkt.adapter.DeptoListAdapter.DeptoViewHolder
import com.example.checkapartmentkt.databinding.ItemRowBinding
import com.example.checkapartmentkt.model.Departamento
class DeptoListAdapter : ListAdapter<Departamento, DeptoViewHolder>(DeptoComparador()) {
class DeptoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val binding = ItemRowBinding.bind(itemView)
val tvNombre = binding.tvNombreRow;
val tvUnidad = binding.tvUnidadRow;
val tvDireccion = binding.tvDireccionRow;
val tvPuntaje = binding.tvPuntajeRow;
val imagenDpto = binding.imgViewRow;
companion object {
fun create(parent: ViewGroup): DeptoViewHolder {
val view: View = LayoutInflater.from(parent.context)
.inflate(R.layout.item_row, parent, false)
return DeptoViewHolder(view)
}
}
fun unirDatos(depto: Departamento) {
tvNombre.text = depto.nombre
tvDireccion.text = depto.direccion
tvPuntaje.text = depto.puntaje.toString()
tvUnidad.text = depto.unidad
Glide.with(itemView).load(depto.urlFoto).fitCenter().into(imagenDpto)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DeptoViewHolder {
return DeptoViewHolder.create(parent)
}
override fun onBindViewHolder(holder: DeptoViewHolder, position: Int) {
val depto = getItem(position)
holder.unirDatos(depto)
}
}
class DeptoComparador : DiffUtil.ItemCallback<Departamento>() {
override fun areItemsTheSame(oldItem: Departamento, newItem: Departamento): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Departamento, newItem: Departamento): Boolean {
return oldItem.id == newItem.id
}
}
<file_sep>/app/src/main/java/com/example/checkapartmentkt/viewmodel/DeptoViewModel.kt
package com.example.checkapartmentkt.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.asLiveData
import com.example.checkapartmentkt.model.Departamento
import com.example.checkapartmentkt.repository.Repository
class DeptoViewModel(private val repository: Repository) : ViewModel() {
val allDepartamento : LiveData<List<Departamento>> = repository.allDeptos.asLiveData()
suspend fun acutalizarDepartamento(depto: Departamento){
repository.actualizarDepartamento(depto)
}
}
class DeptoViewModelFactory(private val repository: Repository) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(DeptoViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return DeptoViewModel(repository) as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}<file_sep>/app/src/main/java/com/example/checkapartmentkt/application/DepartamentoApplication.kt
package com.example.checkapartmentkt.application
import android.app.Application
import com.example.checkapartmentkt.db.BaseDeDatos
import com.example.checkapartmentkt.repository.Repository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.SupervisorJob
class DepartamentoApplication : Application() {
val applicationScope = CoroutineScope(SupervisorJob())
val baseDeDatos by lazy { BaseDeDatos.getBaseDeDatos(this, applicationScope) }
val repository by lazy { Repository(baseDeDatos.dao()) }
}<file_sep>/app/src/main/java/com/example/checkapartmentkt/repository/Repository.kt
package com.example.checkapartmentkt.repository
import androidx.annotation.WorkerThread
import com.example.checkapartmentkt.dao.DepartamentoDao
import com.example.checkapartmentkt.model.Departamento
import kotlinx.coroutines.flow.Flow
class Repository (private val dao: DepartamentoDao){
val allDeptos : Flow<List<Departamento>> = dao.allDeptos()
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun agregarDepartamento(depto: Departamento){
dao.agregarDeaprtamento(depto)
}
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun actualizarDepartamento(depto: Departamento){
dao.actualizarDepartamento(depto)
}
}<file_sep>/app/src/main/java/com/example/checkapartmentkt/MainActivity.kt
package com.example.checkapartmentkt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.navigation.fragment.NavHostFragment
import com.example.checkapartmentkt.application.DepartamentoApplication
import com.example.checkapartmentkt.databinding.ActivityMainBinding
import com.example.checkapartmentkt.viewmodel.DeptoViewModel
import com.example.checkapartmentkt.viewmodel.DeptoViewModelFactory
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
val viewModel: DeptoViewModel by viewModels{
DeptoViewModelFactory((application as DepartamentoApplication).repository)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.fragmentContainerView) as NavHostFragment
val navController = navHostFragment.navController
}
} | f2323de77916732260a36400d2ef675824173eb2 | [
"Kotlin"
] | 9 | Kotlin | cavigna/CheckApartment_Kotlin | c05eb4576ffdabf4be1672e7d6313fa280692b90 | ec2e96fbc33a70539602f308de88ebac30c853df | |
refs/heads/master | <repo_name>abburishiva/es6-node<file_sep>/dist/controller/subject.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _subject = require('../models/subject');
var _subject2 = _interopRequireDefault(_subject);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var SubjectsController = function () {
function SubjectsController() {
_classCallCheck(this, SubjectsController);
}
_createClass(SubjectsController, [{
key: 'get',
value: function get(req, res) {
_subject2.default.find(function (err, result) {
res.status(200).json(result);
});
}
}]);
return SubjectsController;
}();
exports.default = new SubjectsController();<file_sep>/app.js
import express from 'express'
import bodyParser from 'body-parser';
import routes from './routes/index';
class App {
constructor() {
this.express = express();
this.dataCarriers();
this.mountRoutes();
this.headers();
}
dataCarriers() {
this.express.use(bodyParser.urlencoded({ extended: false }));
this.express.use(bodyParser.json());
}
headers() {
this.express.use(function (req, res, next) {
if (req.url.substr(-1) === '/') {
return res.send({
message: "Welcome To TalentScreen!"
});
}
next();
});
}
mountRoutes() {
this.express.use('/v1', routes)
}
}
export default new App().express<file_sep>/routes/index.js
import express from 'express';
const router = express.Router();
import subject from './subject';
router.use('/subjects', subject);
export default router;<file_sep>/routes/subject.js
import express from 'express';
import subJectController from '../controller/subject';
import middlewareAuth from '../utils/auth/middleAuth';
const router = express.Router();
router.get('/', middlewareAuth, subJectController.get);
export default router;<file_sep>/models/subject.js
import connection from '../utils/db/mySqlConnection';
class SubjectModel {
constructor() {
this.dbMySQL = connection;
this.tableOnly = "select s.*,CASE s.flag WHEN 0 THEN 'false' WHEN 1 THEN 'true' END AS flag ,DATE_FORMAT(s.lastmoddatetime,'%b %d %Y %h:%i %p') as lastmoddatetime from subject s,common_category cc where s.categoryid=cc.id";
this.deatailTableSQL = "s.id, s.name, s.description ,s.mode ,s.template,s.test_framework ,s.codemirror_theme, s.icon_class,cc.id as common_category__id,cc.name as common_category__name, cc.display_name as common_category__display_name, cc.entityid as common_category__entityid,cc.description as common_category__description,cc.enabled as common_category__enabled";
this.tableWithDependenciesSQL = this.tableOnly.replace("s.*", this.deatailTableSQL);
}
find(callback) {
this.dbMySQL.query(this.tableOnly, (err, results) => {
callback(err, results);
});
}
}
export default new SubjectModel();<file_sep>/utils/auth/middleAuth.js
import express from 'express';
const middlewareAuth = (req, res, next) => {
next();
}
export default middlewareAuth;<file_sep>/dist/test/config/mochaConfig.js
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _mocha = require('mocha');
var _mocha2 = _interopRequireDefault(_mocha);
var _chai = require('chai');
var _chai2 = _interopRequireDefault(_chai);
var _chaiHttp = require('chai-http');
var _chaiHttp2 = _interopRequireDefault(_chaiHttp);
var _app = require('../../app.js');
var _app2 = _interopRequireDefault(_app);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
_chai2.default.use(_chaiHttp2.default);
var expect = _chai2.default.expect;
var MochaConfig = function MochaConfig() {
_classCallCheck(this, MochaConfig);
this.chai = _chai2.default;
this.expect = expect;
this.app = _app2.default;
};
exports.default = new MochaConfig();<file_sep>/utils/db/mySqlConnection.js
import mysql from 'mysql';
import config from '../../config/config';
const connection = mysql.createPool({
host: config.dev.mysql.host,
port: config.dev.mysql.port,
user: config.dev.mysql.username,
password: config.dev.mysql.password,
database: config.dev.mysql.database
});
export default connection; | a9eb7d41030175310a7538957caa32bea937b58e | [
"JavaScript"
] | 8 | JavaScript | abburishiva/es6-node | a92cb1ed2e3bf7b62bb7fdb719a50ee972762a5a | 646ff31e95fff8a9de7ed2575f1bb47629906706 | |
refs/heads/master | <file_sep>using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections.ObjectModel;
using static Week12SampleApp.Models.WeatherItemModel;
using Week12SampleApp.Models;
namespace Week12SampleApp.ViewModels
{
public class MainPageViewModel : BindableBase, INavigationAware
{
public DelegateCommand<WeatherItem> RemoveWeatherItemCommand { get; set; }
public DelegateCommand NavigatePageCommand { get; set; }
private string _title;
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
private ObservableCollection<WeatherItem> _weatherCollection = new ObservableCollection<WeatherItem>();
public ObservableCollection<WeatherItem> WeatherCollection
{
get { return _weatherCollection; }
set { SetProperty(ref _weatherCollection, value); }
}
INavigationService _navigationService;
public MainPageViewModel(INavigationService navigationService)
{
_navigationService = navigationService;
RemoveWeatherItemCommand = new DelegateCommand<WeatherItem>(RemoveWeatherItem);
NavigatePageCommand = new DelegateCommand(NavigatePage);
}
private void NavigatePage()
{
_navigationService.NavigateAsync("NavigationSamplePage");
}
private void RemoveWeatherItem(WeatherItem itemToDelete)
{
WeatherCollection.Remove(itemToDelete);
}
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
Title = "Week 12 Sample App";
}
public void OnNavigatingTo(NavigationParameters parameters)
{
}
}
}
<file_sep>using Xamarin.Forms;
namespace Week12SampleApp.Views
{
public partial class NavigationSamplePage : ContentPage
{
public NavigationSamplePage()
{
InitializeComponent();
}
}
}
<file_sep>using NUnit.Framework;
using System;
using static Week12SampleApp.Models.WeatherItemModel;
using Week12SampleApp.ViewModels;
using Prism.Navigation;
using Moq;
namespace Week12SampleApp.UnitTests
{
[TestFixture()]
public class MainPageViewModelTests
{
MainPageViewModel mainPageViewModel;
Mock<INavigationService> navigationServiceMock;
[SetUp]
public void Init()
{
navigationServiceMock = new Mock<INavigationService>();
mainPageViewModel = new MainPageViewModel(navigationServiceMock.Object);
}
[Test]
public void TestRemoveWeatherItemCommandRemovesWeatherItemFromCollection()
{
var weatherItemToDelete = new WeatherItem();
weatherItemToDelete.Name = "<NAME>";
mainPageViewModel.WeatherCollection.Add(weatherItemToDelete);
mainPageViewModel.RemoveWeatherItemCommand.Execute(weatherItemToDelete);
CollectionAssert.DoesNotContain(mainPageViewModel.WeatherCollection,
weatherItemToDelete);
}
[Test]
public void TestOnNavigatedToPopulatesTitle()
{
mainPageViewModel.Title = string.Empty;
mainPageViewModel.OnNavigatedTo(null);
Assert.AreEqual("Week 12 Sample App", mainPageViewModel.Title);
}
[Test]
public void TestNavigatePageCommandCallsNavigateAsync()
{
navigationServiceMock.Setup(ns => ns.NavigateAsync(It.IsAny<string>(), It.IsAny<NavigationParameters>(),
It.IsAny<bool?>(), It.IsAny<bool>()));
mainPageViewModel.NavigatePageCommand.Execute();
navigationServiceMock.Verify(ns=> ns.NavigateAsync("NavigationSamplePage", It.IsAny<NavigationParameters>(),
It.IsAny<bool?>(), It.IsAny<bool>()), Times.Once());
}
}
}
| b88182dd20a66e74bd04b3afa5c6adc83e9d09ee | [
"C#"
] | 3 | C# | tdesmond-CSUSM/Week12SampleApp | a21d56694517c69a14bead602b121f190a58d8ec | d9609fef1a577f418343f3ce0e830d45abc22948 | |
refs/heads/master | <repo_name>ipa-jfh/robot_recorder_tutorials<file_sep>/record_trajectory/scripts/record
#!/usr/bin/env python
import rospy
from recordit.client import Recorder
from record_trajectory.move_trajectory import Manipulator
def main():
rospy.init_node("recorder_example", anonymous=False)
robot = Manipulator()
robot.move_to_start()
with Recorder():
robot.move_trajectory()
robot.move_to_start()
if __name__ == "__main__":
main()
<file_sep>/README.md
# Tutorials for RecordIt
[](https://travis-ci.org/ipa-jfh/robot_recorder_tutorials)
## Related packages
- RecordIt: https://github.com/ipa-jfh/robot_recorder
- urdf-loader: https://github.com/gkjohnson/urdf-loaders
- urdf-animation: https://github.com/ipa-jfh/urdf-animation
- get_urdf_deps: https://github.com/ipa-jfh/get_urdf_deps
## 1. record_trajectory
### Result
<a href="https://ipa-jfh.github.io/urdf-animation/manipulator_ur5/result/">
<img src="https://user-images.githubusercontent.com/17281534/46701301-8f98ac00-cc1f-11e8-8ee1-af82548453d2.gif" width="249" height="211" >
</a>
[>> See 3D animation](https://ipa-jfh.github.io/urdf-animation/manipulator_ur5/result/)
### How to
1. __Install example__
```bash
# Optionally create a new ROS workspace
mkdir -p ~/record_ws/src && cd ~/record_ws/src
# Download repositories
git clone https://github.com/ipa-jfh/robot_recorder_tutorial.git
wstool init .
wstool merge ~/record_ws/src/robot_recorder_tutorial/.rosinstall
wstool up
# Build workspace
source /opt/ros/kinetic/setup.bash
rosdep update && rosdep install --from-paths ~/record_ws/src --ignore-src
cd ~/record_ws && catkin build
source ~/record_ws/devel/setup.bash
```
2. __Record example__
`(auto)`
```bash
roslaunch record_trajectory record_auto.launch
```
or
`(manual - with RViz plugin)`
TODO
Files are saved to `~/.ros/test_animation/`
3. __Create 3d web animation__
Make sure to download/install nodejs/npm from https://nodejs.org/en/
```bash
cd ~/.ros/test_animation/
npm install # install all deps of the npm project
cp -r ./node_modules/urdf-animation/template/* .
npm start
```
4. __Create GIF__
In the webpage press _Record recording_ at the control-box in upper right corner.
Set _quality_ (lower is better) and _speed_ and then press _record()_.
Done.
5. __Publish interactive web animation__
To publish the web animation you have to bundle the js files first:
```bash
cd ~/.ros/test_animation/
npm run build # Might show errors which should be fine
firefox ~/.ros/test_animation/result/index.html # test
```
The folder `./result` has the self-contained webpage, which you can host e.g. on [gh-pages](https://help.github.com/articles/configuring-a-publishing-source-for-github-pages/).
<file_sep>/record_trajectory/scripts/execute
#!/usr/bin/env python
import rospy
from record_trajectory.move_trajectory import Manipulator
def main():
rospy.init_node("recorder_example", anonymous=False)
robot = Manipulator()
while not rospy.is_shutdown():
robot.move_trajectory()
if __name__ == "__main__":
main()
<file_sep>/record_trajectory/CMakeLists.txt
cmake_minimum_required(VERSION 2.8.3)
project(record_trajectory)
find_package(catkin REQUIRED)
catkin_package()
catkin_python_setup()
catkin_install_python(PROGRAMS scripts/execute
DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION})
install(DIRECTORY launch urdf
DESTINATION ${CATKIN_PACKAGE_SHARE_DESTINATION})<file_sep>/record_trajectory/src/record_trajectory/move_trajectory.py
#!/usr/bin/env python
# This is script is solely for simulation!
# Robot and RecordIt has to be launched prior to this script.
import sys
import rospy
import moveit_commander
from moveit_msgs.msg import MoveGroupAction
from actionlib import SimpleActionClient
class ManipulatorBase:
def __init__(self, move_group):
moveit_commander.roscpp_initialize(sys.argv)
robot = moveit_commander.RobotCommander()
self.group = moveit_commander.MoveGroupCommander(move_group)
self.waypoints = []
self.wait = 0.0
def move_to(self, joint_goal):
self.group.go(joint_goal, wait=True)
def move_to_start(self):
self.move_to(self.waypoints[0])
def move_trajectory(self):
for wp in self.waypoints:
if rospy.is_shutdown():
break
self.move_to(wp)
rospy.sleep(self.wait)
class Manipulator(ManipulatorBase):
def __init__(self):
move_group = rospy.get_param("~move_group", "manipulator")
ManipulatorBase.__init__(self, move_group)
self.wait = rospy.get_param("~wait", 0.1)
self.waypoints = rospy.get_param(
"~waypoints",
[
[-5.1, -1.1, 0.8, -1.0, 1.5, -6.0],
[-5.2, -1.0, 2.1, -2.5, 1.9, -5.5],
[-4.9, -0.7, 0.8, -1.7, 1.6, -5.9],
],
)
| 14d028b139db811d8176bf785694481152ad8ba0 | [
"Markdown",
"Python",
"CMake"
] | 5 | Python | ipa-jfh/robot_recorder_tutorials | 588b48554c4516d700babc1b09bf79025f19ffb1 | 81caddc59d79911fc4f9dab051cf07dc76b038c4 | |
refs/heads/master | <file_sep>package org.uva.sea.ql.parser.test;
import static org.junit.Assert.assertEquals;
import java.util.HashMap;
import java.util.Map;
import org.junit.Test;
import org.uva.sea.ql.parser.antlr.ANTLRParser;
import org.uva.sea.ql.visitor.evaluator.ExprEvaluator;
import org.uva.sea.ql.visitor.evaluator.values.BoolValue;
import org.uva.sea.ql.visitor.evaluator.values.DecValue;
import org.uva.sea.ql.visitor.evaluator.values.IntValue;
import org.uva.sea.ql.visitor.evaluator.values.Value;
public class TestExpressionEvaluator {
private ANTLRParser parser;
private final Map<String,Value> runTimeValues;
public TestExpressionEvaluator() {
parser = new ANTLRParser();
this.runTimeValues=new HashMap<String,Value>();
}
@Test
public void testBinAlgebraic() throws ParseError {
runTimeValues.put("IntVal",new IntValue(100));
assertEquals(new IntValue(136).getValue() , ((IntValue) ExprEvaluator.eval(parser.parseExpr("(3 * 12)+IntVal"),runTimeValues)).getValue() );
assertEquals(new IntValue(120).getValue(), ((IntValue) ExprEvaluator.eval(parser.parseExpr("IntVal + (200 * 10)/(200 - 100)"),runTimeValues)).getValue() );
runTimeValues.put("DecimalVal",new DecValue(100.0f));
assertEquals(139.0, ((DecValue) ExprEvaluator.eval(parser.parseExpr("DecimalVal+(3.0 * 13.0)"),runTimeValues)).getValue() ,0.0);
assertEquals(120.0, ((DecValue) ExprEvaluator.eval(parser.parseExpr("DecimalVal + (200.0 * 10.0)/(200.0 - 100.0)"),runTimeValues)).getValue(),0.0 );
}
@Test
public void testBinBool() throws ParseError {
runTimeValues.put("TRUE",new BoolValue(true));
System.out.println(((BoolValue) ExprEvaluator.eval(parser.parseExpr("136 == 136"),runTimeValues)).getValue());
assertEquals(true , ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((3 * 12) + 100) == 136"),runTimeValues)).getValue() );
assertEquals(true , ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((3 * 12) + 100) >= 136"),runTimeValues)).getValue() );
assertEquals(true , ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((3 * 12) + 100) <= 136"),runTimeValues)).getValue() );
assertEquals(false , ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((3 * 12) + 100) != 136"),runTimeValues)).getValue() );
assertEquals(false , ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((3 * 12) + 100) > 136"),runTimeValues)).getValue() );
assertEquals(false , ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((3 * 12) + 100) < 136"),runTimeValues)).getValue() );
assertEquals(true, ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((100 + (200 * 10)/(200 - 100)) == 120) && TRUE"),runTimeValues)).getValue() );
assertEquals(false, ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((100 + (200 * 10)/(200 - 100)) != 120) && TRUE"),runTimeValues)).getValue() );
runTimeValues.put("FALSE",new BoolValue(false));
assertEquals(false, ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((100 + (200 * 10)/(200 - 100)) == 120) && FALSE"),runTimeValues)).getValue() );
assertEquals(true, ((BoolValue) ExprEvaluator.eval(parser.parseExpr("((100 + (200 * 10)/(200 - 100)) == 120) || FALSE"),runTimeValues)).getValue() );
}
@Test
public void testUnary() throws ParseError {
runTimeValues.put("IntVal",new IntValue(100));
assertEquals(new IntValue(136).getValue() , ((IntValue) ExprEvaluator.eval(parser.parseExpr("(-3 * -12)+IntVal"),runTimeValues)).getValue() );
assertEquals(new IntValue(-120).getValue(), ((IntValue) ExprEvaluator.eval(parser.parseExpr("-IntVal + (200 * -10)/(200 - 100)"),runTimeValues)).getValue() );
runTimeValues.put("DecimalVal",new DecValue(100.0f));
assertEquals(-139.0, ((DecValue) ExprEvaluator.eval(parser.parseExpr("-DecimalVal+(-3.0 * 13.0)"),runTimeValues)).getValue() ,0.0);
assertEquals(120.0, ((DecValue) ExprEvaluator.eval(parser.parseExpr("DecimalVal + (-200.0 * -10.0)/(200.0 - 100.0)"),runTimeValues)).getValue(),0.0 );
}
}
<file_sep>package org.uva.sea.ql.gui.qlform;
import java.awt.Dimension;
import java.util.List;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import org.uva.sea.ql.ast.expr.Expr;
import org.uva.sea.ql.gui.qlform.interpreter.VariableUpdater;
import org.uva.sea.ql.visitor.evaluator.ExprEvaluator;
import org.uva.sea.ql.visitor.evaluator.values.BoolValue;
import org.uva.sea.ql.visitor.evaluator.values.Value;
@SuppressWarnings("serial")
public abstract class QLConditionalBody extends JPanel implements Observer, QLContainerComponent{
private final List<JPanel> questionPanelList;
private Map<String,Value> runTimeValues;
private final VariableUpdater varUpdater;
private final Expr condition;
private final boolean isElseBody;
public QLConditionalBody(List<JPanel> questionPanelList,Expr condition,VariableUpdater varUpdater,Map<String,Value> runTimeValues,boolean isElseBody){
super(new MigLayout("fill,insets 0"));
this.questionPanelList=questionPanelList;
this.runTimeValues=runTimeValues;
this.varUpdater=varUpdater;
this.varUpdater.addObserver(this);
this.condition=condition;
this.isElseBody=isElseBody;
setSettings();
}
private void setSettings(){
this.setMinimumSize(new Dimension(617, 40));
this.setOpaque(false);
fillPanel();
setVisibility(runTimeValues);
}
private void fillPanel(){
for(JPanel questionPanel:questionPanelList){
this.add(questionPanel,"align label,wrap");
}
}
public JPanel getPanel(){
return this;
}
@Override
public void update(Observable arg0, Object arg1) {
setVisibility(varUpdater.getUpdatedValues());
}
private void setVisibility(Map<String,Value> runTimeValues){
boolean isVisible=((BoolValue) ExprEvaluator.eval(condition, runTimeValues)).getValue();
if(isElseBody){
this.setVisible(!isVisible);
return;
}
this.setVisible(isVisible);
}
}
<file_sep>package org.uva.sea.ql.gui.ide;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class IDEFrame extends JFrame {
private final static ImageIcon imgIcon = new ImageIcon(IDEFrame.class.getResource("/org/uva/sea/ql/gui/ide/icons/logo.png"));
public IDEFrame() {
setSettings();
}
private void setSettings() {
this.setIconImage(imgIcon.getImage());
this.setLocation(50, 90);
this.setTitle("QL Editor");
this.setLayout(new MigLayout());
this.setSize(new Dimension(575, 470));
this.setResizable(false);
this.getContentPane().setBackground(Color.LIGHT_GRAY);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
<file_sep>package org.uva.sea.ql.gui.qlform;
import java.awt.Color;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class QLContentPanel extends JPanel implements QLContainerComponent {
public QLContentPanel(){
setSettings();
}
private void setSettings(){
this.setLayout(new MigLayout("hidemode 1"));
this.setBackground(Color.black);
}
@Override
public boolean isConditionalBody() {
return false;
}
@Override
public boolean isPanel() {
return true;
}
}
<file_sep>package org.uva.sea.ql.gui.qlform.output;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.uva.sea.ql.gui.qlform.interpreter.VariableUpdater;
import org.uva.sea.ql.visitor.evaluator.values.Value;
public class QLOutputState {
private final List<String> questionLabels;
private final List<String> questionValues;
private boolean hasError = false;
private VariableUpdater varUpdater;
public QLOutputState(VariableUpdater varUpdater) {
this.varUpdater=varUpdater;
questionLabels = new ArrayList<String>();
questionValues = new ArrayList<String>();
}
public void addValue(String value) {
questionValues.add(value);
}
public void addLabelText(String value) {
questionLabels.add(value);
}
public List<String> getQuestionLabels() {
return questionLabels;
}
public List<String> getQuestionVisibleValues() {
return questionValues;
}
public void setErrorFlag(boolean hasError) {
this.hasError = hasError;
}
public boolean hasError() {
return hasError;
}
public Map<String,Value> getAllRunTimeValues(){
return varUpdater.getUpdatedValues();
}
}
<file_sep>package org.uva.sea.ql.gui.ide;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class UtilityBarPanel extends JPanel {
public UtilityBarPanel(){
super(new MigLayout());
setSettings();
}
private void setSettings() {
this.setMaximumSize(new Dimension(200,90));
this.setBackground(Color.LIGHT_GRAY);
}
}
<file_sep>package org.uva.sea.ql.gui.qlform;
import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JTextField;
import org.uva.sea.ql.ast.types.Type;
@SuppressWarnings("serial")
public class QLInputVerifier extends JLabel implements KeyListener, QLAtomComponent{
private final JTextField inputTextField;
private final Type type;
private String value="";
public QLInputVerifier(JComponent component, Type type) {
this.inputTextField = (JTextField) component;
this.type = type;
setSettings();
}
private void setSettings(){
this.setForeground(Color.ORANGE);
inputTextField.addKeyListener(this);
}
private void setVerifierMsg() {
String input = inputTextField.getText();
if (type.isCompatibleToNumericType()) {
numVerifier(input);
return;
}
stringVerifier(input);
}
private void numVerifier(String input) {
if (!isNumChar(input)) {
value="*accepts only numeric characters*";
this.setText(value);
return;
}
value="";
this.setText(value);
}
private void stringVerifier(String input) {
if (!isStringChar(input)) {
this.setVisible(true);
this.setText("*accepts only string characters*");
return;
}
this.setVisible(false);
this.setText("");
}
public static boolean isStringChar(String input) {
return !input.matches(".*\\d.*");
}
public static boolean isNumChar(String input) {
try {
Float.parseFloat(input);
} catch (Exception e) {
return false;
}
return true;
}
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
setVerifierMsg();
}
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public String getDisplayedValue() {
return value;
}
public boolean hasError(){
return !value.isEmpty();
}
@Override
public boolean isQuestionLabel() {
return false;
}
@Override
public boolean isAnswerHolder() {
return false;
}
@Override
public boolean isWarningLabel() {
return true;
}
}
<file_sep>package org.uva.sea.ql.gui.ide;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import net.miginfocom.swing.MigLayout;
@SuppressWarnings("serial")
public class EditorArea extends JPanel {
private final JTextArea editorArea;
public EditorArea() {
super(new MigLayout());
editorArea = new JTextArea(18, 50);
setSettings();
}
private void setSettings() {
this.setBackground(new Color(49, 49, 49));
editorArea.setBackground(Color.black);
editorArea.setForeground(new Color(255, 185, 15));
editorArea.setLineWrap(true);
editorArea.setWrapStyleWord(true);
editorArea.setCaretColor(Color.white);
JScrollPane bar = new JScrollPane(editorArea,
JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
bar.setPreferredSize(new Dimension(550, 300));
this.add(bar);
}
public String getSourceCode(){
return editorArea.getText();
}
public void setSourceCode(String input){
editorArea.setText(input);
}
}
<file_sep>package org.uva.sea.ql.output.generators.pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;
import org.uva.sea.ql.gui.qlform.output.QLOutputSelectorFrame;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class QLToPDF {
private final static Font symbolFont = new Font(Font.FontFamily.ZAPFDINGBATS, 15, Font.BOLD);
private final static Font titleFont = new Font(Font.FontFamily.TIMES_ROMAN, 18,Font.UNDERLINE);
private final static Font questionFont = new Font(Font.FontFamily.TIMES_ROMAN, 14,Font.ITALIC);
private final static Font resultsFont = new Font(Font.FontFamily.TIMES_ROMAN, 14,Font.BOLD);
private final static URL imgPath = QLToPDF.class.getResource("/org/uva/sea/ql/output/generators/pdf/images/uva_logo.jpg");
private final static Map<String,String> boolValues;
static
{
boolValues = new HashMap<String, String>();
boolValues.put("true", "Yes");
boolValues.put("false","No");
}
private final static Map<String,String> yesOrNoSymbol;
static
{
yesOrNoSymbol = new HashMap<String, String>();
yesOrNoSymbol.put("true", "4"); //** Values '4' and '6' corresponds to 'tick' and 'X' symbols of
yesOrNoSymbol.put("false","6"); //** the ZAPFDINGBATS font.
}
private final List<String> questionLabels;
private final List<String> questionValues;
private final JFrame frame;
private QLToPDF(List<String> questionLabels,List<String> questionValues, JFrame frame){
this.questionLabels=questionLabels;
this.questionValues=questionValues;
this.frame= frame;
}
public static void generatePdf(JFrame frame,List<String> questionLabels,List<String> questionValues) {
QLToPDF generator=new QLToPDF(questionLabels,questionValues, frame);
generator.putContent(frame.getTitle());
}
private void putContent(String frameName) {
try {
String path = showSaveDialog(frameName+".pdf",new TypeOfPDF());
if (path.isEmpty())
return;
File filePath = new File(path);
OutputStream file = new FileOutputStream(filePath.getAbsolutePath());
Document document = new Document();
PdfWriter.getInstance(document, file);
document.open();
Image img = Image.getInstance(imgPath);
document.add(setHeaderLogo(img));
document.add(setTitle(frameName));
for (int i = 0; i <= questionLabels.size() - 1; i++) {
Paragraph p1 = new Paragraph(questionLabels.get(i),
questionFont);
p1 = getProperDisplayedValue(p1, questionValues.get(i));
addEmptyLine(p1, 1);
document.add(new Paragraph(p1));
}
document.close();
file.close();
QLOutputSelectorFrame.showConfirmationMessage(frame, frame.getTitle()+".pdf file successful created!");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
private static Paragraph setHeaderLogo(Image img) {
Paragraph logoHeader = new Paragraph();
img.scalePercent(15f);
Chunk imgChunk = new Chunk(img, 0, 0, true);
logoHeader.add(imgChunk);
logoHeader.setAlignment(Element.ALIGN_LEFT);
addEmptyLine(logoHeader, 1);
return logoHeader;
}
private static Paragraph setTitle(String frameName) {
Paragraph header = new Paragraph();
addEmptyLine(header, 1);
Paragraph title = new Paragraph(frameName + " Questionnaire", titleFont);
header.add(title);
addEmptyLine(header, 2);
title.setAlignment(Element.ALIGN_CENTER);
return header;
}
private Paragraph getProperDisplayedValue(Paragraph paragraph, String value) {
paragraph.add(new Chunk(" "));
if (boolValues.containsKey(value)) {
paragraph.add(new Chunk(yesOrNoSymbol.get(value), symbolFont));
paragraph.add(new Chunk(" (" + boolValues.get(value) + ")", resultsFont));
} else {
paragraph.add(new Chunk(" " + value, resultsFont));
}
return paragraph;
}
public static String showSaveDialog(String fileName,FileFilter fileType) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setAcceptAllFileFilterUsed(false);
fileChooser.setSelectedFile(new File(fileName));
fileChooser.setFileFilter(fileType);
int returnValue = fileChooser.showSaveDialog(null);
if (returnValue == JFileChooser.APPROVE_OPTION) {
File outputFile = fileChooser.getSelectedFile();
return outputFile.getAbsolutePath();
}
return "";
}
class TypeOfPDF extends FileFilter {
public boolean accept(File file) {
return file.isDirectory();
}
public String getDescription() {
return ".pdf";
}
}
}<file_sep>package org.uva.sea.ql.output.generators.json;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.uva.sea.ql.gui.qlform.output.QLOutputSelectorFrame;
import org.uva.sea.ql.output.generators.pdf.QLToPDF;
import org.uva.sea.ql.visitor.evaluator.values.Value;
public class QLToJSON {
private final Map<String,Value> allRunTimeValues;
private final JSONObject qlForm = new JSONObject();
private final JFrame frame;
private QLToJSON(Map<String,Value> allRunTimeValues, JFrame frame) {
this.allRunTimeValues=allRunTimeValues;
this.frame= frame;
}
public static void generateJson(JFrame frame,Map<String,Value> allRunTimeValues) {
QLToJSON generator = new QLToJSON(allRunTimeValues, frame);
generator.createForm(frame.getTitle());
generator.writeToFile(frame.getTitle());
}
@SuppressWarnings("unchecked")
private void createForm(String frameName) {
JSONObject title = new JSONObject();
title.put("formName", frameName);
JSONArray structure = new JSONArray();
structure.add(title);
JSONObject content = getContentList();
structure.add(content);
qlForm.put("qlForm", structure);
}
private void writeToFile(String frameName) {
try {
String path = QLToPDF.showSaveDialog(frameName+".json", new TypeOfJson());
if (path.isEmpty())
return;
File filePath = new File(path);
FileWriter file = new FileWriter(filePath.getAbsolutePath());
file.write(qlForm.toJSONString());
file.flush();
file.close();
QLOutputSelectorFrame.showConfirmationMessage(frame, frame.getTitle()+".json file successful created!");
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private JSONObject getContentList() {
JSONArray contentList = new JSONArray();
Iterator<String> iterator = allRunTimeValues.keySet().iterator();
while (iterator.hasNext()) {
JSONObject question = new JSONObject();
String key = iterator.next().toString();
question.put("ident", key);
question.put("answer",String.valueOf(allRunTimeValues.get(key).getValue()));
contentList.add(question);
}
JSONObject questionsList = new JSONObject();
questionsList.put("questions", contentList);
return questionsList;
}
class TypeOfJson extends FileFilter {
public boolean accept(File file) {
return file.isDirectory();
}
public String getDescription() {
return ".json";
}
}
}
<file_sep>package org.uva.sea.ql.gui.qlform;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import javax.swing.JTextField;
import org.uva.sea.ql.gui.qlform.interpreter.VariableUpdater;
import org.uva.sea.ql.visitor.evaluator.values.StrValue;
import org.uva.sea.ql.visitor.evaluator.values.Value;
@SuppressWarnings("serial")
public class QLTextField extends JTextField implements ActionListener, Observer, QLAtomComponent{
private final String varName;
private final Map<String, Value> runTimeValues;
private String value;
private final static Color defaultColor= new Color(238,238,238);
private final VariableUpdater varUpdater;
public QLTextField(String varName,Map<String, Value> runTimeValues, VariableUpdater varUpdater){
super(8);
this.varName=varName;
this.runTimeValues=runTimeValues;
this.varUpdater=varUpdater;
this.varUpdater.addObserver(this);
setSettings();
}
private void setSettings(){
value=((StrValue) runTimeValues.get(varName)).getValue();
this.setBackground(defaultColor);
this.addActionListener(this);
this.setText(value);
}
@Override
public void actionPerformed(ActionEvent e) {
String input=this.getText();
if(!QLInputVerifier.isStringChar(input)) return;
varUpdater.updateValueAndNotify(varName, runTimeValues, new StrValue(input));
}
@Override
public void update(Observable arg0, Object arg1) {
value=((StrValue) varUpdater.getUpdatedValues().get(varName)).getValue();
this.setText(value);
}
@Override
public String getDisplayedValue() {
return this.getText();
}
@Override
public boolean isQuestionLabel() {
return false;
}
@Override
public boolean isAnswerHolder() {
return true;
}
@Override
public boolean isWarningLabel() {
return false;
}
}
<file_sep>package org.uva.sea.ql.gui.qlform.output;
import java.awt.Component;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import org.uva.sea.ql.gui.qlform.QLAtomComponent;
import org.uva.sea.ql.gui.qlform.QLContainerComponent;
import org.uva.sea.ql.gui.qlform.QLInputVerifier;
import org.uva.sea.ql.gui.qlform.interpreter.VariableUpdater;
public class OutputData {
private final List<JPanel> questionPanelList;
private final QLOutputState outputState;
private final JFrame frame;
public OutputData(List<JPanel> questionPanelList, JFrame frame,VariableUpdater varUpdater) {
this.questionPanelList = questionPanelList;
this.frame = frame;
outputState = new QLOutputState(varUpdater);
}
public QLOutputState getOutputData() {
traverseFormsSubComponents(questionPanelList);
return outputState;
}
/*
* Gathers the question label text and their respective answer
*/
private void gatherDataFromSubComponents(Component[] components) {
for (int i = 0; i < components.length; i++) {
QLAtomComponent component = (QLAtomComponent) components[i];
if (component.isWarningLabel()) {
setWarning(component);
}
else if (component.isQuestionLabel()) {
outputState.addLabelText(component.getDisplayedValue());
}
else if (component.isAnswerHolder()) {
outputState.addValue(component.getDisplayedValue());
}
}
}
private void traverseFormsSubComponents(List<JPanel> questionPanelList) {
for (JPanel questionPanel : questionPanelList) {
QLContainerComponent container =(QLContainerComponent) questionPanel;
if (container.isConditionalBody()) {
if (!isVisible(questionPanel))
return;
Component[] conditionalBodyPanel = questionPanel.getComponents();
traverseConditionalBodysSubComponents(conditionalBodyPanel);
} else {
Component[] components = questionPanel.getComponents();
gatherDataFromSubComponents(components);
}
}
}
private void traverseConditionalBodysSubComponents(Component[] conditionalBodyPanel){
List<JPanel> panelList=new ArrayList<JPanel>();
for (Component questionPanel : conditionalBodyPanel) {
panelList.add((JPanel) questionPanel);
}
traverseFormsSubComponents(panelList);
}
private void setWarning(QLAtomComponent component) {
QLInputVerifier label = (QLInputVerifier) component;
if (!label.hasError())
return;
outputState.setErrorFlag(true);
showWarning();
}
private void showWarning() {
JOptionPane.showMessageDialog(frame,"Wrong input.Check input warnings!");
}
private boolean isVisible(Component component){
return ((JPanel) component).isVisible();
}
}
<file_sep>package org.uva.sea.ql.parser.test;
import static org.junit.Assert.assertEquals;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.junit.Test;
import org.uva.sea.ql.ast.types.BoolType;
import org.uva.sea.ql.ast.types.IntType;
import org.uva.sea.ql.ast.types.MoneyType;
import org.uva.sea.ql.ast.types.StringType;
import org.uva.sea.ql.ast.types.Type;
import org.uva.sea.ql.parser.antlr.ANTLRParser;
import org.uva.sea.ql.visitor.checkers.ExpressionChecker;
import org.uva.sea.ql.visitor.checkers.error.QLErrorMsg;
public class TestExpressionChecker {
private ANTLRParser parser;
private Map<String, Type> declaredVars;
private List<QLErrorMsg> errorReport;
public TestExpressionChecker() {
parser = new ANTLRParser();
errorReport = new ArrayList<QLErrorMsg>();
declaredVars = new LinkedHashMap<String, Type>();
}
@Test
public void testBoolExprType() throws ParseError {
declaredVars.put("BoolVar", new BoolType());
assertEquals(true,ExpressionChecker.check(parser.parseExpr("(4>9) && ((45==3) || BoolVar)"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("(4>\"UndefinedVar\") && ((45==3) || false)"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("(4+6) && ((45==3) || false)"),declaredVars,errorReport));
assertEquals(true,ExpressionChecker.check(parser.parseExpr("(4>=6)!= (((45==3) == false))"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("(4!=6) &&(((45==3) * !false))"),declaredVars,errorReport));
}
@Test
public void testIntExprType() throws ParseError {
declaredVars.put("IntVar", new IntType());
assertEquals(true,ExpressionChecker.check(parser.parseExpr("4+IntVar/(3*6-44)"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("4+\"UndefinedVar\"/(3*6-44)"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("6+9-2*7.9"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("6+9-2*!7.9"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("4+false"),declaredVars,errorReport));
}
@Test
public void testMoneyExprType() throws ParseError {
declaredVars.put("type of question", new MoneyType());
assertEquals(true, ExpressionChecker.check(parser.parseExpr("4.8+9.3/3.2*2.7"),declaredVars, errorReport));
assertEquals(false, ExpressionChecker.check(parser.parseExpr("4.8+9.3/3.2*!2.7"),declaredVars, errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("4.2+3"),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("4.2+false"),declaredVars,errorReport));
}
@Test
public void testStringExprType() throws ParseError {
declaredVars.put("declaredVariable", new StringType());
assertEquals(true,ExpressionChecker.check(parser.parseExpr("variable name"),declaredVars,errorReport));
assertEquals(true,ExpressionChecker.check(parser.parseExpr("\"8+3\""),declaredVars,errorReport));
assertEquals(false,ExpressionChecker.check(parser.parseExpr("8+3"),declaredVars,errorReport));
}
}<file_sep>package org.uva.sea.ql.gui.qlform;
import java.awt.Color;
import java.util.Map;
import java.util.Observable;
import java.util.Observer;
import javax.swing.BorderFactory;
import javax.swing.JTextField;
import org.uva.sea.ql.ast.expr.Expr;
import org.uva.sea.ql.ast.form.ComputedQuestion;
import org.uva.sea.ql.gui.qlform.interpreter.VariableUpdater;
import org.uva.sea.ql.visitor.evaluator.ExprEvaluator;
import org.uva.sea.ql.visitor.evaluator.values.Value;
@SuppressWarnings("serial")
public class QLComputedField extends JTextField implements Observer,QLAtomComponent {
private final VariableUpdater varUpdater;
private final Map<String,Value> runTimeValues;
private final Expr expr;
private final String varName;
public QLComputedField(ComputedQuestion qlElement,VariableUpdater varUpdater,Map<String,Value> runTimeValues) {
super(8);
this.varUpdater=varUpdater;
this.varUpdater.addObserver(this);
this.expr=qlElement.getExpr();
this.varName=qlElement.getId().getName();
this.runTimeValues = runTimeValues;
setSettings();
}
private void setSettings() {
Value initValue = ExprEvaluator.eval(expr, runTimeValues);
this.setText(String.valueOf(initValue.getValue()));
this.setForeground(Color.orange);
this.setBackground(Color.gray);
this.setBorder(BorderFactory.createLineBorder(Color.white));
this.setHorizontalAlignment(JTextField.CENTER);
this.setEditable(false);
}
@Override
public void update(Observable arg0, Object arg1) {
Map<String,Value> currentValues = varUpdater.getUpdatedValues();
Value newVal = ExprEvaluator.eval(expr, currentValues);
varUpdater.updateValue(varName, currentValues, newVal);
this.setText(String.valueOf(newVal.getValue()));
}
@Override
public String getDisplayedValue() {
return this.getText();
}
@Override
public boolean isQuestionLabel() {
return false;
}
@Override
public boolean isAnswerHolder() {
return true;
}
@Override
public boolean isWarningLabel() {
return false;
}
}
<file_sep>package org.uva.sea.ql.gui.qlform.renderer;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.uva.sea.ql.gui.qlform.QLContentPanel;
import org.uva.sea.ql.gui.qlform.QLExportButton;
import org.uva.sea.ql.gui.qlform.QLScrollBar;
import org.uva.sea.ql.gui.qlform.interpreter.VariableUpdater;
public class Renderer {
private final List<JPanel> questionPanelList;
private final JPanel contentPanel = new QLContentPanel();
private final JFrame frame;
private final VariableUpdater varUpdater;
private final static QLScrollBar scrollBar = new QLScrollBar();
public Renderer(List<JPanel> questionPanelList, JFrame frame,VariableUpdater varUpdater) {
this.frame = frame;
this.questionPanelList = questionPanelList;
this.varUpdater=varUpdater;
}
public void addQuestionsToPanel() {
for (JPanel question : questionPanelList) {
contentPanel.add(question, "align label,wrap");
}
scrollBar.add(contentPanel);
frame.add(scrollBar, "align center,wrap");
frame.add(QLExportButton.responsiveButton(questionPanelList, frame, varUpdater),"align center");
frame.setVisible(true);
}
}
<file_sep>package org.uva.sea.ql.ast.expr.binary.bool;
import org.uva.sea.ql.ast.expr.Expr;
import org.uva.sea.ql.ast.expr.binary.Binary;
public abstract class Bool extends Binary{
protected Bool (Expr leftExpr,Expr rightExpr){
super(leftExpr,rightExpr);
}
}
| 03a294c29bf08845cea8d86c7a9053dfc7641968 | [
"Java"
] | 16 | Java | jahnestacado/QL | 1efd8418be182d1fd2b46d22d93069cfd42b677c | d8cadb20211e0b6636b4c5e7b37627001c97c4e0 | |
refs/heads/master | <file_sep>## Reusable Componet Library<file_sep>export { default } from './Label';
| a3a752ff3436d72188c2d1d43de817719e574753 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | sartra/react-reusable-component-lib | 00b37b92bd88219c3aa290c123d18cf3e9d809e7 | c145fd63cd95adf0d97d803a3d67b258e5ca06af | |
refs/heads/main | <repo_name>egpce-cedis/planejamentoSetorPublicoMod03<file_sep>/Topico02_1.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">1 - Tipos de Diagnóstico</h2>
<hr class="pontLaranja">
<p class="Texto">
<strong>
O Diagnóstico Estratégico é construído a partir de duas visões distintas:
</strong>
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> A visão para fora da empresa – o diagnóstico externo;<br>
<i class="fa fa-arrow-right CorLaranja"></i> A visão para dentro da empresa - o diagnóstico interno.
</ul>
<p class="Texto">
O Diagnóstico Estratégico Externo (DEE) (Análise do Ambiente Externo) é a atividade mais complexa e, na maioria dos casos, a mais relevante do processo de planejamento estratégico.
<br><br>O produto do DEE é a identificação das oportunidades e das ameaças que uma organização tem e que será a base para que ela atinja a sua eficácia organizacional.
</p>
<div class="row">
<div class="col-sm">
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem04.jpeg" data-toggle="lightbox" data-footer=" Os diferentes ambientes de uma Organização">
<img class="img-fluid" src="imagens/imagem04.jpeg" alt=" Os diferentes ambientes de uma Organização" width="400">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 4:</strong> Os diferentes ambientes de uma Organização <br><strong>Fonte:</strong> Pereira (2009)</p>
</div>
</div>
<div class="col-sm">
<p class="Texto">
O Diagnóstico Estratégico Interno (Análise da Organização) é a atividade que permite que uma organização tome consciência real dos seus pontos fortes e fracos e está relacionada com a eficiência operacional.
<br><br>É imprescindível analisar os fatores externos e internos para que um sólido diagnóstico possa ser feito, visto que as mudanças influenciam as organizações, obrigando-as a responderem através de novos paradigmas e novas estratégias.
</p>
</div>
</div>
<h2 class="font-bold">1.1 - Diagnóstico Estratégico Externo</h2>
<hr class="pontLaranja">
<p class="Texto">
O DEE (ou Análise Ambiental) é a maneira como a organização faz o mapeamento ambiental e a análise das forças competitivas que existem no ambiente. Os principais objetivos do DEE são:
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Identificar indicadores de tendências;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Avaliar o ambiente de negócios;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Avaliar a evolução setorial;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Analisar a concorrência.
</ul>
<p class="Texto">
<strong>O DEE se divide em duas análises distintas:</strong>
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Macroambiente – é a análise de fatores globais (demográficos, socioculturais, econômicos, dentre outros) que, na maioria dos casos, afetam todas as organizações de maneira similar.<br>
<i class="fa fa-arrow-right CorLaranja"></i> Análise Setorial – é a análise de fatores (concorrentes, fornecedores, clientes, dentre outros) relacionados diretamente com o setor de negócios no qual determinada organização atua.
</ul>
<p class="Texto">
O macroambiente difere do ambiente setorial, porque o macroambiente é o universo geral no qual todas as organizações atuam, enquanto o ambiente setorial é aquele no qual uma organização específica atua. Entretanto, as fronteiras entre o macroambiente e o ambiente setorial não devem ser vistos como fronteiras estáticas, uma vez não se tratam de sistemas inertes, mas sim de sistemas dinâmicos, pois tanto a empresa, como o macroambiente de uma forma geral são seres <strong>“organizacionais”</strong> vivos. Esses conceitos estão ilustrados na imagem 5.
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem05.png" data-toggle="lightbox" data-footer="Detalhamento do Macroambiente e do Ambiente Setorial de uma organização">
<img class="img-fluid" src="imagens/imagem05.png" alt="Detalhamento do Macroambiente e do Ambiente Setorial de uma organização">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 5:</strong> Detalhamento do Macroambiente e do Ambiente Setorial de uma organização <br><strong>Fonte:</strong> Chiavenato e Shapiro(2004)</p>
</div>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse1" aria-expanded="false" aria-controls="collapse1">
<h3>Macroambiente</h3>
</button>
</h2>
</div>
<div id="collapse1" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
O <strong>macroambiente</strong> consiste no ambiente geral das organizações, onde estão todos os fatores externos a uma organização, dentre os quais se destacam: os fatores demográficos, econômico, socioculturais, político-legais, tecnológicos e ecológicos.
</p>
<div class="row ">
<div class="col-sm Texto">
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem06.jpg" data-toggle="lightbox" data-footer="Macroambiente e Microambiente">
<img class="img-fluid" src="imagens/imagem06.jpg" alt="Macroambiente e Microambiente" width="550">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 1:</strong> Macroambiente e Microambiente <br><strong>Fonte:</strong> Chiavenato e Shapiro; Microambientes (2003)</p>
</div>
</div>
<div class="col-sm Texto"><br><br>
Os fatores demográficos refletem mudanças demográficas, tais como: tamanho, densidade e distribuição geográfica populacional, mobilidade da população e processo migratório e taxa de crescimento e envelhecimento da população, dentre outros.<br><br>
Essas mudanças quando bem monitoradas podem revelar grandes oportunidades ou problemas para uma organização sensível a um outro desses fatores. Tais fatores normalmente mudam de forma lenta e, portanto, quando bem monitorados não causam grandes sustos.
</div>
</div><br><br>
<!-- Botão para acionar modal -->
<center>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Economicos">
Fatores Econômicos
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Socioculturais">
Fatores Sócioculturais
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#PoliticoLegais">
Fatores Político-Legais
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Ecologicos">
Fatores Ecológicos
</button>
</center>
<!-- Modal -->
<div class="modal fade" id="Economicos" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Fatores Econômicos</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os fatores econômicos refletem a situação econômica, refletem o estado geral da economia em termos de inflação, níveis de receita, produto interno bruto, desemprego e outros indicadores responsáveis por grande parte das mudanças no ambiente externo. As mudanças na economia trazem oportunidades e problemas às organizações e cabe aos seus gestores saber aproveitá-las ou contorná-las, além de continuamente monitorar as mudanças dos indicadores-mestres da economia, buscando minimizar fraquezas e capitalizar oportunidades.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="Socioculturais" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Fatores Sócioculturais</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os fatores sócioculturais são mudanças no sistema cultural e social, que afetam as ações de uma organização e a demanda por seus produtos ou serviços, tais como: direitos humanos, hábitos das pessoas em relação a atitudes e suposições, crenças e aspirações pessoais, relacionamentos interpessoais e estrutura social, estrutura educacional ou preocupação com a saúde e o preparo físico, dentre outros.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="PoliticoLegais" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Fatores Político-Legais </h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os fatores político-legais caracterizam-se por numerosas leis e inúmeras autoridades que exercem indireta e forte influência sobre as organizações. Os fatores tecnológicos podem influenciar o uso do conhecimento e de técnicas da organização na produção de seus produtos e serviços, além de afetarem suas características.
<br><br>Devido às constantes mudanças na tecnologia, a administração deve se manter à frente dos mais recentes desenvolvimentos, para manter a competitividade da organização. Esses fatores possuem, em geral, uma velocidade de mudança muito grande, e, portanto, o grau de influência desses fatores em uma organização depende do seu grau de dependência em relação a eles.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="Ecologicos" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Fatores Ecológicos</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os fatores ecológicos são aqueles relacionados com o uso adequado e de forma sustentável dos recursos naturais de uma forma geral. Na atualidade, eles exercem um grande impacto sobre a organização que não os administrar de forma adequada, em função do crescente nível de consciência ambiental e de desenvolvimento ecológico da população.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<hr>
<br>
<p class="Texto">
Uma leitura distinta, mas complementar, para o macroambiente é aquela proposta por <NAME>, há 25 anos, em seu livro Megatendências, uma vez que muitas dessas tendências se revelam bem conectadas com os tempos atuais. Naisbit, analisa quatro fatores (Quadro 1) e sua proposta é a de que as suas alterações ocorrem de forma lenta e, depois de consolidadas, influenciam o ambiente por um longo tempo, cerca de sete a dez anos, e às vezes até mais.
</p>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="CorLaranja">
<tr style="background-color: #fde7a7;">
<th scope="col">
<h5><strong>Fatores </strong></h5>
</th>
<th scope="col">
<h5><strong>Descrição</strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Econômicos
</td>
<td class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Globalização da economia;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Viagens (lazer) será a maior indústria global;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Ásia e América - "zonas do agrião" - investimento e crescimento;<br>
<i class="fa fa-arrow-right CorLaranja"></i> De nações para redes internacionais - blocos;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Do trabalho intenso para alta tecnologia;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Do centralismo do estado para o controle do mercado.<br>
</td>
</tr>
<tr>
<td class="Texto">
Sociais
</td>
<td class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Estilo de vida global versus nacionalismo cultural;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Mulheres na liderança (trabalho, moda, política, esportes, família etc.);<br>
<i class="fa fa-arrow-right CorLaranja"></i> Da denominação masculina para a emergência da mulher;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Supremacia do servidor/cidadão.
</td>
</tr>
<tr>
<td class="Texto">
Políticos
</td>
<td class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Descentralização do poder;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Emergência de um socialismo de livre mercado;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Novos códigos de conduta no século 21; <br>
<i class="fa fa-arrow-right CorLaranja"></i> Mais democracia, mais países.
</td>
</tr>
<tr>
<td class="Texto">
Tecnológicos
</td>
<td class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> A revolução das telecomunicações;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Comunidades eletrônicas;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Máquinas capazes de emoção e raciocínio;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Alta tecnologia e grande contato humano;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Era da biologia (clonagem, biorremediação).
</td><br>
</tr>
</tbody>
</table>
</div>
</section>
<br>
<hr class="BackLaranja">
<center>
<p class="FonteFigura CorLaranja">
<strong>Quadro 01</strong> - Fatores que afetam o macroambiente de uma organização
<br><strong>Fonte:</strong> NAISBIT (1983)
</p>
</center>
<p class="Texto">
O fato concreto é que os fatores do macroambiente exercem influência sobre uma organização e seus negócios e, portanto, são relevantes e devem ser considerados. As organizações precisam analisar esses fatores e suas mudanças, estando preparadas para usá-los a seu favor quando possível e minimizar os seus prejuízos, quando for o caso. Em resumo, já que é difícil influenciar esses fatores do macroambiente, é fundamental, no mínimo, monitorá-los para não ser surpreendido por eles.
</p>
</div>
<br><br>
</div>
</div>
</div>
</section>
<br>
<!-- collapse -->
<section id="SetordeNegócios">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingtwo">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse2" aria-expanded="false" aria-controls="collapse2">
<h3>Setor de Negócios</h3>
</button>
</h2>
</div>
<div id="collapse2" class="collapse" aria-labelledby="headingtwo" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
O <strong class="CorLaranja">Setor de Negócios</strong> (A análise do setor de negócios é também citada na literatura com vários outros nomes, dentre os quais: análise do ambiente setorial, análise do ambiente das tarefas ou análise de ambiente operacional.) consiste no ambiente com o qual a organização se relaciona diretamente, ambiente este em que atua de forma competitiva e cujos principais elementos são: mercado, clientes, produtos e/ou serviços, concorrentes e fornecedores. Esse é o ambiente específico no qual uma organização interage para sobreviver e prosperar com grupos e pessoas reais e ele é diferente para cada organização, variando conforme os negócios em que atua.
</p>
<div class="row">
<div class="col-sm">
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem07.png" data-toggle="lightbox" data-footer="Os principais elementos do setor de negócios">
<img class="img-fluid" src="imagens/imagem07.png" alt="Os principais elementos do setor de negócios">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 7:</strong> Os principais elementos do setor de negócios <br><strong>Fonte:</strong> CHIAVENATO e SHAPIRO (2003) </p>
</div>
</div>
<div class="col-sm">
<p class="Texto">
O mercado, numa definição ampla, é a instituição social que emerge naturalmente das relações econômicas e que permite às pessoas (ou grupo de pessoas) realizar trocas, normalmente reguladas pela lei da oferta e da procura.
<br><br>Numa definição restrita, mercado consiste no segmento de pessoas, empresas ou áreas geográficas onde estão os consumidores e <em>prospects</em> de uma empresa ou marca. Algumas perguntas são muito relevantes para a tomada de decisões estratégicas.
</div>
</div>
<div class="alert alert-light-primary" role="alert">
<p class="Texto">
<strong>
Qual o tamanho do mercado no qual uma empresa atua (ou deseja atuar)?
<br>Quais as tendências e perspectivas deste mercado?
<br>Quais as causas de crescimento deste mercado e possíveis consequências?
</strong>
</p>
</div>
<p class="Texto">
Essas são algumas das perguntas que se bem respondidas ajudam e muito na definição de decisões estratégicas.
<br><br>Os clientes são pessoas físicas e/ou jurídicas que compram produtos e/ou usam serviços de uma organização. Eles diferem entre si sob diversos aspectos, como: idade, sexo, educação, estilo de vida e renda. De todas as forças diretas com as quais uma organização interage, os clientes são as mais vitais, pois deles depende seu presente e seu futuro.
<br><br>Uma organização deve conhecer muito bem seus clientes e seus não clientes e para isso é necessária a realização de pesquisas frequentes com eles, pois a análise dos resultados dessas pesquisas trará elementos concretos para a tomada de decisões estratégicas. Por outro lado, pesquisa mal feitas, que falhem no mapeamento das mudanças de hábitos, preferências e necessidades dos clientes, podem conduzir uma organização a resultados desastrosos.
<br><br>Os produtos são os bens tangíveis produzidos por uma organização. Serviços são atividades intangíveis realizadas por uma organização que atendem às necessidades de determinados clientes ou que agregam valor a bens produzidos. O conhecimento do mercado e dos clientes é que permite a uma organização saber que produtos e/ou serviços atendem às suas necessidades, bem como o nível de competição, de padronização e de diferenciação/inovação dos produtos/serviços que a instituição deve oferecer.
<br><br>Os concorrentes são organizações específicas que oferecem mercadorias iguais ou similares aos mesmos clientes e que competem entre si pelos mesmos recursos do mercado, como matéria-prima e mão de obra. Os concorrentes podem ser diretos ou indiretos. Os concorrentes diretos são aqueles que produzem produtos e serviços similares, enquanto os concorrentes indiretos alteram o interesse do consumidor, desviando as suas intenções de compra.
<br><br>As mudanças oriundas de concorrentes indiretos são mais difíceis de se prever e de monitorar do que aquelas dos concorrentes diretos. Os fornecedores são provedores específicos de recursos humanos, financeiros, materiais e de informação, necessários a uma organização para operar. Fornecedores são organizações que fornecem recursos como fundos, energia, equipamentos, serviços e materiais para a produção de produtos ou serviços das organizações. Esses recursos afetam expressivamente a qualidade, o custo e o prazo de entrega de qualquer produto ou serviço.
</p>
</div>
</div>
</div>
</div>
</div>
</section>
<br>
<h2 class="font-bold">1.2 - Diagnóstico Estratégico Interno</h2>
<hr class="pontLaranja">
<p class="Texto">
O DEI (ou análise do ambiente interno) é o retrato da realidade da organização no momento em que ele foi feito. É olhar para dentro da organização. Esse olhar para dentro permite a identificação de potencialidades e vulnerabilidades, agrupando perspectivas internas divergentes e com isso vislumbrando um <strong>“retrato”</strong> mais focado e compreensivo da organização.
<br><br>Esse retrato deve, no mínimo, analisar as principais áreas ou funções da organização, como, por exemplo, recursos humanos, marketing ou produção, a utilização e o nível de ferramentas de gestão, de sistemas e métodos organizacionais.
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem08.png" data-toggle="lightbox" data-footer="Macroambiente, Microambiente e Ambiente Interno">
<img class="img-fluid" src="imagens/imagem08.png" alt="Macroambiente, Microambiente e Ambiente Interno">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 8:</strong> Macroambiente, Microambiente e Ambiente Interno</p>
</div><br><br>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="CorLaranja">
<tr>
<th scope="col">
<h5><strong>Etapa </strong></h5>
</th>
<th scope="col">
<h5><strong>Objetivo </strong></h5>
</th>
<th scope="col">
<h5><strong>O que deve ser analisado </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Primeira
</td>
<td class="Texto">
Análise das <u>funções</u> principais da organização
</td>
<td class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Marketing<br>
<i class="fa fa-arrow-right CorLaranja"></i> Finanças<br>
<i class="fa fa-arrow-right CorLaranja"></i> Recursos Humanos<br>
<i class="fa fa-arrow-right CorLaranja"></i> Produção<br>
<i class="fa fa-arrow-right CorLaranja"></i> Logística (TI)<br>
<i class="fa fa-arrow-right CorLaranja"></i> Outras (P&D)
</td>
</tr>
<tr>
<td class="Texto">
Segunda
</td>
<td class="Texto">
Análise dos <u>sistemas e métodos organizacionais</u> da organização.
</td>
<td class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Avaliação Competitiva<br>
<i class="fa fa-arrow-right CorLaranja"></i> Recursos Organizacionais<br>
<i class="fa fa-arrow-right CorLaranja"></i> Arquitetura Organizacional<br>
<i class="fa fa-arrow-right CorLaranja"></i> Gestão de Processos<br>
<i class="fa fa-arrow-right CorLaranja"></i> Competências Essenciais<br>
<i class="fa fa-arrow-right CorLaranja"></i> Gestão de Qualidade
</td>
</tr>
</tbody>
</table>
</div>
<center><p class="FonteFigura CorLaranja"><strong>Quadro 02:</strong> Etapas e Objetivos para a realização do diagnóstico estratégico interno
</p></center>
</section>
<br>
<p class="Texto">
A primeira etapa tem como objetivo analisar as principais funções que qualquer organização possui. O olhar deve ser feito na forma com a qual a organização desenvolve estas funções, através de perguntas bem elaboradas junto aos responsáveis pelas funções, bem como através de brainstorm com pessoas que são afetadas por essas funções no interior da organização.
<br><br>A segunda etapa tem como objetivo analisar as ferramentas de gestão, sistemas e métodos que são utilizados pela organização. Esse olhar ultrapassa as fronteiras das principais funções quando analisadas isoladamente, pois cada uma das facetas, que esse olhar buscará, estará olhando a organização para dentro como um todo.
<br><br>Essa análise completa permitirá a identificação objetiva dos Fatores Críticos de Sucesso da organização no ramo de atividade na qual ela opera ou planeja operar. Fatores Críticos de Sucesso (FCS) são os fatores que levam uma organização a cumprir sua missão (razão de ser) e atingir sua visão.
<br><br>Os FCS são fatores-chave, ou seja, fatores cujo desenvolvimento será determinante e principal responsável para que uma organização se sobressaia em relação a seus concorrentes. A comparação dos FCS de uma organização com os seus concorrentes diretos ou indiretos permite identificar aqueles que são superiores, inferiores ou semelhantes aos das organizações comparadas. O resultado dessa análise fornecerá de uma forma muito precisa os pontos fortes, neutros e fracos de uma organização.
<br><br>Os pontos fortes são características ou forças internas controláveis da empresa, que, se bem utilizadas, permitem alcançar vantagem competitiva sobre seus concorrentes. Por outro lado, os pontos fracos são características ou forças internas controláveis, que, se expostas ao ambiente, dificultam alcançar vantagem competitiva sobre seus concorrentes
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem09.jpg" data-toggle="lightbox" data-footer="Passos para a elaboração de estratégias após o DEI">
<img class="img-fluid" src="imagens/imagem09.jpg" alt="Passos para a elaboração de estratégias após o DEI">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 9:</strong> Passos para a elaboração de estratégias após o DEI <br><strong>Fonte:</strong> Almeida (2000)</p>
</div>
<p class="Texto">
Uma síntese das principais características e diferenças dos diagnósticos estratégicos externo e interno de uma organização é apresentada no Quadro 3.
</p>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="CorLaranja">
<tr style="background-color: #fde7a7;">
<th scope="col">
<h5><strong> </strong></h5>
</th>
<th scope="col">
<h5><strong>Externo </strong></h5>
</th>
<th scope="col">
<h5><strong>Interno </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
O que se procura
</td>
<td class="Texto">
Eficácia
</td>
<td class="Texto">
Eficiência
</td>
</tr>
<tr>
<td class="Texto">
Horizonte de Tempo Analisado
</td>
<td class="Texto">
Futuro
</td>
<td class="Texto">
Presente
</td>
</tr>
<tr>
<td class="Texto">
Produto
</td>
<td class="Texto">
Oportunidades e ameaças
</td>
<td class="Texto">
Pontos fortes e fracos
</td>
</tr>
<tr>
<td class="Texto">
Ação
</td>
<td class="Texto">
A entidade deverá se adaptar ao futuro do ambiente
</td>
<td class="Texto">
A ação só depende da própria entidade
</td>
</tr>
<tr>
<td class="Texto">
Como será montada a estratégia
</td>
<td class="Texto">
Procura-se aproveitar as oportunidades e evitar as ameaças
</td>
<td class="Texto">
Procura-se tirar vantagem dos pontos fortes e reduzir os pontos fracos
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
<center><p class="FonteFigura CorLaranja"><strong>Quadro 03:</strong> Principais características e diferenças do diagnóstico estratégico
<br><strong>Fonte:</strong> Almeida (2000)</p></center>
</section>
<br>
<p class="Texto">
As imagens 10 e 11 apresentam de forma esquemática os produtos dos Diagnósticos Estratégicos Externo e Interno.
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem10.png" data-toggle="lightbox" data-footer="Passos para a elaboração de estratégias após o DEI">
<img class="img-fluid" src="imagens/imagem10.png" alt="Passos para a elaboração de estratégias após o DEI">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 10:</strong> Passos para a elaboração de estratégias após o DEI</p>
</div>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem11.png" data-toggle="lightbox" data-footer="Os Produtos do Diagnostico Estratégico Interno">
<img class="img-fluid" src="imagens/imagem11.png" alt="Os Produtos do Diagnostico Estratégico Interno">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 11:</strong> Os Produtos do Diagnostico Estratégico Interno</p>
</div>
<br><br>
<div class="text-center">
<a href="Topico02.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico03.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Referencias.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h3 class="font-bold">Referências</h3>
<hr>
<ul style="list-style: none;">
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
ALLEBRANDT, Sé<NAME> et al. <strong>Planejamento estratégico</strong> local. Coleção Educação a Distância, Série Livro-Texto. Ijuí: Editora Unijuí, 2009.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. <strong>Gestão de Processos e a Gestão Estratégica</strong>. Rio de Janeiro. Qualitymark, 2003.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
ALMEIDA, <NAME>. <strong>Manual de planejamento estratégico</strong>: desenvolvimento de um plano estratégico com a utilização de planilhas Excel. São Paulo: Atlas, 2001.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
ANDER-EGG, Ezequiel. <strong>Introducción a la planificación</strong>. Buenos Aires: Lumen, 1995.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
ATLAS SOCIOECONÔMICO RIO GRANDE DO SUL. <strong>Regiões Funcionais de Planejamento</strong>, 2011. Acesso em: 10 mai. 2012.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
BERGUE, <NAME>; KLERING, <NAME>. <strong>A redução sociológica no processo de transposição de tecnologias gerenciais</strong>. Organizações & Sociedade (O&S), v. 17, n. 52, p. 137-155, jan./mar. 2010.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
BUARQUE, <NAME>. <strong>Construindo o desenvolvimento local sustentável</strong>: metodologia de planejamento. São Paulo: Garamond, 2002.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
COELHO, <NAME>.; <NAME>.; <NAME>. <strong>PRÓ-RS IV</strong>: Propostas estratégicas para o desenvolvimento regional do Estado do Rio Grande do Sul (2011-2014). Passo Fundo: Passografic, 2010.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
COSTA, <NAME>; KRUCKEN, Lia. O uso de mapas para promover e gerenciar o conhecimento estratégico nas organizações. In: ANGELONI, <NAME> (Org.). <strong>Gestão do conhecimento no Brasil</strong>: casos, experiências e práticas de empresas privadas. Rio de Janeiro: Qualitymark, 2010. p. 3-20.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>.; <NAME>. <strong>Feitas para Durar</strong>: Práticas bem-sucedidas de empresas visionárias. Rio de Janeiro. Rocco, 1995.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. e <NAME>. <strong>Planejamento Estratégico</strong>: fundamentos e aplicações. Rio de Janeiro. Campus, 2004.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>.; <NAME>. (Org.) <strong>Gestão da Estratégia</strong>: experiências e lições de empresas brasileiras. Rio de Janeiro. Campus, 2005.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
DAGNINO, <NAME> - <strong>Planejamento estratégico governamental</strong> / <NAME>. – Florianópolis. Departamento de Ciências da Administração / UFSC; [Brasília]: CAPES: UAB, 2009. 166p.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
DALAND, <NAME>. <strong>Estratégia e estilo do planejamento brasileiro</strong>. São Paulo: Lidador, 1967.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. <strong>Administração em Organizações sem fins lucrativos</strong>: princípios e práticas. São Paulo: Pioneira, 1997.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
FINAMORE, <NAME> (Org.). <strong>Planejamento estratégico da Região da Produção</strong>: do diagnóstico ao Mapa Estratégico 2008/2028. Passo Fundo: UPF Editora, 2010. Acesso em: 29 nov. 2011.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>; <NAME>. <strong>Estratégia e Gestão Empresarial</strong>. Rio de Janeiro. Campus,2004.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. <strong>A redução sociológica</strong>: introdução ao estudo da razão sociológica. Rio de Janeiro: Edições Tempo Brasileiro Ltda., 1965.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>.; <NAME>. <strong>Competindo pelo futuro</strong>: estratégias inovadoras para obter o controle do. seu setor e criar os mercados de amanhã. Rio de Janeiro. Campus, 1995.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
JULIO, <NAME>. <strong>A Arte da Estratégia</strong>. 7. ed. Rio de Janeiro. Campus, 2005.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>; NORTON, <strong><NAME> e Norton na Prática</strong>. Rio de Janeiro. Campus, 2004.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
_______. <strong>A Estratégia em Ação</strong>: Balanced Scorecard. Rio de Janeiro. Campus, 1997.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
_______. <strong>Mapas estratégicos</strong> – balanced scorecard: convertendo ativos intangíveis em resultados tangíveis. Rio de Janeiro: Elsevier, 2004.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
KLERING, <NAME>; <NAME>; GUADAGNIN, <NAME>. <strong>Novos caminhos da Administração Pública brasileira</strong>. Análise-PUCRS, v. 21, n. 1, p. 4-17, jan./jun. 2010.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. <strong>Estratégias políticas</strong>: Chimpanzé, Maquiavel e Gandhi. São Paulo: Edições Fundap, 1996.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
MINTZBERG, Henry; AHLSTRAND, Bruce; LAMPEL, Joseph. </trong>Safári de estratégia</strong>: um roteiro pela selva do planejamento estratégico. Porto Alegre: Bookman, 2000. NONAKA, Ikujiro; <NAME>. Criação do conhecimento na empresa. Rio de Janeiro: Campus, 1997.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
OLIVEIRA, <NAME>. <strong>Planejamento Estratégico</strong>: conceitos, metodologia e práticas. 13. ed. São Paulo: Atlas, 1999.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
PEREIRA, <NAME>. <strong>Gestão Estratégica</strong>. São Paulo, 2009.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. <strong>Estratégia Competitiva</strong>. Rio de Janeiro: Campus, 2005.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
SEN, Amartya. <strong>Desenvolvimento como liberdade</strong>. São Paulo: Companhia das Letras, 2000.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
SILVEIRA, <NAME>. <strong>Abordagem sistêmica pra diagnóstico da vocação competitiva e desenvolvimento microrregional</strong>: o caso de Blumenau. 1999. 71 f. Dissertação (Mestrado) – Programa de Pós-Graduação em Engenharia de Produção, Universidade Federal de Santa Catarina, Florianópolis, 1999.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>. <strong>A Quinta Disciplina</strong>: arte e prática da organização que aprende. São Paulo: Best Seller, 2001.
</li><br>
<li>
<i class="fa fa-book fa-lg CorLaranja" aria-hidden="true"></i>
<NAME>.<strong> O que é estratégia</strong>. São Paulo: <NAME>, 2002.
</li>
<br>
<br><br>
<div class="text-center">
<a href="Topico03.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href=".php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Topico01_2.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">2 - A Gestão Estratégica </h2>
<hr class="pontLaranja">
<p class="Texto">
A gestão estratégica é uma <strong>“metodologia”</strong> importante que visa assegurar o sucesso da empresa no momento atual, bem como principalmente o seu sucesso no futuro. Nesse sentido, a gestão estratégica inclui no mínimo três etapas distintas:
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> O planejamento estratégico,<br>
<i class="fa fa-arrow-right CorLaranja"></i> A execução,<br>
<i class="fa fa-arrow-right CorLaranja"></i> O controle.<br>
</ul>
<p class="Texto">
<strong>O planejamento estratégico, a primeira etapa da gestão estratégica, visa:</strong>
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Identificar os riscos e propor planos para minimizá-los e, até mesmo, evitá-los;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Identificar os pontos fortes e fracos de uma organização em relação à sua concorrência e ao ambiente de negócio em que atua;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Conhecer o mercado e definir estratégias para os produtos e serviços.<br>
</ul>
<br>
<div class="row">
<div class="col-sm">
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem01.png" data-toggle="lightbox" data-footer="Os três tipos de planejamento dentro da “pirâmide organizacional” ">
<img class="img-fluid" src="imagens/imagem01.png" alt="Os três tipos de planejamento dentro da “pirâmide organizacional” " width="400" >
</a>
<p class="TituloFigura CorLaranja">
<strong>Figura 1:</strong> Os três tipos de planejamento dentro da “pirâmide organizacional”
</p>
</div>
</div>
<div class="col-sm Texto"><br>
O planejamento estratégico está relacionado aos objetivos de longo prazo e às ações que serão realizadas para alcançá-los, os quais afetam a organização como um todo. Ele é conceituado como um processo gerencial que possibilita ao executivo estabelecer o rumo a ser seguido. É geralmente de responsabilidade dos níveis mais altos da empresa. Na realidade, sem o envolvimento direto do principal executivo da empresa, como o líder da condução do processo estratégico em uma empresa, este dificilmente ocorrerá a contento.
</div>
</div>
<p class="Texto"><br><br>
Num segundo nível, o planejamento tático está relacionado aos objetivos de curto prazo e às ações que afetam somente uma parte da empresa. Ele tem como objetivo otimizar determinada área e não a empresa como um todo, sendo desempenhado por níveis organizacionais inferiores.
<br><br>E em um terceiro nível, o planejamento operacional, por sua vez, pode ser considerado como a formalização das metodologias de desenvolvimento e de implantação estabelecidas. Nesse nível se encontram, basicamente, os planos de ação ou planos operacionais.
<br><br>Como o planejamento estratégico trata a empresa como um todo e, perante seu ambiente, ele deve ser analisado quando se pretende estudar as estratégias traçadas, pois tem como objetivo a geração de vantagens competitivas para a empresa.
<br><br>Por fim, o planejamento estratégico – o primeiro passo da gestão estratégia de uma organização - é parte essencial do pensamento empresarial. No entanto, essa cultura estratégica ainda está pouco difundida no Brasil, exceto nas grandes organizações privadas, que já estão bem inseridas no contexto de globalização da economia e de competição global. Por outro lado, por exemplo, nos Estados Unidos, essa questão estratégica é o pré-requisito básico para a grande maioria das organizações, independente de seu tipo ou porte.
</p>
<br>
<h2 class="font-bold">2.1 - Os Elementos Principais da Gestão Estratégica </h2>
<hr class="pontLaranja">
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="text-white">
<tr style="background-color: #fc6b30;">
<th>
<h5><strong>Declaração de missão </strong></h5>
</th>
<th>
<h5><strong>Definição dos objetivos</strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
A missão é o elemento que traduz as responsabilidades e pretensões da organização junto ao ambiente e define o negócio, delimitando o seu ambiente de atuação. A missão da organização representa sua razão de ser, o seu papel na sociedade.
</td>
<td class="Texto">
A organização persegue simultaneamente diferentes objetivos em uma hierarquia de importância, de prioridades ou de urgência.
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
</section>
<br>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="CorLaranja">
<tr style="background-color: #fde7a7;">
<th scope="col">
<h5><strong>Visão de negócios </strong></h5>
</th>
<th scope="col">
<h5><strong>Fatores críticos de sucesso </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Mostra uma imagem da organização no momento da realização de seus propósitos no futuro. Trata-se não de predizer o futuro, mas de assegurá-lo no presente. A visão de negócios cria um “estado de tensão” positivo entre o mundo como ele é e como gostaríamos que fosse (sonho). A visão de negócios associada a uma declaração de missão compõe a intenção estratégica da organização.
</td>
<td class="Texto">
Esse recurso metodológico é uma etapa do processo inserida entre o diagnóstico e a formulação das estratégias. Ele procura evidenciar questões realmente críticas para a organização, emergindo dos problemas apontados na análise realizada com a aplicação do modelo SWOT, de cuja solução dependerá a consecução da missão. Os determinantes de sucesso também são denominados fatores críticos de sucesso e encaminham as políticas de negócios.
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
</section>
<br>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="text-white">
<tr style="background-color: #fc6b30;">
<th scope="col">
<h5><strong>Diagnóstico estratégico externo </strong></h5>
</th>
<th scope="col">
<h5><strong>Diagnóstico estratégico interno </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Procura antecipar oportunidades e ameaças para a concretização da visão, da missão e dos objetivos empresariais. Corresponde à análise de diferentes dimensões do ambiente que influenciam as organizações. Estuda também as dimensões setoriais e competitivas.
</td>
<td class="Texto">
Corresponde ao diagnóstico da situação da organização diante das dinâmicas ambientais, relacionando-a às suas forças e às fraquezas e criando as condições para a formulação de estratégias que representam o melhor ajustamento da organização no ambiente em que atua. O alinhamento dos diagnósticos externos e internos produz as premissas que alicerçam a construção de cenários.
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
</section>
<br>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="CorLaranja">
<tr style="background-color: #fde7a7;">
<th scope="col">
<h5><strong>Análise dos públicos de interesse (stakeholderes) </strong></h5>
</th>
<th scope="col">
<h5><strong>Formalização do plano </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Quando foi definida a estratégia, já se observou que só se tem sucesso na estratégia elaborada ao atender às necessidades dos públicos de interesse. Um stakeholder consiste em uma pessoa, um grupo de pessoas ou uma organização que pode influenciar ou ser influenciado pela organização, como consumidores, usuários, empregados, proprietários, dirigentes, governo, instituições financeiras, opinião pública ou acionistas. A análise consiste na identificação dos grupos e de seus interesses e poderes de influência no que diz respeito à missão da organização.
</td>
<td class="Texto">
Um plano estratégico é um plano para a ação, mas não basta somente a formulação das estratégias dessa ação. É necessário implementálas por meio de programas e projetos específicos. Requer um grande esforço de pessoal e emprego de modelos analíticos para a avaliação, a alocação e o controle de recursos. Esse elemento metodológico exige uma abrangência completa de todas as áreas de tomada de decisão da organização; uma racionalidade formal no processo de tomada de decisão e um firme controle sobre o trabalho.
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
</section>
<br>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="text-white">
<tr style="background-color: #fc6b30;">
<th scope="col">
<h5><strong>Auditoria de desempenho e resultados (reavaliação estratégica) </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Trata-se de rever o que foi implementado para decidir os novos rumos do processo, mantendo as estratégias implantadas com sucesso e revendo as más estratégias. A reavaliação das estratégias aparece como resultado de um processo de medição de diversos grupos de influências associados a cada estratégia.
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
</section>
<br>
<h2 class="font-bold">2.2 - Por que Gestão (Planejamento) Estratégica(o)? </h2>
<hr class="pontLaranja">
<p class="Texto">
As múltiplas ferramentas de gestão disponíveis nos dias atuais, seja na área de qualidade (TQM, ISO 9001 ou 6-sigma), seja na área de marketing (CRM), ou seja, por exemplo, na área de produção (produção enxuta – lean manufacturing) se forem aplicados sem visão estratégica na maioria das vezes, focam-se em problemas que não necessariamente têm influência externa, ou seja, esses programas, às vezes, falham por uma visão excessiva e exclusivamente interna, fazendo com que as prioridades possam estar mal definidas em termos de resultados efetivamente importantes para a posição competitiva da empresa.
<br><br>Para Drucker (1994), a cada três anos, uma organização precisa desafiar o status quo através do questionamento:
</p>
<div class="alert alert-light-primary" role="alert">
<p class="Texto text-center">
<strong>
“Se eu estivesse nesse negócio, serviço, canal de distribuição etc. entraria nele agora?”
</strong>
</p>
</div>
<p class="Texto">
A resposta a essa simples pergunta de Drucker <strong>exige uma visão sistêmica de toda a organização e de seus múltiplos negócios, quando for o caso</strong>. Esse é o objetivo da Gestão Estratégica. Para isso, é necessário uma <strong>Estratégia Organizacional</strong>, pois sem ela é como voar num boeing sem piloto e sem instrumentos automáticos.
<br><br><strong>As principais vantagens da Gestão Estratégica (Planejamento Estratégico) são:</strong></br>
</p>
<ul class="fa-ul Texto">
<i class="fa fa-arrow-right CorLaranja"></i> fornece uma visão sistêmica, pois aprofunda o conhecimento sobre a organização, mercado/clientes, concorrentes, parceiros e fornecedores;<br>
<i class="fa fa-arrow-right CorLaranja"></i> egiliza e fundamenta decisões, uma vez que entre os líderes da organização sobre o que realmente é importante;<br>
<i class="fa fa-arrow-right CorLaranja"></i> estabelece uma direção única, porque alinha os esforços de todos na organização para o atendimento de objetivos comuns;<br>
<i class="fa fa-arrow-right CorLaranja"></i> melhora a capacidade de adaptação, por facilitar a reestruturação organizacional frente às mudanças de cenários externo e de competição;<br>
<i class="fa fa-arrow-right CorLaranja"></i> melhora a alocação de recursos;<br>
<i class="fa fa-arrow-right CorLaranja"></i> reforça a motivação;<br>
<i class="fa fa-arrow-right CorLaranja"></i> melhora o controle;<br>
<i class="fa fa-arrow-right CorLaranja"></i> sistematiza ciclos de melhoria contínua da organização.<br>
</ul>
<p class="Texto">
<strong>Para Oliveira (1999), a Gestão Estratégica compreende:</strong>
</p>
<ul class="fa-ul Texto">
<i class="fa fa-arrow-right CorLaranja"></i> planejamento Estratégico;<br>
<i class="fa fa-arrow-right CorLaranja"></i>organização Estratégica;<br>
<i class="fa fa-arrow-right CorLaranja"></i>direção Estratégica;<br>
<i class="fa fa-arrow-right CorLaranja"></i>controle Estratégico; e<br>
<i class="fa fa-arrow-right CorLaranja"></i>desenvolvimento Estratégico.<br>
</ul>
<p class="Texto">
<strong>Oliveira (1999) desdobra o Planejamento Estratégico nas fases e etapas apresentadas, resumidamente, na imagem a seguir.</strong>
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem02.png" data-toggle="lightbox" data-footer="As fases e etapas do Planejamento Estratégico">
<img class="img-fluid" src="imagens/imagem02.png" alt="As fases e etapas do Planejamento Estratégico" width="550">
</a>
<p class="TituloFigura CorLaranja"><strong>Imagem 2:</strong> As fases e etapas do Planejamento Estratégico <br><strong>Fonte:</strong> (Oliveira, 1999) </p>
</div>
<p class="Texto">
Por outro lado, Chiavenato (2004) desdobra o Planejamento Estratégico numa sequência distinta, conforme se verifica na imagem 3.
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem03.png" data-toggle="lightbox" data-footer="As fases e etapas do Planejamento Estratégico">
<img class="img-fluid" src="imagens/imagem03.png" alt="As fases e etapas do Planejamento Estratégico" width="550">
</a>
<p class="TituloFigura CorLaranja"><strong>Imagem 3:</strong> As fases e etapas do Planejamento Estratégico <br><strong>Fonte:</strong> (Chiavenato, 1999). </p>
</div>
<p class="Texto">
Em resumo, os elementos que compõem a gestão estratégica estão elencados em ambas as propostas aqui apresentadas.
<br><br>Uma atividade essencial no processo de gestão estratégica de uma organização é a reflexão sobre a sua intenção estratégica.
</p>
<!-- Citação 2 -->
<blockquote class="blockquoteEad3">
<p class="Texto"><strong>“A intenção estratégica representa a alavancagem de todos os recursos internos, capacidades e competências essenciais de uma organização com a finalidade de cumprir suas metas no ambiente competitivo. Ela somente pode existir quando todas as pessoas da organização em todos os níveis e áreas estão empenhadas na busca de um desempenho que seja único e significativo. É essa intenção estratégica que proporciona aos membros da organização a meta que merece seu esforço, dedicação e compromisso pessoal de permanecer como o melhor no mercado ou derrubar a empresa que está no pódio.”</strong>
<footer class="blockquote-footer CorLaranja"><i class="fas fa-graduation-cap CorLaranja"></i> (<NAME>; <NAME>, 1989)</footer>
</blockquote>
<br>
<p class="Texto">
Esse processo consiste no estabelecimento das “pedras fundamentais” sobre as quais uma empresa se encontra organizada, tais como:
</p>
<ul class="fa-ul Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Qual é o negócio da organização?<br>
<i class="fa fa-arrow-right CorLaranja"></i> Qual a razão de existir da organização?<br>
<i class="fa fa-arrow-right CorLaranja"></i> Quais os caminhos que a organização espera trilhar no futuro para sobreviver num mundo altamente globalizado e competitivo?
</ul>
<br><br>
<div class="text-center">
<a href="Topico01.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico01_3.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Topico03_1.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">1 - O Processo de Formulação de Estratégias</h2>
<hr class="pontLaranja">
<p class="Texto">
Definir os objetivos estratégicos é uma tarefa a ser conduzida pelos principais gestores de uma organização. Essa definição não é tarefa fácil, pois toda organização possui diferentes grupos com diferentes expectativas.
<br><br>Esses grupos, os <strong class="CorLaranja"><em>stakeholders</em></strong>, ( compreendem os funcionários, os clientes, os fornecedores, a direção, o conselho administrativo, os financiadores, os parceiros, as agências governamentais e outras organizações que possuam uma relação direta ou indireta com a organização ) têm critérios diferentes a respeito do que esperam da organização.
<br><br>A periodicidade da definição e da revisão dos objetivos estratégicos de uma organização é função da velocidade de mudanças nos setores em que ela atua.
<br><br>Uma das formas mais conhecidas, difundidas e utilizadas é a análise SWOT que propõe uma avaliação dos pontos fortes (<em>strenghts</em>) e pontos fracos (<em>weaknesses</em>) da organização à luz das oportunidades (<em>opportunities</em>) e das ameaças (<em>threats</em>) do ambiente externo. A ênfase está nas avaliações das situações externa e interna, porque são os fatores considerados muito relevantes para a formação da estratégia. Após verificar as diversas possíveis estratégias, então é feita a escolha das melhores. As estratégias resultantes desse processo devem ser únicas, simples e explícitas.
</p>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="text-white">
<tr style="background-color: #fde7a7;">
<th scope="col">
<h5><strong> </strong></h5>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="Texto">
Outra forma de se formular a estratégia é através dos modelos de <strong class="CorLaranja">Porter</strong> ( As 5 forças de Porter e as Estratégias Genéricas de Porter conforme será detalhado mais a frente.). Para ele:
<br><br>
<!-- Citação -->
<blockquote class="blockquoteEad2">
<strong>“O desenvolvimento de uma estratégia ompetitiva é, em essência, o desenvolvimento de uma fórmula ampla para o modo como a empresa irá competir, quais deveriam ser suas metas e as políticas necessárias para levar-se a cabo estas metas.”.</strong>
<footer class="blockquote-footer"><i class="fas fa-graduation-cap "></i> PORTER (2013 )</footer>
</blockquote>
</div>
<br>
</td>
</tr>
</tbody>
</table>
</div>
<hr class="BackLaranja">
</section>
<br>
<p class="Texto">
Para Porter, a estratégia de uma organização deve ser baseada na estrutura de mercado em que ela atua, não dando muita ênfase às capacidades internas da empresa, tendo como resultado desse processo estratégias genéricas.
<br><br>Diversas outras são as correntes que propõem modelos diferentes para a formulação de estratégias nas organizações. Uma delas, que vem recentemente se destacando, é a da organização que aprende. Nesse caso, a formulação das estratégias caminha ao lado da sua implantação, ou seja, não existe uma dissociação entre pensar e agir. Os defensores dessa corrente de pensamento estratégico defendem que numa organização, que aprende, todas as pessoas, que fazem parte da organização, podem contribuir para o processo de criação das estratégias e a organização tem a possibilidade de experimentar e consequentemente aprender. Assim, a formulação das estratégias passa a ser um processo de aprendizado coletivo ao longo do tempo.
<br><br>O relevante é que o processo de formulação de estratégias possui diversas formas, de acordo com cada tipo de organização. Vale destacar que, atualmente, devido à velocidades das mudanças, com maior ênfase na globalização e nas mudanças tecnológicas, é cada vez mais considerado o fator humano dentro das organizações, estimulando a criatividade, a iniciativa e o aprendizado contínuo, pois segundo Davenport e Prusak (1998):
</p>
<!-- Citação -->
<blockquote class="blockquoteEad3">
<p class="Texto"><strong>“… numa economia global, o conhecimento pode ser a maior vantagem competitiva da empresa.”</strong>
<footer class="blockquote-footer CorLaranja"><i class="fas fa-graduation-cap CorLaranja "></i> DAVENPORT; PRUSAK (1998)</footer>
</blockquote>
<br>
<p class="Texto">
Segundo <strong class="CorLaranja">Júlio</strong> (<NAME>, no livro “A Arte da Estratégia”)(2005), os objetivos estratégicos mais comuns de uma organização podem ser classificados como: crescer, ou seja, aumentar as vendas. Isso até pode ser escrito de outra maneira, como <strong>“inauguração de novas lojas”, “aquisição de outra empresa”, “estabelecimento de aliança estratégica”</strong>. Porém, segundo Prahalad, crescer tem de ser o objetivo de todas as organizações. <strong>“É crescer ou morrer”</strong>, diz ele.
</p>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse1" aria-expanded="false" aria-controls="collapse1">
<h3>Ganhar participação no mercado</h3>
</button>
</h2>
</div>
<div id="collapse1" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">Trata-se de estabelecer um determinado nível de market share para ser atingido em determinado período de tempo. </p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<p class="Texto">
quando uma organização entra em um novo mercado e quer construir uma participação de 15% em cinco anos.
</p>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingtwo">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse2" aria-expanded="false" aria-controls="collapse2">
<h3>Aumentar a rentabilidade</h3>
</button>
</h2>
</div>
<div id="collapse2" class="collapse" aria-labelledby="headingtwo" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Um objetivo organizacional bastante comum é o aumento dos lucros. Porter chega a dizer que esse é o único objetivo que realmente importa. Para ele, a eficiência e o acerto da estratégia de uma organização devem ser medidos pelo seu resultado econômico.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingthree">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse3" aria-expanded="false" aria-controls="collapse3">
<h3>Superar uma crise</h3>
</button>
</h2>
</div>
<div id="collapse3" class="collapse" aria-labelledby="headingthree" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
No mundo dos negócios, o objetivo de <strong>“sobreviver”</strong> é básico, principalmente, em épocas turbulentas para a economia ou para preparar-se para superar uma crise que poderá a vir acontecer futuramente.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingfour">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse4" aria-expanded="false" aria-controls="collapse4">
<h3>Fortalecer a marca e a imagem ou ampliar a visibilidade</h3>
</button>
</h2>
</div>
<div id="collapse4" class="collapse" aria-labelledby="headingfour" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Esse tipo de objetivo tem sido cada vez mais importante na era da ultracompetição globalizada, em que todo poder pertence ao cliente. Melhorar a posição da marca da organização, ou da marca de seus principais produtos, em pesquisas do tipo Top of Mind é um dos modos de formular esse objetivo. Melhorar o atendimento ao cliente é outro.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<p class="Texto">
Júlio (2007) sugere que as estratégias a serem formuladas sejam smart.
</p>
<section id="quadroConteudo">
<div class="table-responsive">
<table class="table table-hover">
<thead class="text-white">
<tr style="background-color: #fde7a7;">
<thead>
</thead>
<tbody>
<tr><br>
<td class="Texto">
<font size="5">
S
</font>
</td>
<td class="Texto">
e<u>S</u>pecífico
</td>
<td class="Texto">
Uma ação (ou um comportamento) observável tem de poder ser descrito ligada a uma taxa, número, porcentagem ou frequência. Como, exemplo: aumentar as vendas em 20%.
</td>
</tr>
<tr>
<td class="Texto">
<font size="5">
M
</font>
</td>
<td class="Texto">
<u>M</u>ensurável
</td>
<td class="Texto">
De modo geral, é o que se pode medir por meio de um sistema ou método. No exemplo mencionado acima, pode-se medir o crescimento de vendas por meio do resultado do faturamento.
</td>
</tr>
<tr>
<td class="Texto">
<font size="5">
A
</font>
</td>
<td class="Texto">
<u>A</u>lcançável
</td>
<td class="Texto">
Esse é o princípio de estabelece rum ponto B a ser alcançado a partir de um ponto A conhecido. Se a meta for difícil demais em relação à capacidade da instituição, os funcionários nem "dão partida".
</td>
</tr>
<tr>
<td class="Texto">
<font size="5">
R
</font>
</td>
<td class="Texto">
<u>R</u>elevante
</td>
<td class="Texto">
O objetivo tem de ser tão relevante para a empresa e para seus indivíduos que consiga lhes injetar ânimo para lutar por ele. Aqui, relevante também pode ser considerado como sinônimo de "desafiador".
</td>
</tr>
<tr>
<td class="Texto">
<font size="5">
T
</font>
</td>
<td class="Texto">
<u>T</u>empo definido
</td>
<td class="Texto">
É imprescindível sugerir o estabelecimento de uma data (dia, mês e ano) para o objetivo ser totalmente alcançado. Além disso, é altamente recomendável dividi-lo em várias metas, cada qual com sua data.
</td>
</tr>
</tbody>
</table>
<div class="FonteFigura CorLaranja"><center><strong>Quadro 04</strong> – Metodologia Smart<br> <strong>Fonte:</strong> Júlio (2007)<center></div>
</div>
</section>
<br>
<h2 class="font-bold">1.1 - Métodos para a Formulação de Estratégias</h2>
<hr class="pontLaranja">
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingfive">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse5" aria-expanded="false" aria-controls="collapse5">
<h3>Matriz SWOT </h3>
</button>
</h2>
</div>
<div id="collapse5" class="collapse" aria-labelledby="headingfive" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Uma ferramenta bastante utilizada no delineamento das ações, auxiliando também na sua priorização, é a matriz SWOT (Forças, Fraquezas, Oportunidades e Ameaças), em que se faz o relacionamento entre os ambientes interno e externo.
<br><br>O produto da análise SWOT é uma série de decisões sobre que oportunidades serão aproveitadas, quais ameaças serão enfrentadas, que pontos fracos serão minimizados e que pontos fortes serão fortalecidos.
<br><br>Uma incidência de ameaças externas a muitos pontos fracos indica a necessidade de sobrevivência, ou seja, a organização precisa reduzir custos, desinvestir ou até vender esse negócio.
</p><br>
<div class="row">
<div class="col-sm">
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem12.png" data-toggle="lightbox" data-footer="Tipos básicos de estratégias a serem adotadas a partir da Matriz SWOT">
<img class="img-fluid" src="imagens/imagem12.png" alt="Tipos básicos de estratégias a serem adotadas a partir da Matriz SWOT">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 1:</strong> Tipos básicos de estratégias a serem adotadas a partir da Matriz SWOT </p>
</div>
</div>
<div class="col-sm Texto">
Já se a instituição encontrar forte relacionamento de pontos fracos internos com oportunidades externas, deve-se buscar rapidamente o crescimento para solidificar o posicionamento da organização no setor.
<br><br>Quando se tem maior incidência de pontos fortes aliados a oportunidades, tem-se, provavelmente, uma posição, mesmo que potencial, de liderança de mercado, sendo necessário a organização desenvolvê-la.
</div>
</div>
<p class="Texto">
Por fim, um cruzamento de ameaças e pontos fortes indica uma possível estagnação do negócio em que a empresa tem uma posição de liderança e aponta para a necessidade de manutenção de sua posição.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingsix">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse6" aria-expanded="false" aria-controls="collapse6">
<h3>Abordagem da Estratégia Competitiva – Modelo de Porter </h3>
</button>
</h2>
</div>
<div id="collapse6" class="collapse" aria-labelledby="headingsix" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Para Porter, a estratégia consiste em uma série coerente de ações ofensivas ou defensivas, formuladas com o intuito de proporcionar à organização uma posição sólida no mercado em que atua e de superar a concorrência. Tal posição é alcançada por meio do domínio das cinco forças competitivas que delimitam a concorrência em uma indústria:
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Ameaça de novos entrantes;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Poder de barganha dos fornecedores;<br>
<i class="fa fa-arrow-right CorLaranja"></i>Poder de barganha dos compradores;<br>
<i class="fa fa-arrow-right CorLaranja"></i>Ameaça de produtos ou serviços substitutos;<br>
<i class="fa fa-arrow-right CorLaranja"></i>Rivalidade entre concorrentes.
</ul>
<p class="Texto">
Cabe ressaltar que quando Porter se refere às indústrias, ele utiliza esse termo de forma genérica, pois tanto se refere às indústrias de bens (automobilística, química. metalúrgica, dentre outras) quanto às indústrias de serviço (hotelaria, entretenimento, turismo, dentre outras).
<br><br>O conjunto dessas 5 forças determina o potencial de lucro final numa determinada indústria, sendo medido em termos de retorno de longo prazo sobre o capital investido, pois nem todas as indústrias têm o mesmo potencial.
</p>
<!-- Titulo Figura -->
<div class="text-center">
<a href="imagens/imagem13.png" data-toggle="lightbox" data-footer="Modelo das 5 forças de Porter">
<img class="img-fluid" src="imagens/imagem13.png" alt="Modelo das 5 forças de Porter">
</a>
<p class="TituloFigura CorLaranja"><strong>Figura 1:</strong> Modelo das 5 forças de Porter</p>
</div>
<p class="Texto">
Elas diferem, fundamentalmente, em seu potencial de lucro final, à medida que o conjunto das forças difere no sentido de diminuir a taxa de retorno sobre o capital investido em relação à taxa competitiva básica de retorno, que é aproximadamente igual ao rendimento sobre títulos do governo a longo prazo, ajustados para mais pelo risco do negócio (PORTER, 1980).
<br><br>Em qualquer indústria, seja ela doméstica ou internacional, que produza um produto ou um serviço, as regras da concorrência estão englobadas nessas cinco forças competitivas. Seu vigor coletivo provém das habilidades das empresas em uma indústria (PORTER, 1980).
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<br><br>
<div class="text-center">
<a href="Topico03.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico03_2.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Topico02.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">2 - Diagnóstico Estratégico </h2>
<hr class="pontLaranja">
<p class="Texto"><strong>Objetivo:</strong> Apresentar conceitos e tipos de diagnóstico, considerando ambientes externos e internos, a fim de identificar oportunidades e ameaças da organização.</p>
<!-- Citação -->
<blockquote class="blockquoteEad3">
<p class="Texto"><strong>“A realidade é como ela é e não como gostaríamos que ela fosse.”</strong>
<footer class="blockquote-footer CorLaranja"><i class="fas fa-graduation-cap CorLaranja"></i> Maquiavel</footer>
</blockquote>
<br>
<p class="Texto">
O Diagnóstico Estratégico de uma organização, também chamado por muitos autores de Análise do Ambiente, tem por objetivo mapear o maior número de variáveis que de alguma forma afetam direta ou indiretamente uma organização.
<br><br><strong>Para Ansoff e McDonnell (1993), o Diagnóstico Estratégico é o procedimento necessário para responder a duas perguntas:</strong>
</p>
<div class="alert alert-light-primary" role="alert">
<p class="Texto">
<strong>
Como diagnosticar os desafios ambientais futuros com os quais se defrontará a instituição?
<br><br>Como determinar a reação estratégica da instituição que garantirá o sucesso?.
</strong>
</p>
</div>
<p class="Texto">Mudanças são inevitáveis e algumas vezes inesperadas. O Diagnóstico Estratégico é uma ferramenta valiosíssima para prever ou adaptar-se às mudanças ou, no mínimo, não ser surpreendido por elas. É um instrumento que permite ao gestor verificar a situação real de uma organização bem como:</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Descobrir a sua essência;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Criar um contexto para a formulação das estratégias;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Conhecer aspectos importantes (natureza do setor, tendências do mercado, intensidade da concorrência etc.) que não estão sob seu controle;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Revelar forças e fraquezas em um dado momento.
</ul>
<br><br>
<div class="text-center">
<a href="Topico01_3.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico02_1.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Apresentacao.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">Apresentação</h2>
<hr class="pontLaranja">
<p class="Texto">
Neste módulo final, abordaremos o planejamento estratégico setorial na perspectiva da gestão, diagnóstico e formulação estratégica, tendo por base os cinco princípios básicos do alinhamento estratégico.
<br><br>A elaboração do conteúdo é fundamentada, principalmente nos trabalhos produzido por: <NAME> e <NAME>.
</p>
<br>
<h2 class="font-bold">Objetivo</h2>
<hr class="pontLaranja">
<p class="Texto">
Abordar o planejamento estratégico setorial na perspectiva da gestão,diagnóstico e formulação estratégica.
</p>
<br><br>
<div class="text-center">
<a href="Topico01.php" type="button" class="btn btn-outline-success btn-sm">Próxima página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body>
</html><file_sep>/Topico01_3.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">3 - Missão, Visão e Valores: Conceitos </h2>
<hr class="pontLaranja">
<!-- collapse1 -->
<section id="Missão">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingOne">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse1" aria-expanded="false" aria-controls="collapse1">
<h3><center>Missão</center></h3>
</button>
</h2>
</div>
<div id="collapse1" class="collapse" aria-labelledby="headingOne" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Significa dizer qual a razão de ser da instituição, para que ela existe.
<br><br>Fórmula da missão do ponto de vista da qualidade:
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> O QUE FAZER + POR QUE FAZER + PARA QUEM FAZER
</ul>
<p class="Texto">
<strong>
A missão tem como foco o produto/serviço e os clientes/público beneficiário.
</strong>
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<p class="Texto">
"Integrar as ações governamentais, por meio da coordenação do planejamento de gestão pública, visando ao desenvolvimento do Estado e à promoção da cidadania." (Secretaria de Estado e Planejamento e Gestão de Minas Gerais)
<br><br>"Gerir o planejamento de forma a promover o desenvolvimento sustentável do Estado do Pará."(Secretaria de Planejamento do Estado do Pará)
</p>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<br>
<!-- collapse2 -->
<section id="Visão">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingtwo">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse2" aria-expanded="false" aria-controls="collapse2">
<h3><center>Visão</center></h3>
</button>
</h2>
</div>
<div id="collapse2" class="collapse" aria-labelledby="headingtwo" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
É uma imagem mental, uma descrição daquela situação futura e desejada, que todos os envolvidos almejam. Representa aonde se quer chegar, em um período de tempo determinado.
<br><br>A visão descreve o futuro desejado, a partir dos esforços individuais, dos esforços das equipes e da alocação de recursos. Embora desafiadora, a visão precisa ser prática, realista e visível. Se não podemos ver claramente o que queremos ser no futuro, certamente não conseguiremos alcançar. Tudo não passará de uma ilusão. Por outro lado, se a visão não for um desafio que mobilize os esforços, não passará de rotineira continuidade.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<p class="Texto">
<em>"Ser excelência em gestão pública, incorporando-a como valor de Estado." (Secretaria de Estado e Planejamento e Gestão de Minas Gerais)
<br><br>"Ser referência na gestão do planejamento estadual."(Secretaria de Planejamento do Estado do Pará)</em>
</p>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</section>
<br>
<!-- collapse3 -->
<section id="Valores">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingthree">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse3" aria-expanded="false" aria-controls="collapse3">
<h3><center>Valores </center></h3>
</button>
</h2>
</div>
<div id="collapse3" class="collapse" aria-labelledby="headingthree" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Servem de guia e estabelecem critérios para os comportamentos e atitudes das pessoas responsáveis por tomar decisões e implementar ações na organização.
<br><br>Os valores são, em outros termos, os limites éticos pelos quais se pautam todos que constituem a organização.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<p class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Compromisso com o social;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Ações desenvolvidas com competência, ética, honestidade e transparência;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Flexibilidade para aceitar e promover as mudanças;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Respeito e zelo pela coisa pública;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Senso de equipe e valorização do ser humano;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Entender e satisfazer as expectativas dos clientes internos e externos;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Agir proativamente visando alcançar melhores índices de desempenho;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Servidores comprometidos com os resultados da organização;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Seriedade e transparência nas ações.
</p>
</td>
</tr>
</table>
</div>
<p class="Texto">
<strong>Objetivos Estratégicos</strong>
<br><br>Intenções assertivas e factíveis na busca por algo de valor, de resultados de progresso, vantagens e melhorias, nas quais a situação futura almejada seja melhor que a presente. Devem ser globais e amplos, definidos com foco no longo prazo, com o propósito de cumprir a missão e alcançar a visão da instituição.
<br><br><strong>Características dos objetivos (SMART):</strong>
<br><br>Ao contrário da missão, que é definida de forma genérica, os objetivos devem ser definidos de forma concreta e devem apresentar as seguintes características:
</p><br>
<!-- Botão para acionar modal -->
<center>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Specific">
Specific (Específicos)
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Mensurable">
Mensurable (Mensuráveis)
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Attainable">
Attainable (Alcançáveis)
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Realistics">
Realistics (Realistas)
</button>
<button type="button" class="btn BackLaranja text-white" data-toggle="modal" data-target="#Time">
Time Bound (Tempo)
</button>
</center>
<!-- Modal -->
<div class="modal fade" id="Specific" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Specific (Específicos)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os objetivos devem ser específicos, claros, concisos e fáceis de entender (não devem ser generalistas). Devem compreender algo que possa ser claramente atingido
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="Mensurable" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Mensurable (Mensuráveis)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Sendo os objetivos constituídos por desejos ou aspirações, devem ser passíveis de serem avaliados, através da definição de parâmetros que verifiquem se foram ou não atingidos.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="Attainable" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Attainable (Alcançáveis)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os objetivos têm que ser alcançáveis. Esse aspecto implica que os objetivos sejam propostos em consonância com todos os seus intervenientes, para que estejam motivados e compreendam os objetivos e suas dificuldades. Devem ser definidos de modo congruente com o momento e os recursos.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="Realistics" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Realistics (Realistas)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os objetivos devem ser tangíveis e condizentes com a realidade da organização, deve existir a possibilidade de poderem vir a ser alcançados.
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
<div class="modal fade" id="Time" tabindex="-1" role="dialog" aria-labelledby="TituloModalCentralizado" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="TituloModalCentralizado">Time Bound (Tempo)</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Fechar">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
Os objetivos devem ser estabelecidos com um limite temporal bem definido (ou uma série de fases).
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
</div>
<br><br>
</div>
</div>
</div>
</section>
<br>
<br><br>
<div class="text-center">
<a href="topico01_2.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico02.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/assets/css/Topico02.2.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">2.2 - Atuação do Agente Jovem Ambiental na Educação Ambiental</h2>
<hr>
<p class="Texto">
O Agente Jovem Ambiental é um ator social que será capacitado para atuar em sua área
de influência, com o objetivo de sensibilizar mais pessoas para o cuidado com o nosso
planeta. Sua tarefa é levar a Educação Ambiental por onde for, ou seja, na sua
Comunidade, Bairro, Escola, Distrito ou Município.
</p>
<p class="Texto">
Ao longo deste curso, você irá aprender muita coisa sobre meio ambiente, desde
germinar uma planta, até elaborar um projeto de educação ambiental. Aliás, no final deste
curso, será elaborado um projeto, chamado de Plano de Ação Comunitário (PAC), no qual
vão constar as atividades dos AJAs no seu município. Então vá exercitando seu olhar
sobre a sua comunidade e o seu município: quais os problemas, quais as soluções, quais os meios para resolver, quais os parceiros, dentre outros itens que vamos explicar no
último módulo.
</p>
<div class="bd-callout bd-callout-success">
<p class="Texto">
Perguntas que devem ficar na cabeça dos AJAS desde já:
</p>
</div>
<div class="bd-callout bd-callout-warning">
<ul class="Texto pl-5">
<li>
Quais ações podem ser realizadas?
</li>
<li>
Quem, quando e onde pode realizá-las?
</li>
<li>
Quais podem ser os parceiros que apoiem cada ação?
</li>
<li>
Quais são os objetivos ou resultados esperados de cada ação?
</li>
</div>
<br><br>
<div class="text-center">
<a href="Topico02.1.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico02.3.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Topico03.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">3. Formulação Estratégica </h2>
<hr class="pontLaranja">
<p class="Texto">
<strong>Objetivo:</strong> Apresentar métodos para formulação de estratégias para aplicar nos processos de gestão da organização.
</p>
<p class="Texto">
<strong>
Ter estratégia é fazer escolhas. É escolher como uma organização vai se diferenciar das outras. Escolhas de fazer alguma coisa, como:
</strong>
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> que clientes atender;<br>
<i class="fa fa-arrow-right CorLaranja"></i> que produtos produzir e/ou vender;<br>
<i class="fa fa-arrow-right CorLaranja"></i> ou quais canais de venda utilizar.
</ul>
<p class="Texto">
<strong>
E também escolhas de deixar de fazer alguma coisa, conscientemente, como:
</strong>
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> que clientes não atender;<br>
<i class="fa fa-arrow-right CorLaranja"></i> em quais canais de venda não atuar;<br>
<i class="fa fa-arrow-right CorLaranja"></i> e que produtos e/ou serviços não oferecer.
</ul>
<p class="Texto">
É definir o que é o melhor para a organização, e não apenas usar o que é bom para todas as outras organizações. As escolhas estratégicas representam os grandes caminhos definidos por uma organização para alcançar vantagem competitiva, uma questão fundamental na gestão estratégica.
</p>
<div class="row">
<div class="col-sm">
<div class="CaixaLaranjaEad" role="alert">
<p class="Texto">
Para <strong class="CorLaranja">Porter</strong> ( <NAME> escreveu o livro Estratégia Competitiva, em 1980, um marco na história do tema estratégia, pois a partir deste livro o tema ganhou grande impulso por meio de pesquisas, da literatura, do ensino e da prática. ), eficiência operacional é uma necessidade, mas não é o suficiente para a garantia do sucesso a longo prazo de uma organização. É preciso ter uma estratégia. É absolutamente imprescindível que os principais gestores de uma organização invistam tempo em traçar estratégias que a diferenciem de seus concorrentes. <br>
</p>
</div>
</div>
<div class="col-sm">
<div class="CaixaLaranjaEad" role="alert">
<p class="Texto CorLaranja">
Hamel e Prahalad escreveram o artigo <em>“The core competence of the corporation”</em> para a Harvard Bussiness Review em 1990. Nesse artigo, introduziram o termo competência essencial (<em>core competence</em>), ao apontarem que as empresas bem-sucedidas e extremamente competitivas eram mais que portfólios de negócios, eram portfólios de competências, as estratégias devem ser definidas sobre as competências básicas da organização, tentando aproveitar as oportunidades futuras do ambiente, na busca de vantagem competitiva sustentável.
</p>
</div>
</div>
</div>
<p class="Texto">
Existe espaço para uma série de estratégias de sucesso. O pior erro é não escolher. É tentar um pouco de tudo para, no fim, não conseguir nenhuma vantagem. Isso não funciona porque todas as boas estratégias envolvem escolhas. Para Porter, não se pode ter ao mesmo tempo custos baixos e ser líder ou único em qualidade e serviço.
<br><br>Uma organização pode dizer que possui uma estratégia, quando responde afirmativamente às três perguntas seguintes.
</p>
<div class="alert alert-light-primary" role="alert">
<p class="Texto">
<strong>
♣ A empresa escolheu uma posição única, diferente dos concorrentes?<br>
♣ Optou por desempenhar atividades de marketing e desenvolvimento de produtos de maneira diferente<br>
♣ A empresa optou por não fazer determinadas coisas?
</strong>
</p>
</div>
<p class="Texto">
Quando uma organização consegue criar uma estratégia única, a sua posição no mercado se torna sustentável por muito mais tempo.
</p>
<br><br>
<div class="text-center">
<a href="Topico02_1.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Topico03_1.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body><file_sep>/Topico03_2.php
<?php
// HEADER
include('layout/header.php');
?>
<body>
<!-- PLUGIN DO FADE IN -->
<script src="https://unpkg.com/aos@next/dist/aos.js"></script>
<script>
AOS.init();
</script>
<!-- MENU -->
<?php include('layout/menu.php') ?>
<div id="main">
<!-- NAV TOP -->
<?php include('layout/nav.php') ?>
<!-- CONTEUDO INICIO -->
<div class="main-content container-fluid">
<div class="page-title">
<h2 class="font-bold">2 - Objetivos Estratégicos </h2>
<hr class="pontLaranja">
<p class="Texto">
<strong>Exemplos reais</strong>
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo 1 - <br>Movimento<br> todos pela<br> Educação</h5>
</th>
<td class="Texto">
<ol>
<li> Toda criança e jovem de 4 a 17 anos na escola.</li>
<li> Toda criança plenamente alfabetizada até os 8 anos.</li>
<li> Todo aluno com aprendizado adequado à sua série.</li>
<li> Todo jovem com o Ensino Médio concluído até os 19 anos.</li>
<li> Investimento em Educação ampliado e bem gerido.</li>
</ol>
</td>
</tr>
</table>
</div>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo 2 - ONG <br>Moradia e <br>Cidadania</h5>
</th>
<td class="Texto">
<ol>
<li> Tornar a ONG auto-sustentável;</li>
<li> Firmar parcerias estratégicas para o alcance da Missão da ONG;</li>
<li> Centrar a atuação da ONG nas ações de Educação e Geração de Trabalho e Renda;</li>
<li> Fortalecer as iniciativas de voluntariado e de combate à fome e à miséria;</li>
</ol>
</td>
</tr>
</table>
</div>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingseven">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse7" aria-expanded="false" aria-controls="collapse7">
<h3>Estratégia corporativa </h3>
</button>
</h2>
</div>
<div id="collapse7" class="collapse" aria-labelledby="headingseven" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Estabelece posições comerciais, em diferentes indústrias, que possibilitam melhorar o desempenho do grupo de negócios em que a organização se diversificou. A formulação desse tipo de estratégia é realizada no mais alto nível da organização.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingeight">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse8" aria-expanded="false" aria-controls="collapse8">
<h3>Estratégia organizacional </h3>
</button>
</h2>
</div>
<div id="collapse8" class="collapse" aria-labelledby="headingeight" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
É projetada para alcançar os objetivos globais da organização. Esse processo inclui atividades de seleção e desenvolvimento de estratégias gerais e, posteriormente, tomadas de decisões específicas a respeito do papel das diversas linhas de negócios da organização e da quantidade de recursos a serem alocados.
<br><br>Existem algumas estratégias gerais que a organização pode adotar:
</p>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> estratégia de concentração em uma única linha de negócios;<br>
<i class="fa fa-arrow-right CorLaranja"></i> estratégia de crescimento;<br>
<i class="fa fa-arrow-right CorLaranja"></i> estratégia de estabilidade;<br>
<i class="fa fa-arrow-right CorLaranja"></i> estratégia de redução de despesas;<br>
<i class="fa fa-arrow-right CorLaranja"></i> estratégias combinadas.
</ul>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingnine">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse9" aria-expanded="false" aria-controls="collapse9">
<h3>Estratégia de negócios </h3>
</button>
</h2>
</div>
<div id="collapse9" class="collapse" aria-labelledby="headingnine" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
Envolve as tomadas de decisões em nível de divisão ou unidade de negócios, ou seja, para cada negócio em que a organização atua, devendo ser consistente com a sua estratégia corporativa. A estratégia de negócio tem como objetivo um desempenho bem-sucedido em uma linha de negócio específica, bem como formar e/ou reforçar uma posição competitiva de longo prazo, que produza uma vantagem competitiva para a instituição.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingten">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse10" aria-expanded="false" aria-controls="collapse10">
<h3>Estratégias funcionais </h3>
</button>
</h2>
</div>
<div id="collapse10" class="collapse" aria-labelledby="headingten" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
São formuladas por especialistas de cada área funcional da organização (marketing, recursos humanos, financeira e demais), descrevendo as tarefas específicas que cada área terá que desenvolver para se implementar a estratégia da instituição. Dessa forma, os responsáveis pela estratégia funcional devem entrar em harmonia com as estratégias de negócios para garantir que todas as estratégias sejam consistentes.
<br><br>A estratégia funcional possui uma abrangência mais restrita e adiciona detalhes mais relevantes ao plano de negócios estabelecendo as ações, abordagens e práticas para a operação de uma área ou função do negócio. Os objetivos da estratégia funcional são: fornecer apoio para a estratégia geral de negócios e para a abordagem competitiva da instituição; e descrever como a área funcional vai atingir seus objetivos e função.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingeleven">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse11" aria-expanded="false" aria-controls="collapse11">
<h3>Estratégia operacional </h3>
</button>
</h2>
</div>
<div id="collapse11" class="collapse" aria-labelledby="headingeleven" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
É direcionada às unidades operacionais básicas, tais como fábricas, distritos e regiões de vendas e departamentos dentro de áreas funcionais. As estratégias operacionais estão relacionadas com iniciativas estratégicas e abordagens mais restritas ao gerenciamento de unidades operacionais-chaves e para o tratamento de tarefas operacionais diárias, que tenham significado estratégico, acrescentando detalhes e complementos às estratégias funcionais e ao plano geral do negócio.
</p>
</div>
</div>
</div>
</div>
</section>
<br>
<section id="Controle">
<div class="accordion" id="accordionExample">
<div class="card">
<div class="card-header" id="headingthirteen">
<h2 class="mb-0">
<button class="btn btn-success btn-block text-left collapsed " type="button" data-toggle="collapse" data-target="#collapse13" aria-expanded="false" aria-controls="collapse13">
<h3>Estratégias de Recursos Humanos </h3>
</button>
</h2>
</div>
<div id="collapse13" class="collapse" aria-labelledby="headingthirteen" data-parent="#accordionExample">
<div class="card-body">
<p class="Texto">
<strong>Gestão Participativa</strong>
</p>
<hr>
<p class="Texto">
Associada ao estilo organizacional que permite participação significativa dos funcionáriosb trabalhadores no planejamento, execução e controle de suas tarefas.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Formação de grupos nos quais os trabalhadores receberam autonomia para decidir;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Criação do Clube dos 20, com a finalidade de estimular o espírito participativo dos funcionários nas decisões gerenciais;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Manutenção de pessoal de alto nível, mostrando aos funcionários que precisam participar mais nas decisões e ajudar a acabar com a burocracia interna.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Administração da Compensação</strong>
</p>
<hr>
<p class="Texto">
Atividade da organização que lida com a recompensa recebida pelos funcionários como retorno pela execução de tarefas organizacionais, podendo ser diretas (salários, bônus, comissões etc) e indiretas (planos de saúde, férias etc.)
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Adotou um programa de participação nos lucros como forma de estimular os empregados;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Reestruturação do plano de cargos e salários;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Premiação em dinheiro aos que tiveram sugestões aceitas e carta de agradecimento aos outros que também participaram.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Treinamento e Desenvolvimento</strong>
</p>
<hr>
<p class="Texto">
Iniciativas para a capacitação e aperfeiçoamento dos funcionários, visando a agregar-lhes valor e a torná-los cada vez mais habilitados para a execução das atividades da instituição.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Entre outras ações, a instituição subsidia 100% da educação de seus funcionários, do ensino fundamental ao doutorado;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Para implantar a nova cultura, a organização desenvolve cursos, seminários e palestras;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Investir permanentemente em mão de obra, com programas de desenvolvimento de frentes e de capacitação para tomada de decisões.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Motivação</strong>
</p>
<hr>
<p class="Texto">
Ações que visam estimular, incentivar e levar funcionários a agir de determinada forma ou a levar a um comportamento específico de comprometimento com a instituição.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Ações como a motivação dos funcionários para que pensem, proponham e ajudem a colocar em execução, alternativas para conter custos;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Os funcionários receberam, folhetos recomendando um esforço permanente para reduzir custos, melhorar o atendimento e criar dispositivos para aumentar a lucratividade dos associados.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Avaliação de Desempenho</strong>
</p>
<hr>
<p class="Texto">
Procedimentos de apreciação sistemática do desempenho de cada funcionário no cargo e o seu potencial de desenvolvimento na organização.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Mensalmente, gerentes e líderes preenchem formulários de avaliação de seus subordinados para garantir a qualidade no trabalho;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Os funcionários são avaliados periodicamente, baseados na comparação com outros colegas do mesmo cargo.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Células de Negócios</strong>
</p>
<hr>
<p class="Texto">
Formação de equipes autogeridas com maiores responsabilidades e poder de decisão.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Adotou o sistema “células de negócios” tornando as equipes de vendas especializadas<br>
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Contratação</strong>
</p>
<hr>
<p class="Texto">
Admissão de novos funcionários para compor seu quadro.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Contratação para aumento do quadro de funcionários;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Abertura de 1500 novas vagas no quadro de pessoal;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Admitiu mais de 1900 empregados;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Devido ao crescimento, o quadro de pessoal aumentou.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Incentivo à Aposentadoria</strong>
</p>
<hr>
<p class="Texto">
Iniciativas objetivando a aposentadoria de funcionários com benefícios extras, como forma de reduzir o quadro sem o impacto da demissão direta.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Adotou programa de incentivos à aposentadoria. <br>
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Recrutamento Interno </strong>
</p>
<hr>
<p class="Texto">
Preferência a funcionários internos para preenchimento de cargos, normalmente com promoção.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Executivos criados na instituição assumiram o comando das seis novas diretorias, os antigos diretores viraram consultores dos novatos.
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Redução do quadro de Funcionários </strong>
</p>
<hr>
<p class="Texto">
Demissão direta e/ou incentivos à demissão voluntária.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> O enxugamento atingiu os cargos de alto e médio escalão;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Reduziu em 25% o número de funcionários;<br>
<i class="fa fa-arrow-right CorLaranja"></i> Reduziu o quadro de pessoal de cerca de 1400 para 800 funcionários;<br>
<i class="fa fa-arrow-right CorLaranja"></i> De cinco membros do escalão executivo superior passaram a ser apenas três<br>
</ul>
</td>
</tr>
</table>
</div><br>
<p class="Texto">
<strong>Responsabilidade Social </strong>
</p>
<hr>
<p class="Texto">
Ações visando à atuação socialmente responsável dos funcionários.
</p>
<div class="table-responsive">
<table class="table">
<tr>
<th class="BackLaranja text-white textmiddle">
<h5> Exemplo</h5>
</th>
<td>
<ul class="Texto">
<i class="fa fa-arrow-right CorLaranja"></i> Atenção a áreas sociais com parcerias com a Fundação Abrinq e o Instituto Ethos de Responsabilidade Social com participação dos funcionários nas atividades. <br>
</ul>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</div>
</a>
<br>
<h2 class="font-bold">2.1 Mapas Estratégicos como Suporte ao Planejamento </h2>
<hr class="pontLaranja">
<p class="Texto">
Para Mintzberg, Ahlstrand e Lampel (2000), a formulação da estratégia consiste em um processo emergente e, enquanto a estratégia deliberada focaliza o controle, a estratégia emergente focaliza o aprendizado. Para os mesmos autores, a administração estratégica pode ser considerada um processo de aprendizado coletivo. Logo, o que realmente importa não é apenas a aprendizagem em si, mas a aprendizagem coletiva. Essa noção é plenamente compatível com organizações que operam em ambientes complexos, nos quais o conhecimento requerido para criar estratégias se encontra bastante difuso.
<br><br>Acerca, ainda, de conhecimento, Nonaka e Takeuchi (1991) tratam o processo de criação do conhecimento como resultado de um ciclo contínuo de quatro processos integrados: externalização, internalização, combinação e socialização.
<br><br>Conforme recordam Costa e Krucken (2010), mapear conhecimentos é parte fundamental dos processos de gestão do conhecimento organizacional. Os mapas servem tanto para localizar especializações quanto para mapear os ativos de conhecimento, possibilitando que quaisquer tipos de conhecimento se tornem, formalmente, acessíveis. Destarte, o processo de construção de um mapa trata da explicitação: compreende externalização e socialização do conhecimento; desenvolve visões, linguagens e vocabulário comuns; estimula a interação e a evolução do conhecimento construído coletivamente. O mapa como produto, por sua vez, retrata o conhecimento codificado, produzindo internalização e combinação, ou, em outras palavras, serve como um guia para a análise crítica, o diagnóstico e a contextualização, oferecendo subsídios para a elaboração de cenários e para a tomada de decisões. Além disso, consolida uma memória evolutiva e material de base para a gestão do conhecimento.
<br><br>Ademais, segundo as mesmas autoras, experiências envolvendo mapas estratégicos trazem como resultados principais o desenvolvimento da visão estratégica do negócio e do seu ambiente, a análise crítica do posicionamento do negócio e o desenvolvimento da visão sistêmica de competitividade. Adicionalmente, estimulam o desenvolvimento de competências individuais entre os sujeitos, tais como: análise crítica; comunicação verbal e visual; compartilhamento de conhecimentos; e trabalho em equipe. Dessa forma, é imprescindível que os mapas sejam desenvolvidos dinamicamente, como registros em atualização constante.
</p>
<br><br>
<div class="text-center">
<a href="Topico03_1.php" type="button" class="btn btn-outline-success btn-sm">Página Anterior</a>
<a href="Referencias.php" type="button" class="btn btn-outline-success btn-sm">Próxima Página</a>
</div>
<!-- SCRIPT LIGHTBOX -->
<script>
$(document).on('click', '[data-toggle="lightbox"]', function(event) {
event.preventDefault();
$(this).ekkoLightbox();
});
$(function() {
$('[data-toggle="popover"]').popover()
})
$('.popover-dismiss').popover({
trigger: 'focus'
})
$(document).ready(function() {
new WOW().init();
});
</script>
</div> <!-- CLASS PAGE TITLE FIM -->
</div> <!-- CONTEUDO FIM -->
<!-- FOOTER -->
<?php include('layout/footer.php') ?>
</div> <!-- DIV MAIN FIM -->
<!-- FOOTER JS -->
<?php include('layout/js.php') ?>
</body> | 45f7620ea1a1741c71ace180257303f227624208 | [
"PHP"
] | 10 | PHP | egpce-cedis/planejamentoSetorPublicoMod03 | 6a7ed5173da3d98dc506cad94a7408580fea4b39 | a794b4334f64fe970263e8c0a1f0fd0726ad8cf5 | |
refs/heads/master | <repo_name>joetgish/strings<file_sep>/progA.cpp
// Utility program to practice string operations
//
#include <iostream>
#include <string>
using namespace std;
int main()
{
string valA = "houseboatestablish";
cout << "length =" << valA.length() << endl;
for(int ix = 0; ix < valA.length(); ix++)
{
cout << valA.at(ix) << endl;
}
valA.erase(3,6);
cout << valA << endl;
return 0;
}
| d6296c6cb25fbe41aefd4a6c91e1992ea8f84f97 | [
"C++"
] | 1 | C++ | joetgish/strings | 0b4efe65a1835be8374d4cdfd2d05516e6f61898 | 4bb1a2c5225ce366a172748baa41b5d15d1f1d60 | |
refs/heads/main | <repo_name>eboriley/netflix-clone<file_sep>/src/Nav.js
import React , {useEffect, useState} from 'react'
import './Nav.css'
function Nav() {
const [show, handleShow] = useState(false)
useEffect(() => {
window.addEventListener("scroll", ()=>{
if (window.scrollY > 100){
handleShow(true);
} else handleShow(false);
});
return () => {
window.removeEventListener("scroll");
};
}, []);
return (
<div className={`nav ${show && "nav__black"}`}>
<img
className="nav__logo"
src="https://assets.brand.microsites.netflix.io/assets/493f5bba-81a4-11e9-bf79-066b49664af6_cm_1440w.png?v=49"
alt="Netflix logo"
/>
<img
className="nav__avatar"
src="https://images.unsplash.com/photo-1603415526960-f7e0328c63b1?ixid=MXwxMjA3fDB8MHxzZWFyY2h8MjB8fHByb2ZpbGUlMjBwaWN0dXJlfGVufDB8fDB8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"
alt="avatar"
/>
</div>
)
}
export default Nav
| 2158920b0e512aafeebd54ea88c85dee6eaee3e4 | [
"JavaScript"
] | 1 | JavaScript | eboriley/netflix-clone | 5fab0f6fe2795f1a891663d13b74b3f630b62474 | 621dfd411ee16d719b07e14fa95f9917797dc20b | |
refs/heads/master | <repo_name>bayansar/AdventureWorkReview<file_sep>/sql/migration.sql
ALTER TABLE adventureworks.productreview
CHANGE ReviewDate ReviewDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
CHANGE ModifiedDate ModifiedDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
ADD CONSTRAINT fk_product_id FOREIGN KEY (ProductID) REFERENCES adventureworks.product(ProductID),
ALTER COLUMN Rating SET DEFAULT 0,
ADD Status varchar(255);<file_sep>/mysql/review.go
package mysql
import (
"log"
"time"
"fmt"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
"github.com/bayansar/AdventureWorkReview/review"
)
type ReviewDbService struct {
orm orm.Ormer
}
func NewReviewDbService(username, password, dbName, host string) *ReviewDbService {
orm.RegisterModel(new(review.Review))
err := orm.RegisterDataBase(
"default",
"mysql",
fmt.Sprintf("%s:%s@tcp(%s:3306)/%s?charset=utf8", username, password, host, dbName), 30)
if err != nil {
}
orm.RunSyncdb("default", false, true)
return &ReviewDbService{
orm: orm.NewOrm(),
}
}
func (rds *ReviewDbService) Insert(review *review.Review) (int64, error) {
review.CreatedAt = time.Now()
review.LastUpdateAt = time.Now()
review.Status = "SUBMITTED"
id, err := rds.orm.Insert(review)
if err != nil {
return 0, err
}
log.Printf("new review is created in db with id: %d,", review.ID)
return id, nil
}
func (rds *ReviewDbService) Update(review *review.Review) (int64, error) {
num, err := rds.orm.Update(review)
if err != nil {
log.Printf("%s: %s", "Failed to update a review", err)
return 0, err
}
log.Printf("the review is updated in db with id: %d,", review.ID)
return num, nil
}
func (rds *ReviewDbService) GetById(id int64) (*review.Review, error) {
r := &review.Review{
ID: id,
}
err := rds.orm.Read(r)
if err != nil {
return nil, err
}
return r, nil
}
func (rds *ReviewDbService) GetApprovedReviews() ([]*review.Review, error) {
var reviews []*review.Review
_, err := rds.orm.QueryTable("productreview").Filter("status", "APPROVED").All(&reviews)
if err != nil {
return nil, err
}
return reviews, nil
}
<file_sep>/review/review.go
package review
import (
"time"
)
type Review struct {
ID int64 `json:"id" orm:"auto;column(ProductReviewID)"`
ProductId string `json:"productid" orm:"column(ProductID)"`
Name string `json:"name" orm:"column(ReviewerName)"`
CreatedAt time.Time `json:"createdAt" orm:"null;column(ReviewDate)"`
Email string `json:"email" orm:"column(EmailAddress)"`
Review string `json:"review" orm:"column(Comments)"`
Status string `json:"status" orm:"null;column(Status)"`
LastUpdateAt time.Time `json:"lastUpdateAt" orm:"null;column(ModifiedDate)"`
}
func (u *Review) TableName() string {
return "productreview"
}
type QueueService interface {
Publish(review *Review) error
Subscribe() (<-chan Review, error)
}
type DbService interface {
Insert(review *Review) (int64, error)
Update(review *Review) (int64, error)
GetById(id int64) (*Review, error)
GetApprovedReviews() ([]*Review, error)
}
type NotifyService interface {
Notify(review *Review, message string) error
}
<file_sep>/review/notifier.go
package review
import (
"log"
)
type Notifier struct {
ConsumerQueue QueueService
NotifyService NotifyService
approveMes string
declineMes string
}
func (n *Notifier) Run() error {
n.approveMes = "Your review is approved and released!"
n.declineMes = "Your review is declined because of bad language!"
messages, err := n.ConsumerQueue.Subscribe()
if err != nil {
return err
}
go func() {
for m := range messages {
var notifyMes string
if m.Status == "APPROVED" {
notifyMes = n.approveMes
} else if m.Status == "DECLINED" {
notifyMes = n.declineMes
} else {
log.Printf("%s: %s", "Illegal status to notify which is ", m.Status)
}
err := n.NotifyService.Notify(&m, notifyMes)
if err != nil {
log.Printf("%s: %s", "Failed to notify user", err)
}
}
}()
return nil
}
<file_sep>/review/validator.go
package review
import (
"log"
"regexp"
"strings"
)
type Validator struct {
PublisherQueue QueueService
ConsumerQueue QueueService
DB DbService
BadWords []string
}
func (v *Validator) Run() error {
reg, err := regexp.Compile("[^a-zA-Z0-9]+")
if err != nil {
log.Printf("%s: %s", "Failed compile regex", err)
return err
}
messages, err := v.ConsumerQueue.Subscribe()
if err != nil {
return err
}
go func() {
for m := range messages {
wordList := v.split(m.Review, reg)
if v.checkForBadWords(wordList, v.BadWords) == true {
m.Status = "APPROVED"
} else {
m.Status = "DECLINED"
}
_, err := v.DB.Update(&m)
if err != nil {
continue
}
err = v.PublisherQueue.Publish(&m)
if err != nil {
continue
}
}
}()
return nil
}
func (v *Validator) split(review string, reg *regexp.Regexp) []string {
processedReview := reg.ReplaceAllString(review, " ")
return strings.Split(processedReview, " ")
}
func (v *Validator) checkForBadWords(wordList []string, badWords []string) bool {
// A map might be used in case of high number of bad words to avoid from quadratic complexity
for _, word := range wordList {
for _, badWord := range v.BadWords {
if strings.EqualFold(word, badWord) == true {
return false
}
}
}
return true
}
<file_sep>/review/api.go
package review
import (
"log"
"net/http"
"fmt"
"encoding/json"
"strconv"
"github.com/gorilla/mux"
)
type Api struct {
Queue QueueService
DB DbService
}
func (a *Api) CreateReview() http.HandlerFunc {
return errorHandler(func(w http.ResponseWriter, r *http.Request) error {
defer r.Body.Close()
newReview := Review{}
if err := json.NewDecoder(r.Body).Decode(&newReview); err != nil {
return fmt.Errorf("cannot decoding review : %v", err)
}
id, err := a.DB.Insert(&newReview)
if err != nil {
return err
}
newReview.ID = id
err = a.Queue.Publish(&newReview)
if err != nil {
return err
}
err = json.NewEncoder(w).Encode(map[string]string{
"success": "true",
"reviewId": strconv.FormatInt(newReview.ID, 10),
})
if err != nil {
return err
}
return nil
})
}
func (a *Api) GetReviewById() http.HandlerFunc {
return errorHandler(func(w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
idStr := vars["id"]
id, err := strconv.ParseInt(idStr, 10, 64)
if err != nil {
return fmt.Errorf("cannot parse variable: %v", err)
}
review, err := a.DB.GetById(id)
if err != nil {
return err
}
err = json.NewEncoder(w).Encode(review)
if err != nil {
return err
}
return nil
})
}
func (a *Api) GetApprovedReviews() http.HandlerFunc {
return errorHandler(func(w http.ResponseWriter, r *http.Request) error {
reviews, err := a.DB.GetApprovedReviews()
if err != nil {
return nil
}
err = json.NewEncoder(w).Encode(reviews)
if err != nil {
return err
}
return nil
})
}
func errorHandler(f func(http.ResponseWriter, *http.Request) error) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
err := f(w, r)
if err != nil {
log.Printf("handling %q: %v", r.RequestURI, err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
}
<file_sep>/README.md
# AdventureWorkReview
## **Instructions**
1. *Clone the repository*
2. *Download docker images*
```
docker pull mysql
docker pull rabbitmq:3-management-alpine
```
3. *Change current folder to project*
```
cd AdventureWorkReview
```
4. *Build docker image*
```
docker-compose build
```
5. *Create and start containers*
```
docker-compose up -d
```
- Please wait several minutes for migrating database. When it is complete, the application container would start.
- You can check whether it starts with the command below:
```
docker ps
```
6. *Post a review*
```
curl -X POST http://0.0.0.0:8888/api/reviews \ -H 'Content-Type: application/json' \
-d '{
"name": "<NAME>",
"email": "<EMAIL>", "productid": "3",
"review": "I really love the product and will recommend!" }'
```
## **REST API**
```
- POST '/api/reviews' (Create a new review)
- GET '/api/reviews/approved' (Get all approved reviews)
- GET '/api/reviews/{id}' (Get a review)
```
<file_sep>/Dockerfile
FROM golang:1.9 as builder
# Set go bin which doesn't appear to be set already.
ENV GOBIN /go/bin
RUN go get -u github.com/golang/dep/...
COPY . ${GOPATH}/src/github.com/bayansar/AdventureWorkReview/
WORKDIR ${GOPATH}/src/github.com/bayansar/AdventureWorkReview/
# Go dep!
RUN dep ensure -vendor-only && CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /review-app
RUN go test -v
# STEP 2 build a small image
FROM scratch
ENV RABBIT_URI amqp://guest:guest@rabbitmq:5672
ENV MYSQL_USER root
ENV MYSQL_PASSWORD <PASSWORD>
ENV DB_NAME=adventureworks
ENV VALIDATE_QUEUE_NAME=validate
ENV NOTIFY_QUEUE_NAME=notify
ENV BAD_WORDS=fee,nee,cruul,leent
ENV DB_HOST=mysql
COPY --from=builder /review-app /review-app
EXPOSE 8888
CMD ["/review-app"]<file_sep>/main.go
package main
import (
"log"
"net/http"
"github.com/caarlos0/env"
"github.com/gorilla/mux"
"github.com/bayansar/AdventureWorkReview/email"
"github.com/bayansar/AdventureWorkReview/mysql"
"github.com/bayansar/AdventureWorkReview/rabbitmq"
"github.com/bayansar/AdventureWorkReview/review"
"os"
)
type Config struct {
RabbitUri string `env:"RABBIT_URI,required"`
DbHost string `env:"DB_HOST,required"`
DbUser string `env:"MYSQL_USER,required"`
DbPassword string `env:"MYSQL_PASSWORD,required"`
DbName string `env:"DB_NAME,required"`
ValidateQueueName string `env:"VALIDATE_QUEUE_NAME,required"`
NotifyQueueName string `env:"NOTIFY_QUEUE_NAME,required"`
BadWords []string `env:"BAD_WORDS,required" envSeparator:","`
}
func main() {
cfg := Config{}
err := env.Parse(&cfg)
if err != nil {
log.Fatalf("%s : %v","Couldn't parse environment variables!" , err)
}
reviewValidateQueueService := rabbitmq.NewReviewQueueService(cfg.RabbitUri, cfg.ValidateQueueName)
reviewNotifyQueueService := rabbitmq.NewReviewQueueService(cfg.RabbitUri, cfg.NotifyQueueName)
reviewDbService := mysql.NewReviewDbService(cfg.DbUser, cfg.DbPassword, cfg.DbName, cfg.DbHost)
notifyService := email.NewReviewEmailService()
reviewApi := &review.Api{
Queue: reviewValidateQueueService,
DB: reviewDbService,
}
reviewValidator := &review.Validator{
ConsumerQueue: reviewValidateQueueService,
PublisherQueue: reviewNotifyQueueService,
DB: reviewDbService,
BadWords: cfg.BadWords,
}
err = reviewValidator.Run()
if err != nil {
os.Exit(1)
}
reviewNotifier := &review.Notifier{
ConsumerQueue: reviewNotifyQueueService,
NotifyService: notifyService,
}
err = reviewNotifier.Run()
if err != nil {
os.Exit(1)
}
r := mux.NewRouter()
r.HandleFunc("/api/reviews", reviewApi.CreateReview()).Methods("POST")
r.HandleFunc("/api/reviews/approved", reviewApi.GetApprovedReviews()).Methods("GET")
r.HandleFunc("/api/reviews/{id}", reviewApi.GetReviewById()).Methods("GET")
log.Println("Server listening on port 8888...")
log.Fatal(http.ListenAndServe(":8888", r))
}
<file_sep>/email/review.go
package email
import (
"log"
"github.com/bayansar/AdventureWorkReview/review"
)
type ReviewEmailService struct {
emailService interface{}
}
func NewReviewEmailService() *ReviewEmailService{
return &ReviewEmailService{}
}
func (res *ReviewEmailService) Notify(review *review.Review, message string) error {
/*
*** Send email is simulated below line***
res.emailService.sendEmail(review.Name, review.Email, message)
*/
log.Println("email is sent successfully")
return nil
}
<file_sep>/rabbitmq/review.go
package rabbitmq
import (
"encoding/json"
"github.com/bayansar/AdventureWorkReview/review"
"github.com/pkg/errors"
"github.com/streadway/amqp"
"log"
)
type ReviewQueueService struct {
conn *amqp.Connection
ch *amqp.Channel
q amqp.Queue
}
func NewReviewQueueService(uri string, qname string) (*ReviewQueueService, error) {
conn, err := amqp.Dial(uri)
if err != nil {
//log.Printf("%s: %s", "Failed to connect to RabbitMQ", err)
return nil, errors.Wrap(err, "Failed to connect to RabbitMQ")
}
ch, err := conn.Channel()
if err != nil {
log.Printf("%s: %s", "Failed to open a channel", err)
}
q, err := ch.QueueDeclare(
qname, // name
false, // durable
false, // delete when unused
false, // exclusive
false, // no-wait
nil, // arguments
)
if err != nil {
log.Printf("%s: %s", "Failed to declare a queue", err)
}
return &ReviewQueueService{
conn: conn,
ch: ch,
q: q,
},nil
}
func (rqs *ReviewQueueService) Publish(review *review.Review) error {
b, err := json.Marshal(review)
if err != nil {
log.Printf("%s: %s", "Failed to serialize review object!", err)
return err
}
err = rqs.ch.Publish(
"", // exchange
rqs.q.Name, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: b,
})
if err != nil {
log.Printf("%s: %s", "Failed to publish a message", err)
}
log.Printf("the review is pushed to queue: %s with id: %d,", rqs.q.Name, review.ID)
return err
}
func (rqs *ReviewQueueService) Subscribe() (<-chan review.Review, error) {
messages, err := rqs.ch.Consume(
rqs.q.Name, // queue
"", // consumer
true, // auto-ack
false, // exclusive
false, // no-local
false, // no-wait
nil, // args
)
if err != nil {
log.Printf("%s: %s", "Failed to register a consumer", err)
return nil, err
}
reviewMessages := make(chan review.Review)
go func() {
for m := range messages {
r := review.Review{}
err := json.Unmarshal(m.Body, &r)
if err != nil {
log.Printf("%s: %s", "Failed to deserialize review", err)
continue
}
log.Printf("review is retrieved from queue: %s with id: %d,", rqs.q.Name, r.ID)
reviewMessages <- r
}
}()
return reviewMessages, nil
}
<file_sep>/docker-compose.yml
version: '3'
services:
rabbitmq:
image: rabbitmq:3-management-alpine
restart: unless-stopped
ports:
- 5672:5672
- 15672:15672
mysql:
image: mysql:latest
volumes:
- ./sql:/docker-entrypoint-initdb.d
environment:
MYSQL_ROOT_PASSWORD: <PASSWORD>
restart: unless-stopped
ports:
- 3306:3306
review-app:
build: ./
image: review-app:1.0
environment:
RABBIT_URI: amqp://guest:guest@rabbitmq:5672
MYSQL_USER: root
MYSQL_PASSWORD: <PASSWORD>
DB_NAME: adventureworks
VALIDATE_QUEUE_NAME: validate
NOTIFY_QUEUE_NAME: notify
BAD_WORDS: fee,nee,cruul,leent
DB_HOST: mysql
restart: unless-stopped
ports:
- 8888:8888
links:
- rabbitmq:rabbitmq
- mysql:mysql
depends_on:
- mysql
- rabbitmq
| 55c771ae029d4078ca6f7ea05a79c5efd23eaa9b | [
"SQL",
"YAML",
"Markdown",
"Go",
"Dockerfile"
] | 12 | SQL | bayansar/AdventureWorkReview | 058090ec42fa242d1f5d3399f88251b6e25d7524 | d0be23df6f417130ca968acce2fa44bf5d6e69b6 | |
refs/heads/master | <file_sep>package com.company;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.Scanner;
public class Main {
private static final char SEPARATOR = '|';
private static final String SEPARATOR_REGEX = "\\|";
private static final char NEW_LINE = '\n';
private String _failoVardas = "duomenys.txt";
private FileReader _in;
private BufferedReader _bufferis;
private Scanner _sc;
private FileWriter _out;
public static void main(String[] args) {
// write your code here
Dot taskas1;
Dot taskas2;
Dot taskas3;
taskas1 = new Dot(3, 4);
taskas2 = new Dot(-10, 10, "raudona");
taskas3 = new Dot("melyna");
System.out.println(taskas1);
System.out.println(taskas2);
System.out.println(taskas3);
System.out.println("atstumas tarp tasko 1 ir 3 " + taskas1.getDistance(taskas3));
System.out.println("ar taspats ketvirtis tasko 1 ir 3 " + taskas1.isSameQuarter(taskas3));
System.out.println("ar taspats ketvirtis tasko 1 ir 2 " + taskas1.isSameQuarter(taskas2));
Dot taskas4 = new Dot(10, 10, "raudona");
System.out.println("ar vienodi taskai 2 ir 4 " + taskas4.equals(taskas2));
//tekstiniame faile yra informacija tokiu formatu
//x|y| spalva bent 10 eiluciu
//nustatyti visus taskus i tasku masyva
//rasti didziausia atstuma tarp dvieju tasku
//atspausdinti abu taskus i ekrana
//masyvas[i] = new Dot (Doub;e.parseDouble(zodziai[0], Double.parseDouble(zodziai[1]), zodziai[2]);
Main objektas = new Main();
objektas.skaitymasIsFailo();
}
//atidaryti faila nuskaitymui
public void atidarytiFaila() {
try {
_in = new FileReader(_failoVardas);
_bufferis = new BufferedReader(_in);
} catch (Exception e) {
}
}
//skaityti faila
public void skaitymasIsFailo() {
atidarytiFaila();
int eiluciuKiekis = gaukFailoEiluciuKieki();
atidarytiFaila();
Dot[] masyvas = new Dot[eiluciuKiekis];
try {
String eilute = _bufferis.readLine();
int i = 0;
while (eilute != null) {
String[] zodziai = eilute.split(SEPARATOR_REGEX);
masyvas[i] = new Dot(Double.parseDouble(zodziai[0]), Double.parseDouble(zodziai[1]), zodziai[2]);
i++;
eilute = _bufferis.readLine();
}
_bufferis.close();
_in.close();
skaiciavimas(masyvas);
} catch (Exception e) {
}
}
private int gaukFailoEiluciuKieki() {
atidarytiFaila();
int rezultatas = 0;
try {
String eilute = _bufferis.readLine();
while (eilute != null) {
rezultatas++;
eilute = _bufferis.readLine();
}
_bufferis.close();
_in.close();
} catch (Exception e) {
}
return rezultatas;
}
public void skaiciavimas(Dot[] masyvas) {
double atstumas = 0;
Dot pirmas=null;
Dot antras=null;
for (int i = 0; i < masyvas.length - 1; i++) {
for (int j = 1; j < masyvas.length; j++) {
if (masyvas[i].getDistance(masyvas[j])>atstumas){
atstumas=masyvas[i].getDistance(masyvas[j]);
pirmas = masyvas[i];
antras = masyvas[j];
}
}
}
System.out.println("dydziausias atstumas: "+ atstumas);
System.out.println(pirmas);
System.out.println(antras);
}
//sukelti eilutes i masyva
//pereiti per masyva
//rasti atstuma tarp 2 tasku
}
| e47afa5a9c4d8073090f468b0341e029b6e425ce | [
"Java"
] | 1 | Java | karoliszagarnauskas/Java_06_uzduotis1 | 2d66d4259717d8016432dbc858ad283429fbf680 | a6b07f943ce240e415cd81b599f41eb2701e725c | |
refs/heads/master | <repo_name>jhyhhmail/appium<file_sep>/src/main/java/com/jhyhh/appium/utils/BooleanUtils.java
package com.jhyhh.appium.utils;
public class BooleanUtils {
/**
* true|y|1|yes|on
*/
public static boolean isTrue(String str) {
return ("yes".equalsIgnoreCase(str) || "1".equalsIgnoreCase(str)
|| "true".equalsIgnoreCase(str) || "on".equalsIgnoreCase(str)
|| "y".equalsIgnoreCase(str));
}
public static boolean isTrue(Object obj) {
if (obj == null) {
return false;
}
if (obj instanceof Boolean) {
return ((Boolean) obj).booleanValue();
}
if (obj instanceof Number) {
return (((Number) obj).intValue() != 0);
}
String str = String.valueOf(obj);
return isTrue(str);
}
/**
* true|y|1|yes|on
*/
public static boolean isTrue(String str, boolean defaultValue) {
if (str == null) {
return defaultValue;
}
return isTrue(str);
}
}
<file_sep>/src/main/java/com/jhyhh/appium/android/T12306/launcher/TestAppium.java
package com.jhyhh.appium.android.T12306.launcher;
import io.appium.java_client.android.AndroidDriver;
import java.util.List;
import org.openqa.selenium.WebElement;
import com.jhyhh.appium.AndroidDriverManager;
import com.jhyhh.appium.AndroidDriverWait;
import com.jhyhh.appium.ExpectedCondition;
public class TestAppium {
public static void main(String[] args) {
AndroidDriverManager app = new AndroidDriverManager();
AndroidDriver<WebElement> driver = app
.getAndroidDriver("LGD857d51963f0");
app.waitTime(20000);
// 如果有升级执行升级动作
WebElement el = new AndroidDriverWait(driver, 60)
.until(new ExpectedCondition<WebElement>() {
public WebElement apply(AndroidDriver d) {
return d.findElementByAndroidUIAutomator("new UiSelector().text(\"升级\")");
}
});
el.click();
new AndroidDriverWait(driver, 60)
.until(new ExpectedCondition<WebElement>() {
public WebElement apply(AndroidDriver d) {
return d.findElementByAndroidUIAutomator("new UiSelector().descriptionContains(\"温馨提示\")");
}
});
// 等待加载完成后点目的站文本框,选择目的站。
List<WebElement> editTexts = new AndroidDriverWait(driver, 60)
.until(new ExpectedCondition<List<WebElement>>() {
public List<WebElement> apply(AndroidDriver d) {
return d.findElementsByClassName("android.widget.EditText");
}
});
editTexts.get(1).click();
// 选择车站列表Tab
List<WebElement> mudiButtons = new AndroidDriverWait(driver, 60)
.until(new ExpectedCondition<List<WebElement>>() {
public List<WebElement> apply(AndroidDriver d) {
return d.findElementsByClassName("android.widget.Button");
}
});
mudiButtons.get(3).click();
app.waitTime(5000);
// 切换到J 开头的List
new AndroidDriverWait(driver, 60).until(
new ExpectedCondition<WebElement>() {
public WebElement apply(AndroidDriver d) {
return d.findElementByAndroidUIAutomator("new UiSelector().descriptionContains(\"j\")");
}
}).click();
// 根据下标找到佳木斯view
new AndroidDriverWait(driver, 60)
.until(new ExpectedCondition<List<WebElement>>() {
public List<WebElement> apply(AndroidDriver d) {
return d.findElementsByClassName("android.view.View");
}
}).get(9).click();
List<WebElement> buttons = new AndroidDriverWait(driver, 60)
.until(new ExpectedCondition<List<WebElement>>() {
public List<WebElement> apply(AndroidDriver d) {
return d.findElementsByClassName("android.widget.Button");
}
});
buttons.get(buttons.size() - 1).click();
System.out.println("end");
}
}<file_sep>/src/main/java/com/jhyhh/appium/AndroidADBUtils.java
package com.jhyhh.appium;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import org.apache.commons.lang3.StringUtils;
public class AndroidADBUtils {
synchronized static public List<String> getDevices() {
Process process = null;
try {
process = Runtime.getRuntime().exec("adb devices");
process.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
InputStreamReader isr = new InputStreamReader(process.getInputStream());
Scanner sc = new Scanner(isr);
List<String> devices = new ArrayList<String>();
while (sc.hasNext()) {
String device = sc.nextLine();
if(StringUtils.isEmpty(device)){
continue;
}
if(device.endsWith("device")){
device = device.replace("device", "").trim();
devices.add(device);
}
}
sc.close();
return devices;
}
public static void main(String[] args) {
System.out.println(AndroidADBUtils.getDevices());
}
}
<file_sep>/src/main/java/com/jhyhh/appium/ExpectedCondition.java
package com.jhyhh.appium;
import io.appium.java_client.android.AndroidDriver;
import com.google.common.base.Function;
/**
* Models a condition that might reasonably be expected to eventually evaluate to something that is
* neither null nor false. Examples would include determining if a web page has loaded or that an
* element is visible.
* <p>
* Note that it is expected that ExpectedConditions are idempotent. They will be called in a loop by
* the {@link WebDriverWait} and any modification of the state of the application under test may
* have unexpected side-effects.
*
* @param <T> The return type
*/
public interface ExpectedCondition<T> extends Function<AndroidDriver, T> {}<file_sep>/target/m2e-wtp/web-resources/META-INF/maven/com.jhy.phone/appium/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.jhy.phone</groupId>
<artifactId>appium</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>appium Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!--dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId>
<version>2.2.4</version> </dependency> <dependency> <groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId> <version>2.47.1</version> </dependency>
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version>
<scope>test</scope> </dependency> <dependency> <groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId> <version>4.3.3</version> </dependency>
<dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId>
<version>17.0</version> </dependency> <dependency> <groupId>cglib</groupId>
<artifactId>cglib</artifactId> <version>3.1</version> </dependency> <dependency>
<groupId>commons-validator</groupId> <artifactId>commons-validator</artifactId>
<version>1.4.1</version> </dependency -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.9</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.appium</groupId>
<artifactId>java-client</artifactId>
<version>3.1.0</version>
</dependency>
</dependencies>
<build>
<finalName>appium</finalName>
</build>
</project>
| b14cd55314860fe559062e5de011a9274b93fdbb | [
"Java",
"Maven POM"
] | 5 | Java | jhyhhmail/appium | 35984607217528238b76e36dbaad3ce851ea26db | 15ce9775965c72f2695f39e6ae4a70083d75c820 | |
refs/heads/master | <repo_name>AlexNastin/EpamHostelProject<file_sep>/src/by/epam/hostel/entity/Entity.java
package by.epam.hostel.entity;
import java.io.Serializable;
public abstract class Entity implements Cloneable, Serializable{
/**
*
*/
private static final long serialVersionUID = -1928578207162711308L;
}
<file_sep>/src/by/epam/hostel/localization/usermenu_en.properties
user.exit = Exit
user.orders = Orders
user.makeorder = Make a booking
<file_sep>/src/by/epam/hostel/logic/impl/CommandGoRegister.java
package by.epam.hostel.logic.impl;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class receive data for
* displaying registration page.
*
* @author <NAME>
*/
public class CommandGoRegister implements ICommand {
/**
* This method handles request to get data for displaying registration page.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
return JspPageName.REGISTER_PAGE;
}
}
<file_sep>/src/by/epam/hostel/localization/errorlogin_en.properties
errorlogin.message = Invalid login or password.
errorlogin.link = Back to form<file_sep>/src/by/epam/hostel/localization/login_en.properties
login.locbutton.log = Log in
login.name = Login(e-mail)
login.pass = <PASSWORD>
login.register = Register
login.email = E-mail:
login.log.name = Login Form<file_sep>/src/by/epam/hostel/logic/impl/admin/CommandGetUser.java
package by.epam.hostel.logic.impl.admin;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlAdminDao;
import by.epam.hostel.entity.User;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class finds the necessary user
* in the database.
*
* @author <NAME>
*/
public class CommandGetUser implements ICommand {
private final String NOT_FIND = "admin.notfind";
/**
* This method back user of the base number.
*
* @param request a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
String idUserStr = request.getParameter(RequestParameterName.ID_USER);
String pageName = null;
try {
if ("".equals(idUserStr) != true) {
Integer idUser = Integer.valueOf(idUserStr);
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
IMySqlAdminDao dao = abstractDAOFactory.getMySqlAdminDao();
User user = dao.getUser(idUser);
if (user != null) {
request.setAttribute(RequestParameterName.USER, user);
pageName = JspPageName.USERFIND_PAGE;
} else {
request.setAttribute(RequestParameterName.ERROR, NOT_FIND);
pageName = JspPageName.ADMINUSERS_PAGE;
}
} else {
request.setAttribute(RequestParameterName.ERROR, NOT_FIND);
pageName = JspPageName.ADMINUSERS_PAGE;
}
} catch (DaoException e) {
throw new CommandException(e);
}
return pageName;
}
}
<file_sep>/src/by/epam/hostel/dao/connectionpool/ConnectionPool.java
package by.epam.hostel.dao.connectionpool;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import org.apache.log4j.Logger;
/**
*
* This class implements a pattern singleton. This class creates, handles and
* gives connections to database.
*
* @author <NAME>
*/
public final class ConnectionPool {
/**
* It is a logger which print some messages to log file.
*/
private static final Logger LOG = Logger.getLogger(ConnectionPool.class);
private BlockingQueue<PooledConnection> connectionQueue;
private BlockingQueue<PooledConnection> givenAwayConQueue;
private String driverName;
private String url;
private String user;
private String password;
private int poolSize;
/**
* The constructor initializes the fields of the class Database Settings.
*/
private ConnectionPool() {
/**
* This object provide access to config properties.
*/
MySqlPropertyManager propertyManager = MySqlPropertyManager
.getInstance();
this.driverName = propertyManager.getValue(MySqlParameter.DB_DRIVER);
this.url = propertyManager.getValue(MySqlParameter.DB_URL);
this.user = propertyManager.getValue(MySqlParameter.DB_USER);
this.password = propertyManager.getValue(MySqlParameter.DB_PASSWORD);
try {
this.poolSize = Integer.parseInt(propertyManager
.getValue(MySqlParameter.DB_POLL_SIZE));
} catch (NumberFormatException e) {
poolSize = 10;
LOG.info("Invalid number format", e);
}
}
/**
* The inner class for implementation singleton. It holds ConnectionPool
* instance.
*/
private static class Holder {
private static final ConnectionPool INSTANCE = new ConnectionPool();
}
/**
* The method gives ConnectionPool singleton instance.
*/
public static synchronized ConnectionPool getInstance() {
return Holder.INSTANCE;
}
/**
* Directly creates a connection pool
*/
public void initPoolData() throws ConnectionPoolException {
try {
Class.forName(driverName);
connectionQueue = new ArrayBlockingQueue<PooledConnection>(poolSize);
givenAwayConQueue = new ArrayBlockingQueue<PooledConnection>(
poolSize);
for (int i = 0; i < poolSize; i++) {
Connection connection = DriverManager.getConnection(url, user,
password);
PooledConnection pooledConnection = new PooledConnection(
connection);
connectionQueue.add(pooledConnection);
}
} catch (ClassNotFoundException e) {
throw new ConnectionPoolException(
"Can't find database driver class", e);
} catch (SQLException e) {
throw new ConnectionPoolException("SQLException in ConnectionPool",
e);
}
}
/**
* The method closes all connections in two BlockingQueue.
*/
public void dispose() {
clearConnectionQueue();
}
/**
* The method closes all connections in two BlockingQueue.
*/
private void clearConnectionQueue() {
try {
closeConnectionsQueue(givenAwayConQueue);
closeConnectionsQueue(connectionQueue);
} catch (SQLException e) {
LOG.error("Error closing the connection.", e);
}
}
/**
* The method take Connection from BlockingQueue.
*
* @return PooledConnection
*/
public PooledConnection takeConnection() throws ConnectionPoolException {
PooledConnection connection = null;
try {
connection = connectionQueue.take();
givenAwayConQueue.offer(connection);
} catch (InterruptedException e) {
throw new ConnectionPoolException(
"Error connecting to the data source.", e);
}
return connection;
}
/**
* The method closes the connection and statement.
*
* @param Connection connection
* @param Statement statement
* @exception SQLException
*/
public void closeConnection(Connection connection, Statement statement) {
try {
statement.close();
} catch (SQLException e) {
LOG.error("Statement isn't closed.", e);
}
try {
connection.close();
} catch (SQLException e) {
LOG.error("Connection isn't return to the pool.", e);
}
}
/**
* The method closes the connection and statement.
*
* @param Connection connection
* @param Statement statement
* @param PreparedStatement preparedStatement
* @exception SQLException
*/
public void closeConnection(Connection connection, Statement statement,
PreparedStatement preparedStatement) {
try {
statement.close();
} catch (SQLException e) {
LOG.error("Statement isn't closed.", e);
}
try {
preparedStatement.close();
} catch (SQLException e) {
LOG.error("PreparedStatement isn't closed.", e);
}
try {
connection.close();
} catch (SQLException e) {
LOG.error("Connection isn't return to the pool.", e);
}
}
/**
* The method closes the connections in BlockingQueue.
*
* @param BlockingQueue
* <PooledConnection> queue
* @exception SQLException
*/
private void closeConnectionsQueue(BlockingQueue<PooledConnection> queue)
throws SQLException {
Connection connection;
while ((connection = queue.poll()) != null) {
if (!connection.getAutoCommit()) {
connection.commit();
}
((PooledConnection) connection).reallyClose();
}
}
/**
* Class wrapper for Connection.
*
* @author <NAME>
*/
private class PooledConnection implements Connection {
private Connection connection;
public PooledConnection(Connection c) throws SQLException {
this.connection = c;
this.connection.setAutoCommit(true);
}
/**
* The method closes the connection.
*/
public void reallyClose() throws SQLException {
connection.close();
}
@Override
public void clearWarnings() throws SQLException {
connection.clearWarnings();
}
/**
* Throws a connection to one BlockingQueue to another BlockingQueue.
*/
@Override
public void close() throws SQLException {
if (connection.isReadOnly()) {
connection.setReadOnly(false);
}
if (!givenAwayConQueue.remove(this)) {
throw new SQLException(
"Error deleting connection from the given away connections pool.");
}
if (!connectionQueue.offer(this)) {
throw new SQLException(
"Error allocating connection in the pool.");
}
}
@Override
public void commit() throws SQLException {
connection.commit();
}
@Override
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
return connection.createArrayOf(typeName, elements);
}
@Override
public Blob createBlob() throws SQLException {
return connection.createBlob();
}
@Override
public Clob createClob() throws SQLException {
return connection.createClob();
}
@Override
public NClob createNClob() throws SQLException {
return connection.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
return connection.createSQLXML();
}
@Override
public Statement createStatement() throws SQLException {
return connection.createStatement();
}
@Override
public Statement createStatement(int resultSetType,
int resultSetConcurrency) throws SQLException {
return connection.createStatement(resultSetType,
resultSetConcurrency);
}
@Override
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return connection.createStatement(resultSetType,
resultSetConcurrency, resultSetHoldability);
}
@Override
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
return connection.createStruct(typeName, attributes);
}
@Override
public boolean getAutoCommit() throws SQLException {
return connection.getAutoCommit();
}
@Override
public String getCatalog() throws SQLException {
return connection.getCatalog();
}
@Override
public Properties getClientInfo() throws SQLException {
return connection.getClientInfo();
}
@Override
public String getClientInfo(String name) throws SQLException {
return connection.getClientInfo(name);
}
@Override
public int getHoldability() throws SQLException {
return connection.getHoldability();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return connection.getMetaData();
}
@Override
public int getTransactionIsolation() throws SQLException {
return connection.getTransactionIsolation();
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return connection.getTypeMap();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return connection.getWarnings();
}
@Override
public boolean isClosed() throws SQLException {
return connection.isClosed();
}
@Override
public boolean isReadOnly() throws SQLException {
return connection.isReadOnly();
}
@Override
public boolean isValid(int timeout) throws SQLException {
return connection.isValid(timeout);
}
@Override
public String nativeSQL(String sql) throws SQLException {
return connection.nativeSQL(sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return connection.prepareCall(sql);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
return connection.prepareCall(sql, resultSetType,
resultSetConcurrency);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
return connection.prepareCall(sql, resultSetType,
resultSetConcurrency, resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql)
throws SQLException {
return connection.prepareStatement(sql);
}
@Override
public PreparedStatement prepareStatement(String sql,
int autoGeneratedKeys) throws SQLException {
return connection.prepareStatement(sql, autoGeneratedKeys);
}
@Override
public PreparedStatement prepareStatement(String sql,
int[] columnIndexes) throws SQLException {
return connection.prepareStatement(sql, columnIndexes);
}
@Override
public PreparedStatement prepareStatement(String sql,
String[] columnNames) throws SQLException {
return connection.prepareStatement(sql, columnNames);
}
@Override
public PreparedStatement prepareStatement(String sql,
int resultSetType, int resultSetConcurrency)
throws SQLException {
return connection.prepareStatement(sql, resultSetType,
resultSetConcurrency);
}
@Override
public PreparedStatement prepareStatement(String sql,
int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
return connection.prepareStatement(sql, resultSetType,
resultSetConcurrency, resultSetHoldability);
}
@Override
public void rollback() throws SQLException {
connection.rollback();
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
connection.setAutoCommit(autoCommit);
}
@Override
public void setCatalog(String catalog) throws SQLException {
connection.setCatalog(catalog);
}
@Override
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
connection.setClientInfo(name, value);
}
@Override
public void setHoldability(int holdability) throws SQLException {
connection.setHoldability(holdability);
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
connection.setReadOnly(readOnly);
}
@Override
public Savepoint setSavepoint() throws SQLException {
return connection.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return connection.setSavepoint(name);
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
connection.setTransactionIsolation(level);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return connection.isWrapperFor(iface);
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return connection.unwrap(iface);
}
@Override
public void abort(Executor arg0) throws SQLException {
connection.abort(arg0);
}
@Override
public int getNetworkTimeout() throws SQLException {
return connection.getNetworkTimeout();
}
@Override
public String getSchema() throws SQLException {
return connection.getSchema();
}
@Override
public void releaseSavepoint(Savepoint arg0) throws SQLException {
connection.releaseSavepoint(arg0);
}
@Override
public void rollback(Savepoint arg0) throws SQLException {
connection.rollback(arg0);
}
@Override
public void setClientInfo(Properties arg0)
throws SQLClientInfoException {
connection.setClientInfo(arg0);
}
@Override
public void setNetworkTimeout(Executor arg0, int arg1)
throws SQLException {
connection.setNetworkTimeout(arg0, arg1);
}
@Override
public void setSchema(String arg0) throws SQLException {
connection.setSchema(arg0);
}
@Override
public void setTypeMap(Map<String, Class<?>> arg0) throws SQLException {
connection.setTypeMap(arg0);
}
}
}<file_sep>/src/by/epam/hostel/dao/connectionpool/ConnectionPoolException.java
package by.epam.hostel.dao.connectionpool;
import by.epam.hostel.exeption.ProjectException;
/**
* This exception appears in ConnectionPool class
*
* @author <NAME>
*/
public class ConnectionPoolException extends ProjectException {
/**
*
*/
private static final long serialVersionUID = 8555125592745246274L;
public ConnectionPoolException(String message) {
super(message);
}
public ConnectionPoolException(String message, Throwable e) {
super(message, e);
}
public ConnectionPoolException(Throwable e) {
super(e);
}
}
<file_sep>/src/by/epam/hostel/dao/impl/IMySqlUserDao.java
package by.epam.hostel.dao.impl;
import java.util.List;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.entity.Order;
import by.epam.hostel.entity.Room;
/**
* This interface holds methods needed to work with database.
*
* @author <NAME>
*/
public interface IMySqlUserDao {
/**
* This method get all not remote room from database.
*
* @return List<Room>
* @throws DAOException
*
*/
public List<Room> getRoomsNotDeleted() throws DaoException;
/**
* This method get all user orders from database.
*
* @param int idUser
* @return List<Order>
* @throws DAOException
*
*/
public List<Order> getUserOrders(int idUser) throws DaoException;
/**
* This method insert Order to database.
*
* @param String
* arrival
* @param String
* departure
* @param int idUser
* @param int idRoom
* @return int the number of rows affected.
* @throws DAOException
*/
public int insertOrder(String arrival, String departure, int idUser,
int idRoom) throws DaoException;
/**
* This method get all rooms relevant parameters from database.
*
* @param String category
* @param int capacity
* @return List<Room>
* @throws DAOException
*/
public List<Room> getRoomsCategoryAndCapacity(String category, int capacity)
throws DaoException;
/**
* This method get all rooms relevant parameters from database.
*
* @param double price
* @param int capacity
* @return List<Room>
* @throws DAOException
*/
public List<Room> getRoomsPriceAndCapacity(double price, int capacity)
throws DaoException;
/**
* This method get all rooms relevant parameters from database.
*
* @param int capacity
* @return List<Room>
* @throws DAOException
*/
public List<Room> getRoomsCapacity(int capacity) throws DaoException;
/**
* This method get all rooms relevant parameters from database.
*
* @param String category
* @param double price
* @param int capacity
* @return List<Room>
* @throws DAOException
*/
public List<Room> getRoomsPriceAndCategoryAndCapacity(String category,
double price, int capacity) throws DaoException;
/**
* This method get all free rooms from database.
*
* @param String arrival
* @param String departure
* @return List<Room>
* @throws DAOException
*/
public List<Room> getFreeRooms(String arrival, String departure)
throws DaoException;
}
<file_sep>/src/by/epam/hostel/entity/Login.java
package by.epam.hostel.entity;
/**
* This is the class of the business object acting as a storage database table
* Login.
*
* @author <NAME>
*/
public class Login extends Entity {
/**
*
*/
private static final long serialVersionUID = 869263177225053864L;
private int idUser;
private String login;
private int password;
private boolean status;
private boolean blacklist;
public Login(int idUser, String login, int password, boolean status,
boolean blacklist) {
super();
this.idUser = idUser;
this.login = login;
this.password = <PASSWORD>;
this.status = status;
this.blacklist = blacklist;
}
public Login() {
}
public int getIdUser() {
return idUser;
}
public void setIdUser(int idUser) {
this.idUser = idUser;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public int getPassword() {
return password;
}
public void setPassword(int password) {
this.password = <PASSWORD>;
}
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public boolean isBlacklist() {
return blacklist;
}
public void setBlacklist(boolean blacklist) {
this.blacklist = blacklist;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (blacklist ? 1231 : 1237);
result = prime * result + idUser;
result = prime * result + ((login == null) ? 0 : login.hashCode());
result = prime * result + password;
result = prime * result + (status ? 1231 : 1237);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Login other = (Login) obj;
if (blacklist != other.blacklist) {
return false;
}
if (idUser != other.idUser) {
return false;
}
if (login == null) {
if (other.login != null) {
return false;
}
} else if (!login.equals(other.login)) {
return false;
}
if (password != other.password) {
return false;
}
if (status != other.status) {
return false;
}
return true;
}
@Override
public String toString() {
return "Login [idUser=" + idUser + ", login=" + login + ", password="
+ <PASSWORD> + ", status=" + status + ", blacklist=" + blacklist
+ "]";
}
}
<file_sep>/src/by/epam/hostel/entity/Room.java
package by.epam.hostel.entity;
/**
* This is the class of the business object acting as a storage database table
* Rooms.
*
* @author <NAME>
*/
public class Room extends Entity {
/**
*
*/
private static final long serialVersionUID = 7850899406976248706L;
private int idRoom;
private double price;
private int capacity;
private Category category;
private boolean isDeleted;
public Room() {
}
public Room(int idRoom, double price, int capacity, Category category,
boolean isDeleted) {
super();
this.idRoom = idRoom;
this.price = price;
this.capacity = capacity;
this.category = category;
this.isDeleted = isDeleted;
}
public Room(int idRoom, double price, int capacity, Category category) {
super();
this.idRoom = idRoom;
this.price = price;
this.capacity = capacity;
this.category = category;
}
public int getIdRoom() {
return idRoom;
}
public void setIdRoom(int idRoom) {
this.idRoom = idRoom;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getCapacity() {
return capacity;
}
public void setCapacity(int capacity) {
this.capacity = capacity;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public boolean isDeleted() {
return isDeleted;
}
public void setDeleted(boolean isDeleted) {
this.isDeleted = isDeleted;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + capacity;
result = prime * result
+ ((category == null) ? 0 : category.hashCode());
result = prime * result + idRoom;
result = prime * result + (isDeleted ? 1231 : 1237);
long temp;
temp = Double.doubleToLongBits(price);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Room other = (Room) obj;
if (capacity != other.capacity) {
return false;
}
if (category != other.category) {
return false;
}
if (idRoom != other.idRoom) {
return false;
}
if (isDeleted != other.isDeleted) {
return false;
}
if (Double.doubleToLongBits(price) != Double
.doubleToLongBits(other.price)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Room [idRoom=" + idRoom + ", price=" + price + ", capacity="
+ capacity + ", category=" + category + ", isDeleted="
+ isDeleted + "]";
}
}
<file_sep>/src/by/epam/hostel/logic/impl/user/CommandBooked.java
package by.epam.hostel.logic.impl.user;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlAdminDao;
import by.epam.hostel.dao.impl.IMySqlUserDao;
import by.epam.hostel.entity.Room;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class reservation room for the
* user.
*
* @author <NAME>
*/
public class CommandBooked implements ICommand {
private final String INFO = "user.info";
/**
* This method writes the order number into the database, and considers the
* total amount of the order and sends the user to the main page and a
* message for him.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
Integer idRoom = Integer.valueOf(request
.getParameter(RequestParameterName.ID_ROOM));
int idUser = (int) request.getSession(true).getAttribute(
RequestParameterName.ID_USER);
String arrival = (String) request.getSession().getAttribute(
RequestParameterName.ARRIVAL_USER);
String departure = (String) request.getSession().getAttribute(
RequestParameterName.DEPARTURE_USER);
int amountDays = (int) request.getSession().getAttribute(
RequestParameterName.AMOUNT_DAYS);
double totalPrice = 0;
try {
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
IMySqlUserDao daoUser = abstractDAOFactory.getMySqlUserDao();
IMySqlAdminDao daoAdmin = abstractDAOFactory.getMySqlAdminDao();
daoUser.insertOrder(arrival, departure, idUser, idRoom);
Room room = daoAdmin.getRoom(idRoom);
totalPrice = room.getPrice() * (amountDays - 1);
} catch (DaoException e) {
throw new CommandException(e);
}
request.setAttribute(RequestParameterName.USER_INFO, INFO);
request.setAttribute(RequestParameterName.TOTAL_PRICE, totalPrice);
return JspPageName.USER_PAGE;
}
}
<file_sep>/src/by/epam/hostel/localization/blacklist_en.properties
blacklist.message = You are blacklisted. For more information, contact the administrator.
blacklist.link = Back to form<file_sep>/src/by/epam/hostel/dao/factory/DaoFactory.java
package by.epam.hostel.dao.factory;
import by.epam.hostel.dao.DaoException;
/**
*
* This class holds methods that return the necessary implementation dao.
*
* @author <NAME>
*/
public class DaoFactory {
public enum DAOType {
MY_SQL_DAO;
}
private DaoFactory() {
}
/**
*
* The methods returns implementation dao.
*
* @param DAOType type
* @return AbstractDAOFactory
* @throws DaoException
*/
public static AbstractDAOFactory getDAO(DAOType type) throws DaoException {
AbstractDAOFactory daoFactory = null;
switch (type) {
case MY_SQL_DAO:
daoFactory = new MySqlDaoFactory();
default:
daoFactory = new MySqlDaoFactory();
break;
}
return daoFactory;
}
}
<file_sep>/src/by/epam/hostel/logic/impl/admin/CommandAddBlacklist.java
package by.epam.hostel.logic.impl.admin;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlAdminDao;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
import by.epam.hostel.logic.helper.Helper;
/**
* This class implements a pattern command. This class adds the user to the
* black list.
*
* @author <NAME>
*/
public class CommandAddBlacklist implements ICommand {
/**
* This method adds the user to the blacklist.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
try {
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
IMySqlAdminDao dao = abstractDAOFactory.getMySqlAdminDao();
Integer idUser = Integer.valueOf(request
.getParameter(RequestParameterName.ID_USER));
Boolean blacklistBool = Boolean.valueOf(request
.getParameter(RequestParameterName.BLACKLIST_USER));
int blacklistInt = Helper.getInt(blacklistBool);
dao.setBlacklistUser(idUser, Helper.changeInt(blacklistInt));
request.setAttribute(RequestParameterName.USER, dao.getUser(idUser));
} catch (DaoException e) {
throw new CommandException(e);
}
return JspPageName.USERFIND_PAGE;
}
}
<file_sep>/src/by/epam/hostel/logic/impl/CommandLocale.java
package by.epam.hostel.logic.impl;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class change the language in
* the web-application.
*
* @author <NAME>
*/
public class CommandLocale implements ICommand {
/**
* This method change the language and goes to the start page.
*
* @param request a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
String localeName = (String) request.getSession(true).getAttribute(
RequestParameterName.LOCALE);
if ("en".equalsIgnoreCase(localeName)) {
localeName = "ru";
} else {
localeName = "en";
}
request.getSession(true).setAttribute(RequestParameterName.LOCALE,
localeName);
return JspPageName.INDEX_PAGE;
}
}
<file_sep>/src/by/epam/hostel/logic/impl/admin/CommandMakeAdmin.java
package by.epam.hostel.logic.impl.admin;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlAdminDao;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
import by.epam.hostel.logic.helper.Helper;
/**
* This class implements a pattern command. This class changes the status of the
* user.
*
* @author <NAME>
*/
public class CommandMakeAdmin implements ICommand {
/**
* This method changes the status of the user with the administrator or
* user.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
try {
Integer idUser = Integer.valueOf(request
.getParameter(RequestParameterName.ID_USER));
Boolean statusBool = Boolean.valueOf(request
.getParameter(RequestParameterName.STATUS_USER));
int statusInt = Helper.getInt(statusBool);
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
IMySqlAdminDao dao = abstractDAOFactory.getMySqlAdminDao();
dao.setStatus(idUser, Helper.changeInt(statusInt));
request.setAttribute(RequestParameterName.USER, dao.getUser(idUser));
} catch (DaoException e) {
throw new CommandException(e);
}
return JspPageName.USERFIND_PAGE;
}
}
<file_sep>/src/by/epam/hostel/localization/title_en.properties
title.locbutton.name = RU
title.name = Hotel Minsk 3*<file_sep>/src/by/epam/hostel/tag/GetDateTag.java
package by.epam.hostel.tag;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Locale;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
/**
* This tag displays the current date according to the locale.
*
* @author <NAME>
*
*/
@SuppressWarnings("serial")
public class GetDateTag extends TagSupport {
private String locale;
public void setLocale(String locale) {
this.locale = locale;
}
private Locale loc;
/**
* This method prints the current date.
*
* @return SKIP_BODY
* @throws JspException
* a JspException
*/
@Override
public int doStartTag() throws JspException {
if ("ru".equalsIgnoreCase(locale)) {
loc = new Locale("ru", "RU");
} else {
loc = new Locale("en", "EN");
}
GregorianCalendar gc = (GregorianCalendar) Calendar.getInstance();
DateFormat dateFormat = DateFormat
.getDateInstance(DateFormat.FULL, loc);
String time = "<hr/><b> " + dateFormat.format(gc.getTime())
+ " </b><hr/>";
try {
JspWriter out = pageContext.getOut();
out.write(time);
} catch (IOException e) {
throw new JspException(e.getMessage());
}
return SKIP_BODY;
}
/**
* @return EVAL_PAGE
* @throws JspException
* a JspException
*/
@Override
public int doEndTag() throws JspException {
return EVAL_PAGE;
}
}<file_sep>/src/by/epam/hostel/localization/user_en.properties
user.message = Welcome,
user.info = Booked Room
user.exit = Exit
user.orders = Orders
user.makeorder = Make a booking
user.allprice= Total price
user.order.idorder = ID Order
user.order.arrival = Arrival
user.order.departure = Departure
user.room.idroom = Number Room
user.room.price = Price per night
user.room.category = Category
user.room.capacity= Capacity
user.filldate.message = Enter the dates of your stay:
user.filldate.arrival = Check in:
user.filldate.departure = End of your stay:
user.filldate.day= dd
user.filldate.month= mm
user.filldate.year= yyyy
user.filldate.find= Find
user.picks.selection = Selection of parameters
user.picks.price = Price per night
user.picks.category = Category
user.picks.capacity = Capacity
user.picks.book= Booking
user.picks.find= Find
<file_sep>/src/by/epam/hostel/localization/admin_en.properties
admin.message = Welcome,
admin.exit = Exit
admin.users = Users
admin.rooms = Rooms
admin.orders = Orders
admin.find = Find
admin.notfind = There is no such ID in database.
admin.user.iduser = ID User
admin.user.name = Name
admin.user.surname = Surname
admin.user.numpass= Number Passport
admin.user.email= E-mail
admin.user.status= Status
admin.user.blacklist= Blacklist
admin.room.idroom = Number room
admin.room.price = Price per night
admin.room.category = Category
admin.room.capacity= Capacity
admin.room.isdeleted= Deleted
admin.room.insertroom = Add Room
admin.room.booked = Booked
admin.room.booking = Arrival
admin.room.notbooking = Departure
admin.order.idorder = ID Order
admin.order.arrival = Arrival
admin.order.departure = Departure
admin.order.paid = Paid
<file_sep>/src/by/epam/hostel/dao/connectionpool/MySqlPropertyManager.java
package by.epam.hostel.dao.connectionpool;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
*
* This class implements a pattern singleton. This class derives from the
* configuration file settings for the database.
*
* @author <NAME>
*/
public class MySqlPropertyManager {
/**
* It is a logger which print some messages to log file.
*/
private static final Logger LOG = Logger
.getLogger(MySqlPropertyManager.class);
private final String PATH = "db.properties";
private final String PREFIX = this.getClass().getResource("/").getPath();
private Properties properties = new Properties();
private BufferedReader reader = null;
private File file = new File(PREFIX + PATH);
/**
* The inner class for implementation singleton. It holds
* MySqlPropertyManager instance.
*/
private static class Holder {
private static final MySqlPropertyManager INSTANCE = new MySqlPropertyManager();
}
/**
* The method gives MySqlPropertyManager singleton instance.
*/
public static MySqlPropertyManager getInstance() {
return Holder.INSTANCE;
}
/**
* The constructor creates BufferedReader and reads configuration file
* database.
*/
private MySqlPropertyManager() {
try {
reader = new BufferedReader(new FileReader(file));
properties.load(reader);
} catch (FileNotFoundException e) {
LOG.error("File db.properties not found.", e);
} catch (IOException e) {
LOG.error(e);
}
}
/**
* The method gives extract key parameters.
*
* @param String key
* @return String
*/
public String getValue(String key) {
return properties.getProperty(key);
}
}
<file_sep>/src/by/epam/hostel/dao/connectionpool/MySqlParameter.java
package by.epam.hostel.dao.connectionpool;
/**
* This class contains information about the name of the parameters for the
* database.
*
* @author <NAME>
*/
public final class MySqlParameter {
private MySqlParameter() {
}
public static final String DB_DRIVER = "db.driver";
public static final String DB_URL = "db.url";
public static final String DB_USER = "db.user";
public static final String DB_PASSWORD = "<PASSWORD>";
public static final String DB_POLL_SIZE = "db.poolsize";
}
<file_sep>/src/by/epam/hostel/logic/impl/admin/CommandGetBooked.java
package by.epam.hostel.logic.impl.admin;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlAdminDao;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class returns the date of the
* reservation of the room.
*
* @author <NAME>
*/
public class CommandGetBooked implements ICommand {
private final String NOT_FIND = "admin.notfind";
/**
* This method returns the date of the reservation of the room.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
String idRoomStr = request.getParameter(RequestParameterName.ID_ROOM);
String pageName = null;
try {
if ("".equalsIgnoreCase(idRoomStr) != true) {
Integer idRoom = Integer.valueOf(idRoomStr);
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
IMySqlAdminDao dao = abstractDAOFactory.getMySqlAdminDao();
request.setAttribute(RequestParameterName.GET_BOOKEDDATES,
dao.getBookedDatesRoom(idRoom));
pageName = JspPageName.BOOKEDDATE_PAGE;
} else {
request.setAttribute(RequestParameterName.ERROR, NOT_FIND);
pageName = JspPageName.BOOKEDDATE_PAGE;
}
} catch (DaoException e) {
throw new CommandException(e);
}
return pageName;
}
}
<file_sep>/src/by/epam/hostel/logic/impl/user/CommandSampleRooms.java
package by.epam.hostel.logic.impl.user;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlUserDao;
import by.epam.hostel.entity.Room;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class in which the sample rooms
* on an individual user's request.
*
* @author <NAME>
*/
public class CommandSampleRooms implements ICommand {
private final String FAMILY = "FAMILY";
private final String LUX = "LUX";
private final String SUPER_LUX = "SUPER_LUX";
private final String ECONOM = "ECONOM";
/**
* This method implements sample needed rooms for user parameters.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
List<Room> rooms = new ArrayList<Room>();
try {
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
IMySqlUserDao dao = abstractDAOFactory.getMySqlUserDao();
String priceStr = request
.getParameter(RequestParameterName.PRICE_ROOM);
String categoryStr = request
.getParameter(RequestParameterName.CATEGORY_ROOM);
String capacityStr = request
.getParameter(RequestParameterName.CAPACITY_ROOM);
Integer capacity = Integer.valueOf(capacityStr);
if (("".equalsIgnoreCase(priceStr) != true)) {
Double price = Double.valueOf(priceStr);
switch (categoryStr) {
case FAMILY:
rooms = dao.getRoomsPriceAndCategoryAndCapacity(
categoryStr, price, capacity);
break;
case LUX:
rooms = dao.getRoomsPriceAndCategoryAndCapacity(
categoryStr, price, capacity);
break;
case SUPER_LUX:
rooms = dao.getRoomsPriceAndCategoryAndCapacity(
categoryStr, price, capacity);
break;
case ECONOM:
rooms = dao.getRoomsPriceAndCategoryAndCapacity(
categoryStr, price, capacity);
break;
default:
rooms = dao.getRoomsPriceAndCapacity(price, capacity);
break;
}
} else {
switch (categoryStr) {
case FAMILY:
rooms = dao.getRoomsCategoryAndCapacity(categoryStr,
capacity);
break;
case LUX:
rooms = dao.getRoomsCategoryAndCapacity(categoryStr,
capacity);
break;
case SUPER_LUX:
rooms = dao.getRoomsCategoryAndCapacity(categoryStr,
capacity);
break;
case ECONOM:
rooms = dao.getRoomsCategoryAndCapacity(categoryStr,
capacity);
break;
default:
rooms = dao.getRoomsCapacity(capacity);
break;
}
}
} catch (DaoException e) {
throw new CommandException(e);
}
request.getSession(true).setAttribute(RequestParameterName.FREEROOMS,
rooms);
return JspPageName.USERPICKORDER_PAGE;
}
}
<file_sep>/src/by/epam/hostel/entity/BookedDate.java
package by.epam.hostel.entity;
import java.util.Date;
/**
* This is the class of the business object acting as a storage database table
* BookedDates.
*
* @author <NAME>
*/
public class BookedDate extends Entity {
/**
*
*/
private static final long serialVersionUID = 1L;
private int idBooked;
private int idRoom;
private Date booking;
private Date notBooking;
public BookedDate() {
super();
}
public BookedDate(int idBooked, int idRoom, Date booking, Date notBooking) {
super();
this.idBooked = idBooked;
this.idRoom = idRoom;
this.booking = booking;
this.notBooking = notBooking;
}
public int getIdBooked() {
return idBooked;
}
public void setIdBooked(int idBooked) {
this.idBooked = idBooked;
}
public int getIdRoom() {
return idRoom;
}
public void setIdRoom(int idRoom) {
this.idRoom = idRoom;
}
public Date getBooking() {
return booking;
}
public void setBooking(Date booking) {
this.booking = booking;
}
public Date getNotBooking() {
return notBooking;
}
public void setNotBooking(Date notBooking) {
this.notBooking = notBooking;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((booking == null) ? 0 : booking.hashCode());
result = prime * result + idBooked;
result = prime * result + idRoom;
result = prime * result
+ ((notBooking == null) ? 0 : notBooking.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
BookedDate other = (BookedDate) obj;
if (booking == null) {
if (other.booking != null) {
return false;
}
} else if (!booking.equals(other.booking)) {
return false;
}
if (idBooked != other.idBooked) {
return false;
}
if (idRoom != other.idRoom) {
return false;
}
if (notBooking == null) {
if (other.notBooking != null) {
return false;
}
} else if (!notBooking.equals(other.notBooking)) {
return false;
}
return true;
}
@Override
public String toString() {
return "BookedDate [idBooked=" + idBooked + ", idRoom=" + idRoom
+ ", booking=" + booking + ", notBooking=" + notBooking + "]";
}
}
<file_sep>/src/by/epam/hostel/logic/CommandException.java
package by.epam.hostel.logic;
import by.epam.hostel.exeption.ProjectException;
/**
* This exception appears from CommandException.
*
* @author <NAME>
*/
public class CommandException extends ProjectException {
/**
*
*/
private static final long serialVersionUID = 8967941434873708746L;
public CommandException(String message, Throwable e) {
super(message, e);
}
public CommandException(String message) {
super(message);
}
public CommandException(Throwable e) {
super(e);
}
}
<file_sep>/WebContent/WEB-INF/classes/db.properties
db.driver = com.mysql.jdbc.Driver
db.url = jdbc:mysql://localhost:3306/hotel
db.user = root
db.password = <PASSWORD>
db.poolsize = 10<file_sep>/src/by/epam/hostel/localization/register_ru.properties
register.name = \u0418\u043C\u044F
register.surname = \u0424\u0430\u043C\u0438\u043B\u0438\u044F
register.numpass = <PASSWORD>430\u0441\u043F\u043E\u0440\u0442\u0430
register.login = \u041B\u043E\u0433\u0438\u043D(e-mail)
register.password = <PASSWORD>
register.passwordmatch = \<PASSWORD>3F\u0430\u0440\u043E\u043B\u044C
register.message = \u041E\u0442\u043F\u0440\u0430\u0432\u0438\u0442\u044C<file_sep>/src/by/epam/hostel/localization/error_en.properties
error.login = Enter the wrong login
error.fieldnot= Field is not filled.
error.name = ERROR
error.passwordnotmatch = Password do not match
error.link = Back to mainpage<file_sep>/src/by/epam/hostel/logic/impl/user/CommandCheckDate.java
package by.epam.hostel.logic.impl.user;
import java.util.GregorianCalendar;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.controller.RequestParameterName;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.factory.AbstractDAOFactory;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.dao.impl.IMySqlUserDao;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
import by.epam.hostel.logic.helper.Helper;
/**
* This class implements a pattern command. This class determines the
* availability for user.
*
* @author <NAME>
*/
public class CommandCheckDate implements ICommand {
private final String DASH = "-";
/**
* This method selects the availability for the user in a given period of
* time.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
IMySqlUserDao dao = null;
String aday = request.getParameter(RequestParameterName.ADAY);
String amonth = request.getParameter(RequestParameterName.AMONTH);
String ayear = request.getParameter(RequestParameterName.AYEAR);
String dday = request.getParameter(RequestParameterName.DDAY);
String dmonth = request.getParameter(RequestParameterName.DMONTH);
String dyear = request.getParameter(RequestParameterName.DYEAR);
StringBuilder arrival = new StringBuilder();
StringBuilder departure = new StringBuilder();
arrival.append(ayear);
arrival.append(DASH);
arrival.append(amonth);
arrival.append(DASH);
arrival.append(aday);
departure.append(dyear);
departure.append(DASH);
departure.append(dmonth);
departure.append(DASH);
departure.append(dday);
GregorianCalendar dataArrival = new GregorianCalendar(
Integer.valueOf(ayear), Integer.valueOf(amonth) - 1,
Integer.valueOf(aday));
GregorianCalendar dataDeparture = new GregorianCalendar(
Integer.valueOf(dyear), Integer.valueOf(dmonth) - 1,
Integer.valueOf(dday));
int amountDays = Helper.getAmountDays(dataArrival, dataDeparture);
request.getSession(true).setAttribute(
RequestParameterName.ARRIVAL_USER, arrival.toString());
request.getSession().setAttribute(RequestParameterName.DEPARTURE_USER,
departure.toString());
request.getSession().setAttribute(RequestParameterName.AMOUNT_DAYS,
amountDays);
try {
AbstractDAOFactory abstractDAOFactory = DaoFactory
.getDAO(DAOType.MY_SQL_DAO);
dao = abstractDAOFactory.getMySqlUserDao();
request.getSession().setAttribute(RequestParameterName.FREEROOMS,
dao.getFreeRooms(arrival.toString(), departure.toString()));
} catch (DaoException e) {
throw new CommandException(e);
}
return JspPageName.USERPICKORDER_PAGE;
}
}
<file_sep>/src/by/epam/hostel/dao/impl/MySqlUserDao.java
package by.epam.hostel.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import by.epam.hostel.dao.DaoException;
import by.epam.hostel.dao.connectionpool.ConnectionPool;
import by.epam.hostel.dao.connectionpool.ConnectionPoolException;
import by.epam.hostel.dao.factory.DaoFactory;
import by.epam.hostel.dao.factory.DaoFactory.DAOType;
import by.epam.hostel.entity.Category;
import by.epam.hostel.entity.Order;
import by.epam.hostel.entity.Room;
/**
* The inner class for implementation singleton. Direct implementation of the
* interface MySqlUserDao.
*
* @author <NAME>
*/
public final class MySqlUserDao implements IMySqlUserDao {
private static ConnectionPool connectionPool = ConnectionPool.getInstance();
private final String GET_ROOMS_NOT_DELETED = "SELECT * FROM rooms WHERE isDeleted=0";
private final String GET_USER_ORDERS = "SELECT idOrder, idRoom, price, category, capacity, arrival, departure FROM orders, rooms, users WHERE idUser = users_idUser and rooms.idRoom = Rooms_idRoom and idUser=";
private final String GET_BOOKEDROOM = "SELECT rooms_idRoom FROM bookeddate WHERE notbooking>? and booking<? group by rooms_idRoom";
private final String GET_SPECIFIC_ROOMS_CATEGORY_AND_PRICE = "SELECT * FROM rooms WHERE category=? and price<=? and capacity=?";
private final String GET_SPECIFIC_ROOMS_CATEGORY = "SELECT * FROM rooms WHERE category=? and capacity=?";
private final String GET_SPECIFIC_ROOMS_PRICE = "SELECT * FROM rooms WHERE price<=? and capacity=?";
private final String GET_SPECIFIC_ROOMS_CAPACITY = "SELECT * FROM rooms WHERE capacity=?";
private final String INSERT_ORDER = "INSERT INTO orders (arrival, departure, users_idUser, rooms_idRoom, paid) VALUES (?,?,?,?,0)";
private final String INSERT_BOOKEDDATE = "INSERT INTO bookeddate (rooms_idRoom, booking, notbooking) VALUES (?,?,?)";
private MySqlUserDao() {
}
/**
* The inner class for implementation singleton. It holds MySqlUserDao
* instance.
*/
private static class Holder {
private final static MySqlUserDao INSTANCE = new MySqlUserDao();
}
/**
* The method gives MySqlUserDao singleton instance.
*/
public static MySqlUserDao getInstance() {
return Holder.INSTANCE;
}
@Override
public List<Room> getRoomsNotDeleted() throws DaoException {
List<Room> rooms = new ArrayList<Room>();
Connection connection = null;
Statement statement = null;
try {
connection = connectionPool.takeConnection();
statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(GET_ROOMS_NOT_DELETED);
while (resultSet.next()) {
Room room = new Room();
room.setIdRoom(resultSet.getInt(1));
room.setPrice(resultSet.getDouble(2));
switch (resultSet.getString(3)) {
case "ECONOM":
room.setCategory(Category.ECONOM);
break;
case "FAMILY":
room.setCategory(Category.FAMILY);
break;
case "LUX":
room.setCategory(Category.LUX);
break;
case "SUPER_LUX":
room.setCategory(Category.SUPER_LUX);
break;
default:
throw new DaoException("There is no such category.");
}
room.setCapacity(resultSet.getInt(4));
room.setDeleted(resultSet.getBoolean(5));
rooms.add(room);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, statement);
}
return rooms;
}
@Override
public List<Room> getRoomsCategoryAndCapacity(String category, int capacity)
throws DaoException {
List<Room> rooms = new ArrayList<Room>();
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = connectionPool.takeConnection();
preparedStatement = connection
.prepareStatement(GET_SPECIFIC_ROOMS_CATEGORY);
preparedStatement.setString(1, category);
preparedStatement.setInt(2, capacity);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Room room = new Room();
room.setIdRoom(resultSet.getInt(1));
room.setPrice(resultSet.getDouble(2));
switch (resultSet.getString(3)) {
case "ECONOM":
room.setCategory(Category.ECONOM);
break;
case "FAMILY":
room.setCategory(Category.FAMILY);
break;
case "LUX":
room.setCategory(Category.LUX);
break;
case "SUPER_LUX":
room.setCategory(Category.SUPER_LUX);
break;
default:
throw new DaoException("There is no such category.");
}
room.setCapacity(resultSet.getInt(4));
room.setDeleted(resultSet.getBoolean(5));
rooms.add(room);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, preparedStatement);
}
return rooms;
}
@Override
public List<Room> getRoomsPriceAndCapacity(double price, int capacity)
throws DaoException {
List<Room> rooms = new ArrayList<Room>();
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = connectionPool.takeConnection();
preparedStatement = connection
.prepareStatement(GET_SPECIFIC_ROOMS_PRICE);
preparedStatement.setDouble(1, price);
preparedStatement.setInt(2, capacity);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Room room = new Room();
room.setIdRoom(resultSet.getInt(1));
room.setPrice(resultSet.getDouble(2));
switch (resultSet.getString(3)) {
case "ECONOM":
room.setCategory(Category.ECONOM);
break;
case "FAMILY":
room.setCategory(Category.FAMILY);
break;
case "LUX":
room.setCategory(Category.LUX);
break;
case "SUPER_LUX":
room.setCategory(Category.SUPER_LUX);
break;
default:
throw new DaoException("There is no such category.");
}
room.setCapacity(resultSet.getInt(4));
room.setDeleted(resultSet.getBoolean(5));
rooms.add(room);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, preparedStatement);
}
return rooms;
}
@Override
public List<Room> getRoomsPriceAndCategoryAndCapacity(String category,
double price, int capacity) throws DaoException {
List<Room> rooms = new ArrayList<Room>();
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = connectionPool.takeConnection();
preparedStatement = connection
.prepareStatement(GET_SPECIFIC_ROOMS_CATEGORY_AND_PRICE);
preparedStatement.setString(1, category);
preparedStatement.setDouble(2, price);
preparedStatement.setInt(3, capacity);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Room room = new Room();
room.setIdRoom(resultSet.getInt(1));
room.setPrice(resultSet.getDouble(2));
switch (resultSet.getString(3)) {
case "ECONOM":
room.setCategory(Category.ECONOM);
break;
case "FAMILY":
room.setCategory(Category.FAMILY);
break;
case "LUX":
room.setCategory(Category.LUX);
break;
case "SUPER_LUX":
room.setCategory(Category.SUPER_LUX);
break;
default:
throw new DaoException("There is no such category.");
}
room.setCapacity(resultSet.getInt(4));
room.setDeleted(resultSet.getBoolean(5));
rooms.add(room);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, preparedStatement);
}
return rooms;
}
@Override
public List<Room> getRoomsCapacity(int capacity) throws DaoException {
List<Room> rooms = new ArrayList<Room>();
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = connectionPool.takeConnection();
preparedStatement = connection
.prepareStatement(GET_SPECIFIC_ROOMS_CAPACITY);
preparedStatement.setInt(1, capacity);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
Room room = new Room();
room.setIdRoom(resultSet.getInt(1));
room.setPrice(resultSet.getDouble(2));
switch (resultSet.getString(3)) {
case "ECONOM":
room.setCategory(Category.ECONOM);
break;
case "FAMILY":
room.setCategory(Category.FAMILY);
break;
case "LUX":
room.setCategory(Category.LUX);
break;
case "SUPER_LUX":
room.setCategory(Category.SUPER_LUX);
break;
default:
throw new DaoException("There is no such category.");
}
room.setCapacity(resultSet.getInt(4));
room.setDeleted(resultSet.getBoolean(5));
rooms.add(room);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, preparedStatement);
}
return rooms;
}
@Override
public List<Order> getUserOrders(int idUser) throws DaoException {
List<Order> orders = new ArrayList<Order>();
Order order = null;
Room room = null;
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = connectionPool.takeConnection();
statement = connection.createStatement();
resultSet = statement.executeQuery(GET_USER_ORDERS + idUser);
while (resultSet.next()) {
order = new Order();
room = new Room();
order.setIdOrder(resultSet.getInt(1));
room.setIdRoom(resultSet.getInt(2));
room.setPrice(resultSet.getDouble(3));
switch (resultSet.getString(4)) {
case "ECONOM":
room.setCategory(Category.ECONOM);
break;
case "FAMILY":
room.setCategory(Category.FAMILY);
break;
case "LUX":
room.setCategory(Category.LUX);
break;
case "SUPER_LUX":
room.setCategory(Category.SUPER_LUX);
break;
default:
throw new DaoException("There is no such category.");
}
room.setCapacity(resultSet.getInt(5));
order.setArrival(resultSet.getDate(6));
order.setDeparture((resultSet.getDate(7)));
order.setRoom(room);
orders.add(order);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, statement);
}
return orders;
}
@Override
public int insertOrder(String arrival, String departure, int idUser,
int idRoom) throws DaoException {
int result = 0;
Connection connection = null;
PreparedStatement preparedStatement = null;
try {
connection = connectionPool.takeConnection();
preparedStatement = connection.prepareStatement(INSERT_ORDER);
preparedStatement.setString(1, arrival);
preparedStatement.setString(2, departure);
preparedStatement.setInt(3, idUser);
preparedStatement.setInt(4, idRoom);
result = preparedStatement.executeUpdate();
preparedStatement.close();
preparedStatement = connection.prepareStatement(INSERT_BOOKEDDATE);
preparedStatement.setInt(1, idRoom);
preparedStatement.setString(2, arrival);
preparedStatement.setString(3, departure);
result = preparedStatement.executeUpdate();
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, preparedStatement);
}
return result;
}
@Override
public List<Room> getFreeRooms(String arrival, String departure)
throws DaoException {
IMySqlAdminDao dao = DaoFactory.getDAO(DAOType.MY_SQL_DAO)
.getMySqlAdminDao();
List<Room> busyRooms = new ArrayList<Room>();
List<Room> allRooms = new ArrayList<Room>();
allRooms.addAll(getRoomsNotDeleted());
Room room = null;
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = connectionPool.takeConnection();
preparedStatement = connection.prepareStatement(GET_BOOKEDROOM);
preparedStatement.setString(1, arrival);
preparedStatement.setString(2, departure);
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
room = dao.getRoom(resultSet.getInt(1));
busyRooms.add(room);
}
} catch (ConnectionPoolException | SQLException e) {
throw new DaoException(e);
} finally {
connectionPool.closeConnection(connection, preparedStatement);
}
allRooms.removeAll(busyRooms);
return allRooms;
}
}
<file_sep>/src/by/epam/hostel/logic/impl/CommandLogout.java
package by.epam.hostel.logic.impl;
import javax.servlet.http.HttpServletRequest;
import by.epam.hostel.controller.JspPageName;
import by.epam.hostel.logic.ICommand;
import by.epam.hostel.logic.CommandException;
/**
* This class implements a pattern command. This class executes logout of user
* and clears session.
*
* @author <NAME>
*
*/
public class CommandLogout implements ICommand {
/**
* This method handles user's request logout from site. The session will be
* invalidated.
*
* @param request
* a httpServletRequest
* @throws CommandException
* @return String which contains page's path for displaying
*/
@Override
public String execute(HttpServletRequest request) throws CommandException {
request.getSession(true).invalidate();
return JspPageName.INDEX_PAGE;
}
}
<file_sep>/src/by/epam/hostel/localization/register_en.properties
register.name = Name
register.surname = Surname
register.numpass = Number Passport
register.login = Login(e-mail)
register.password = <PASSWORD>
register.passwordmatch = <PASSWORD>
register.message = Send
| 5318813fb979be60901206e3190a979a08d365fb | [
"Java",
"INI"
] | 34 | Java | AlexNastin/EpamHostelProject | 994ac5b0b4ed0e61cb19e2b987bb3cd3826dc00d | 9c82d03bed9fb09e1edf7feb9e3a656deeea301a | |
refs/heads/main | <repo_name>jamie-taylor-privitar/empty<file_sep>/.teamcity/settings.kts
import jetbrains.buildServer.configs.kotlin.v2019_2.*
import jetbrains.buildServer.configs.kotlin.v2019_2.buildSteps.maven
version = "2019.2"
project {
// name = "<NAME>"
description = "Jamie"
buildType {
id("adfsdfsf")
name = "jamie build type"
steps {
maven {
goals = "test"
runnerArgs = "-pl empty"
mavenVersion = auto()
}
}
}
}<file_sep>/.teamcity/pom.xml
<?xml version="1.0"?>
<project>
<modelVersion>4.0.0</modelVersion>
<name>PrivitarPlatform_Pipelines Config DSL Script</name>
<groupId>PrivitarPlatform_Pipelines</groupId>
<artifactId>PrivitarPlatform_Pipelines_dsl</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-parent</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<build>
<sourceDirectory>${basedir}/src/main/kotlin</sourceDirectory>
<testSourceDirectory>${basedir}/src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<artifactId>kotlin-maven-plugin</artifactId>
<groupId>org.jetbrains.kotlin</groupId>
<version>${kotlin.version}</version>
<configuration/>
<executions>
<execution>
<id>compile</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile</id>
<phase>process-test-sources</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>teamcity-configs-maven-plugin</artifactId>
<version>${teamcity.dsl.version}</version>
<configuration>
<format>kotlin</format>
<dstDir>target/generated-configs</dstDir>
<contextParameters>
<buildsToRegister>all</buildsToRegister>
</contextParameters>
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin</artifactId>
<version>${teamcity.dsl.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.teamcity</groupId>
<artifactId>configs-dsl-kotlin-plugins</artifactId>
<version>1.0-SNAPSHOT</version>
<type>pom</type>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-script-runtime</artifactId>
<version>${kotlin.version}</version>
<scope>compile</scope>
</dependency>
<!-- test -->
<!-- we are not using scope 'test' because otherwise the plugin goal teamcity-configs:generate fails -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.4.6</version>
</dependency>
<dependency>
<groupId>com.nhaarman.mockitokotlin2</groupId>
<artifactId>mockito-kotlin</artifactId>
<version>2.2.0</version>
</dependency>
</dependencies>
</project> | a2a20a03726eb8ece591c18ebc3eab7f96b8a2fb | [
"Maven POM",
"Kotlin"
] | 2 | Kotlin | jamie-taylor-privitar/empty | d64271d14df1209768aba82aefa934cb1c6f8769 | bc37987c80f508a01458400e0d77b38c196712bc | |
refs/heads/master | <file_sep>[](https://travis-ci.org/ttwd80/homer)
[](https://coveralls.io/github/ttwd80/homer?branch=master)
# homer
Helps study for test
<file_sep>package com.github.ttwd80.homer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.crypto.scrypt.SCryptPasswordEncoder;
import lombok.extern.slf4j.Slf4j;
@Configuration
@Slf4j
public class SecurityConfiguration {
@Bean
public PasswordEncoder passwordEncoder() {
return new SCryptPasswordEncoder();
}
}
<file_sep>package com.github.ttwd80.homer.model.service;
import com.github.ttwd80.homer.model.entity.User;
import com.github.ttwd80.homer.model.repository.UserRepository;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import java.util.Collections;
import java.util.Optional;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.Mockito.when;
class DefaultUserDetailServiceTest {
private DefaultUserDetailService sut;
@Mock
private UserRepository userRepository;
@BeforeEach
void setUp() {
MockitoAnnotations.initMocks(this);
sut = new DefaultUserDetailService(userRepository);
}
@Test()
void loadUserByUsernameNotFound() {
when(userRepository.findById("not-found")).thenThrow(new UsernameNotFoundException("not-found"));
Assertions.assertThrows(UsernameNotFoundException.class, () -> {
sut.loadUserByUsername("not-found");
});
}
@Test
void loadUserByUsername() {
var user = new User();
user.setUsername("normal-user");
user.setPassword("<PASSWORD>");
user.setRoles(Collections.emptySet());
when(userRepository.findById("normal-user")).thenReturn(Optional.ofNullable(user));
assertThat(sut.loadUserByUsername("normal-user").getPassword()).isEqualTo("<PASSWORD>");
}
}<file_sep>package com.github.ttwd80.homer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class HomerApplication {
public static void main(String[] args) {
SpringApplication.run(HomerApplication.class, args);
}
}
<file_sep>package com.github.ttwd80.homer.model.service;
import com.github.ttwd80.homer.model.entity.Role;
import com.github.ttwd80.homer.model.repository.UserRepository;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.stream.Collectors;
@Service
public class DefaultUserDetailService implements UserDetailsService {
private final UserRepository userRepository;
public DefaultUserDetailService(UserRepository userRepository) {
super();
this.userRepository = userRepository;
}
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
var record = userRepository.findById(username);
if (record.isEmpty()) {
throw new UsernameNotFoundException(username);
} else {
var user = record.get();
var authorities = user.getRoles().stream().map(Role::getRolename).map(SimpleGrantedAuthority::new).collect(Collectors.toList());
var userBuilder = org.springframework.security.core.userdetails.User.builder();
userBuilder.username(user.getUsername()).password(user.getPassword()).authorities(authorities);
return userBuilder.build();
}
}
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.github.ttwd80</groupId>
<artifactId>homer</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>homer</name>
<description>Demo project for Spring Boot</description>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>11</java.version>
<junit-platform.version>1.5.1</junit-platform.version>
<junit-jupiter.version>5.5.1</junit-jupiter.version>
<tomcat.version>9.0.24</tomcat.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.liquibase</groupId>
<artifactId>liquibase-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk15on</artifactId>
<version>1.62</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.4</version>
<executions>
<execution>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<execution>
<id>report</id>
<phase>prepare-package</phase>
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.eluder.coveralls</groupId>
<artifactId>coveralls-maven-plugin</artifactId>
<version>4.3.0</version>
<dependencies>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.1</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.cargo</groupId>
<artifactId>cargo-maven2-plugin</artifactId>
<version>1.7.7</version>
<configuration>
<container>
<containerId>tomcat9x</containerId>
<zipUrlInstaller>
<url>http://repo1.maven.org/maven2/org/apache/tomcat/tomcat/${tomcat.version}/tomcat-${tomcat.version}.zip</url>
</zipUrlInstaller>
</container>
<configuration>
<properties>
<cargo.tomcat.ajp.port>58009</cargo.tomcat.ajp.port>
<cargo.servlet.port>58080</cargo.servlet.port>
</properties>
</configuration>
<deployables>
<deployable>
<properties>
<context>/</context>
</properties>
<pingURL>http://localhost:58080/blank.txt</pingURL>
<pingTimeout>60000</pingTimeout>
</deployable>
</deployables>
</configuration>
<executions>
<execution>
<id>start-container</id>
<phase>pre-integration-test</phase>
<goals>
<goal>start</goal>
</goals>
</execution>
<execution>
<id>stop-container</id>
<phase>post-integration-test</phase>
<goals>
<goal>stop</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
<file_sep>spring.datasource.platform=postgres
spring.datasource.url=jdbc:postgresql://localhost/homer
spring.jpa.database=POSTGRESQL
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
spring.jpa.open-in-view=false
<file_sep>package com.github.ttwd80.homer.model.repository;
import com.github.ttwd80.homer.model.entity.Role;
import org.springframework.data.jpa.repository.JpaRepository;
public interface RoleRepository extends JpaRepository<Role, String> {
}
| b093f630c0a852fb5593499db8ca26e1001d2172 | [
"Markdown",
"Java",
"Maven POM",
"INI"
] | 8 | Markdown | ttwd80/homer | 98a3bcc2f2a7a6717f64699d758c7cf3a6398a38 | af5937b1b98f2fccb5d94246b33d6b24ba3f03f8 | |
refs/heads/master | <file_sep>using System.Net.Http;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class SecondController
{
public Task<string> Get()
{
var client = new HttpClient();
return client.GetStringAsync("http://www.google.com")
.ContinueWith(t => t.Result.Substring(0, 10));
}
}
}<file_sep>using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class FirstController
{
public Task<string> Get()
{
var client = new HttpClient();
return client.GetStringAsync("http://www.google.com");
}
}
}<file_sep>using System;
using System.Linq;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class ThirdController
{
public Task<string> Get()
{
return Db.QueryAsync("SELECT twitterId FROM ids where id = 42")
.ContinueWith(t => Client.GetTweets(t.Result))
.Unwrap()
.ContinueWith(t => t.Result.First())
.ContinueWith(e =>
{
Console.WriteLine($"Error {e}");
return "";
}, TaskContinuationOptions.OnlyOnFaulted);
}
internal class Db
{
public static Task<int> QueryAsync(string sql)
{
// return Task.Delay(0).ContinueWith(_ => 42);
throw new Exception("foo");
}
}
internal class Client
{
public static Task<string[]> GetTweets(int id)
{
return Task.Delay(0).ContinueWith(_ => new [] { "one", "two", "three"});
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Messaging;
using System.Threading.Tasks;
namespace TpgAsyncExercises
{
// do not edit this file
public class TimedInt
{
public DateTime RetrieveDate { get; }
public int Value { get; }
public TimedInt(DateTime retrieveDate, int value)
{
RetrieveDate = retrieveDate;
Value = value;
}
}
public class Randomizer
{
public static readonly Random Random = new Random();
private bool _finished = false;
public Task<TimedInt> Get(int input)
{
if (_finished)
Debug.Assert(false, $"It took too much time to start the Get call for {input}");
var delay = Random.Next(500, 3000);
return Task.Delay(delay).ContinueWith(_ =>
{
_finished = true;
return new TimedInt(DateTime.Now, input);
});
}
public Task<int> GetAndAdd(int root, int addendum)
{
var delay = Random.Next(500, 3000);
return Task.Delay(delay).ContinueWith(_ => root + addendum);
}
public WaitableItem GetWaitable(string input)
{
var item = new WaitableItem(input) ;
var delay = Random.Next(2, 800);
Task.Delay(delay).ContinueWith(_ => { item.Completed = true; });
return item;
}
}
public class TimedQueue
{
private readonly List<TimedInt> _list = new List<TimedInt>();
public void Enqueue(TimedInt input)
{
var retrieveDate = input.RetrieveDate;
if (_list.Any())
{
if (!IsValidSpan(retrieveDate) && !IsValidSpan(_list.Last().RetrieveDate))
{
throw new ArgumentException($"You took too long to queue '{input.Value}'");
}
if (_list.Last().Value > input.Value)
{
throw new ArgumentException($"'{input.Value}' is enqueued out of order");
}
}
_list.Add(input);
}
public int Count => _list.Count();
private static bool IsValidSpan(DateTime retrieveDate)
{
return retrieveDate.AddMilliseconds(100) > DateTime.Now;
}
}
}<file_sep>#pragma warning disable 219
using System;
using System.Diagnostics;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class SecondControllerAwaitMachine
{
public Task<string> Get()
{
var stateMachine = new InternalMachine();
stateMachine._controller = this;
stateMachine._builder = AsyncTaskMethodBuilder<string>.Create();
stateMachine._state = -1;
stateMachine._builder.Start<SecondControllerAwaitMachine.InternalMachine>(ref stateMachine);
return stateMachine._builder.Task;
}
public SecondControllerAwaitMachine()
{
// base.\u002Ector();
}
[CompilerGenerated]
private sealed class InternalMachine : IAsyncStateMachine
{
public int _state;
public AsyncTaskMethodBuilder<string> _builder;
public SecondControllerAwaitMachine _controller;
private HttpClient _client;
private string _html;
private string _htmlResult;
private TaskAwaiter<string> _awaiter;
public InternalMachine()
{
// base.\u002Ector();
}
void IAsyncStateMachine.MoveNext()
{
int num1 = this._state;
string result;
try
{
TaskAwaiter<string> awaiter;
int num2;
if (num1 != 0)
{
this._client = new HttpClient();
awaiter = this._client.GetStringAsync("http://www.google.com").GetAwaiter();
if (!awaiter.IsCompleted)
{
this._state = num2 = 0;
this._awaiter = awaiter;
SecondControllerAwaitMachine.InternalMachine stateMachine = this;
this._builder
.AwaitUnsafeOnCompleted<TaskAwaiter<string>,
SecondControllerAwaitMachine.InternalMachine>(
ref awaiter, ref stateMachine);
return;
}
}
else
{
awaiter = this._awaiter;
this._awaiter = new TaskAwaiter<string>();
this._state = num2 = -1;
}
this._htmlResult = awaiter.GetResult();
this._html = this._htmlResult;
this._htmlResult = (string) null;
result = this._html.Substring(0, 10);
}
catch (Exception ex)
{
this._state = -2;
this._builder.SetException(ex);
return;
}
this._state = -2;
this._builder.SetResult(result);
}
void IAsyncStateMachine.SetStateMachine(IAsyncStateMachine stateMachine)
{
}
}
}
}<file_sep>using System;
namespace SimpleWebServer.cli
{
class Program
{
static void Main(string[] args)
{
// ReSharper disable once ConditionIsAlwaysTrueOrFalse
while (Console.ReadKey() != null)
{
var controller = new StringController();
var task = controller.Get();
task.ContinueWith(t => Console.WriteLine(t.Result));
Console.WriteLine("after continue");
}
}
}
}
<file_sep>using System.Net.Http;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class SecondControllerAwait
{
public async Task<string> Get()
{
var client = new HttpClient();
var s = await client.GetStringAsync("http://www.google.com");
return s.Substring(0, 10);
}
}
}<file_sep>using System;
using System.Net.Http;
namespace SimpleWebServer.cli
{
public class SynchronousWithResult
{
public string Get()
{
// BAD BAD BAD
var client = new HttpClient();
var html = client.GetStringAsync("http://www.google.com").Result;
Console.WriteLine("This will run *after* the google call");
return html;
}
}
}<file_sep>namespace TpgAsyncExercises
{
// you can edit this file
public class WaitableItem
{
public bool Completed { get; set; }
public WaitableItem(string value)
{
}
}
}<file_sep>using System.Linq;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class FourthController
{
public async Task<string> Get()
{
var twitterId = await Db.QueryAsync("SELECT twitterId FROM ids where id = 42");
var tweets = await Client.GetTweets(twitterId);
return tweets.First();
}
internal class Db
{
public static Task<int> QueryAsync(string sql)
{
return Task.Delay(0).ContinueWith(_ => 42);
}
}
internal class Client
{
public static Task<string[]> GetTweets(int id)
{
return Task.Delay(0).ContinueWith(_ => new [] { "one", "two", "three"});
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
namespace TpgAsyncExercises
{
internal class Program
{
public static async Task Main(string[] args)
{
// await Exercise1A();
// Exercise2();
// Exercise3("hello");
Console.ReadKey();
}
// rewrite this method to correctly use async/await
public static Task<int> Exercise1(int input)
{
var r = new Randomizer();
return r.GetAndAdd(input, 5)
.ContinueWith(t => t.Result + 1)
.ContinueWith(t => r.GetAndAdd(t.Result, 2)).Unwrap();
}
public static async Task Exercise1A()
{
var result = await Exercise1(3);
Debug.Assert(result == 11, $"result should be 11");
Console.WriteLine("Success");
}
// Call r.Get for each item in the input array.
// Each call will take a random amount of time (imagine it's a web service call)
// All r.Get calls must be started as quickly as possible
// DO NOT wait until one call returns before starting the next
// The results from r.Get should be enqueued as quickly as
// possible but *must* be enqueued in input order
// IN other words, when "2" arrives, if "1" has not yet
// arrived then wait for it, otherwise enqueue "2" immediately.
#if FALSE
public static async Task Exercise2()
{
var input = new[] {1, 2, 3, 4};
var r = new Randomizer();
var queue = new TimedQueue();
// call r.Get on all input items
// enqueue them as quickly as possible, but in order
Debug.Assert(queue.Count == 4, "not all values are enqueued");
Console.WriteLine("success!");
}
#endif
#if FALSE
// Edit *only* the WaitableItem file to make this code compile
// and run correctly. You should not need to edit
// Exercise3 itself nor should you need to edit the Randomizer
public static async Task Exercise3(string input)
{
var r = new Randomizer();
var result = await r.GetWaitable(input);
Debug.Assert(result == "hello", $"{result} is not 'Hello'");
Console.WriteLine("Success");
}
#endif
}
}<file_sep>using System;
using System.Net.Http;
using System.Reflection.PortableExecutable;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class StringController
{
public Task<string> Get()
{
// return await "http://www.google.com";
return null;
}
}
}<file_sep>using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class SimpleAsyncController
{
public Task<string> Get()
{
return Task.FromResult("hello");
}
}
}<file_sep>using System.Threading.Tasks;
namespace SimpleWebServer.cli
{
public class SimpleSimpleAsyncController
{
public async Task<string> Get()
{
return "hello";
}
}
} | c741435b2f89b2b1b1810cdfa2d3c852c84fb3db | [
"C#"
] | 14 | C# | davidfostersd/tpgasync | ec72ac7f86d4afe5c0dfbef1611d90c6abc7e78e | 15964f55ad98fa6245cf570f667a034f5194820d | |
refs/heads/master | <file_sep>using System;
using Android.App;
using Android.Content.PM;
using Android.OS;
using Microsoft.Practices.Unity;
using Prism.Unity;
using Android.Preferences;
using Android.Content;
namespace VoiceRecognitionSample.Droid
{
[Activity(Label = "VoiceRecognitionSample.Droid", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
public event EventHandler<PreferenceManager.ActivityResultEventArgs> ActivityResult = delegate {};
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App(new AndroidInitializer()));
}
protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
var resultEventArgs = new PreferenceManager.ActivityResultEventArgs(true, requestCode, resultCode, data);
ActivityResult(this, resultEventArgs);
}
}
public class AndroidInitializer : IPlatformInitializer
{
public void RegisterTypes(IUnityContainer container)
{
}
}
}
<file_sep># VoiceRecognitionSample
Prism for Xamarin.Forms(Prism.Forms)で作成した、音声認識のサンプルアプリです。
## 対応プラットフォーム
- iOS(バージョン10.0以上)
- Android
## 機能
音声を認識し、画面上に認識結果の文章を表示します。
## 画面ショット
#### 音声認識実行前
|iOS|Android|
|---|---|
|||
開始ボタンを押下した後に音声を吹き込むと、その音声の認識結果が画面上に表示されます。
#### 音声認識実行後
認識結果は開始/停止ボタンの真上に表示されます。
|iOS|Android|
|---|---|
|||
## 注意・免責
- どちらのプラットフォームでも、音声認識を使用する際はインターネットへの接続が必須です。
- [iOSの場合、端末ごと・アプリごとの音声認識処理の使用回数等の制限があります。](http://qiita.com/nerd0geek1/items/af9f0555c3f6c8d878eb)
- 本アプリの利用は自己責任でお願いします。
<file_sep>using System;
using AVFoundation;
using Foundation;
using Prism.Mvvm;
using Speech;
using VoiceRecognitionSample.Models.iOS;
using Xamarin.Forms;
[assembly: Dependency(typeof(VoiceRecognitionService))]
namespace VoiceRecognitionSample.Models.iOS
{
/// <summary>
/// 音声認識用サービス
/// プロパティの変更をバインドで捉えられるようにするため、BindableBaseを継承する。
/// </summary>
public class VoiceRecognitionService : BindableBase, IVoiceRecognitionService
{
#region Properties
/// <summary>
/// 音声認識の実行状況(実行中の間のみtrueを返す)
/// </summary>
private bool _isRecognizing;
public bool IsRecognizing
{
get { return _isRecognizing; }
set { SetProperty(ref _isRecognizing, value); }
}
/// <summary>
/// 音声認識の結果テキスト
/// </summary>
private string _recognizedText;
public string RecognizedText
{
get
{
if (_recognizedText != null)
return _recognizedText;
else
return string.Empty;
}
set { SetProperty(ref _recognizedText, value); }
}
#endregion
#region Variables
/// 音声認識に必要な諸々のクラスのインスタンス
private AVAudioEngine audioEngine;
private SFSpeechRecognizer speechRecognizer;
private SFSpeechAudioBufferRecognitionRequest recognitionRequest;
private SFSpeechRecognitionTask recognitionTask;
#endregion
#region Public Methods
/// <summary>
/// 音声認識の開始処理
/// </summary>
public void StartRecognizing()
{
RecognizedText = string.Empty;
IsRecognizing = true;
// 音声認識の許可をユーザーに求める。
SFSpeechRecognizer.RequestAuthorization((SFSpeechRecognizerAuthorizationStatus status) =>
{
switch (status)
{
case SFSpeechRecognizerAuthorizationStatus.Authorized:
// 音声認識がユーザーに許可された場合、必要なインスタンスを生成した後に音声認識の本処理を実行する。
// SFSpeechRecognizerのインスタンス生成時、コンストラクタの引数でlocaleを指定しなくても、
// 端末の標準言語が日本語なら日本語は問題なく認識される。
audioEngine = new AVAudioEngine();
speechRecognizer = new SFSpeechRecognizer();
recognitionRequest = new SFSpeechAudioBufferRecognitionRequest();
startRecognitionSession();
break;
default:
// 音声認識がユーザーに許可されなかった場合、処理を終了する。
return;
}
}
);
}
/// <summary>
/// 音声認識の停止処理
/// </summary>
public void StopRecognizing()
{
try
{
audioEngine?.Stop();
recognitionTask?.Cancel();
recognitionRequest?.EndAudio();
IsRecognizing = false;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
#endregion
#region Private Methods
/// <summary>
/// 音声認識の本処理
/// </summary>
private void startRecognitionSession()
{
// 音声認識のパラメータ設定と認識開始。ここのパラメータはおまじない。
audioEngine.InputNode.InstallTapOnBus(
bus: 0,
bufferSize: 1024,
format: audioEngine.InputNode.GetBusOutputFormat(0),
tapBlock: (buffer, when) => { recognitionRequest?.Append(buffer); }
);
audioEngine?.Prepare();
NSError error = null;
audioEngine?.StartAndReturnError(out error);
if (error != null)
{
Console.WriteLine(error);
return;
}
try
{
if (recognitionTask?.State == SFSpeechRecognitionTaskState.Running)
{
// 音声認識が実行中に音声認識開始処理が呼び出された場合、実行中だった音声認識を中断する。
recognitionTask.Cancel();
}
recognitionTask = speechRecognizer.GetRecognitionTask(recognitionRequest,
(SFSpeechRecognitionResult result, NSError err) =>
{
if (result == null)
{
// iOS Simulator等、端末が音声認識に対応していない場合はここに入る。
StopRecognizing();
return;
}
if (err != null)
{
Console.WriteLine(err);
StopRecognizing();
return;
}
if ((result.BestTranscription != null) && (result.BestTranscription.FormattedString != null))
{
// 音声を認識できた場合、認識結果を更新する。
RecognizedText = result.BestTranscription.FormattedString;
}
if (result.Final)
{
// 音声が認識されなくなって時間が経ったら音声認識を打ち切る。
StopRecognizing();
return;
}
}
);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
#endregion
}
}
<file_sep>using System.ComponentModel;
using System.Windows.Input;
using Prism.Commands;
using Prism.Mvvm;
using Prism.Navigation;
using VoiceRecognitionSample.Models;
namespace VoiceRecognitionSample.ViewModels
{
/// <summary>
/// MainPage.xamlに対応するViewModel
/// </summary>
public class MainPageViewModel : BindableBase, INavigationAware
{
#region Constants
/// <summary>
/// 音声認識の開始・停止ボタンのテキスト
/// </summary>
private const string BUTTON_TEXT_START = "開始";
private const string BUTTON_TEXT_STOP = "停止";
#endregion
#region Properties, Variables
/// <summary>
/// 音声認識の結果テキスト
/// </summary>
private string _recognizedText = string.Empty;
public string RecognizedText
{
get { return _recognizedText; }
protected set { SetProperty(ref _recognizedText, value); }
}
/// <summary>
/// 音声認識の開始・停止ボタンの表記
/// </summary>
private string _voiceRecognitionButtonText = BUTTON_TEXT_START;
public string VoiceRecognitionButtonText
{
get { return _voiceRecognitionButtonText; }
protected set { SetProperty(ref _voiceRecognitionButtonText, value); }
}
/// <summary>
/// 音声認識を実行中かどうか(trueなら実行中)
/// </summary>
private bool _isRecognizing;
public bool IsRecognizing
{
get { return _isRecognizing; }
protected set
{
// 音声認識が実行中の場合、音声認識ボタンのテキストを「停止」に変更する。
// 音声認識が停止している場合は「開始」に変更する。
VoiceRecognitionButtonText = value ? BUTTON_TEXT_STOP : BUTTON_TEXT_START;
SetProperty(ref _isRecognizing, value);
}
}
/// <summary>
/// 音声認識サービス
/// </summary>
private readonly IVoiceRecognitionService _voiceRecognitionService;
/// <summary>
/// 音声認識サービスの処理の呼び出し用コマンド
/// </summary>
public ICommand VoiceRecognitionCommand { get; }
#endregion
#region Constructor
/// <summary>
/// コンストラクタ
/// </summary>
public MainPageViewModel(IVoiceRecognitionService voiceRecognitionService)
{
_voiceRecognitionService = voiceRecognitionService;
// 音声認識サービスのプロパティが変更されたときに実行する処理を設定する。
_voiceRecognitionService.PropertyChanged += voiceRecognitionServicePropertyChanged;
// 音声認識サービスの処理本体をコマンドに紐付ける。
VoiceRecognitionCommand = new DelegateCommand(executeVoiceRecognition);
}
#endregion
#region Event of NavigationAware
public void OnNavigatedFrom(NavigationParameters parameters)
{
}
public void OnNavigatedTo(NavigationParameters parameters)
{
}
public void OnNavigatingTo(NavigationParameters parameters)
{
}
#endregion
#region Private Methods
/// <summary>
/// 音声認識サービスのプロパティ変更時にトリガーされるイベントの実処理
/// </summary>
/// <param name="sender">Sender</param>
/// <param name="args">Arguments</param>
private void voiceRecognitionServicePropertyChanged(object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "RecognizedText")
{
// 音声の認識結果テキストの変更がトリガーになった場合、そのテキストをViewModelに取得する。
RecognizedText = _voiceRecognitionService.RecognizedText;
}
if (args.PropertyName == "IsRecognizing")
{
// 音声認識の実行状況変更がトリガーになった場合、その実行状況をViewModelに取得する。
IsRecognizing = _voiceRecognitionService.IsRecognizing;
}
}
/// <summary>
/// 音声認識サービス呼び出し用ボタンのコマンドの実処理
/// </summary>
private void executeVoiceRecognition()
{
if (IsRecognizing)
{
// 音声認識を実行中の場合、「停止」ボタンとして機能させる。
_voiceRecognitionService.StopRecognizing();
}
else
{
// 音声認識が停止中の場合、「開始」ボタンとして機能させる。
_voiceRecognitionService.StartRecognizing();
}
}
#endregion
}
}
| 461592a4d6fa5e76086e8ea5967815ed619884ac | [
"Markdown",
"C#"
] | 4 | C# | kssyamagata/VoiceRecognitionSample | a2af17ab717531f20b435d8b749df6c67c406382 | ad94f834c3115572519d466f66672025278d653f | |
refs/heads/master | <repo_name>kfrn/Check-Sammy<file_sep>/CheckSammy.py
#!/usr/bin/env python3.6
'''
Check Sammy is a GUI tool for checksumming stuff (using the md5 algorithm).
It stores the hash values in separate json files (SomePath/InputFileName.md5).
The same files can be used for running integrity checks. In this case Sammy will look
for the json in whatever new path the file has been moved to (SomeOtherPath/InputFileName.md5).
Sammy was born at the Austrian Film Museum in 2019.
"Hoog Sammy, kijk omhoog Sammy
Anders is het vast te laat"
'''
from tkinter import *
from tkinter import filedialog
import multiprocessing.dummy as mp
import tkinter as tk
import os
import hashlib
import json
import threading
import datetime
import shutil
class SammyGUI(tk.Tk):
# In this class all the widgets and methods of the GUI.
def __init__(self):
super().__init__()
self.checksummer = CheckSammy()
self.version = '0.7.4'
self.title('Check Sammy %s' % self.version)
if os.name == 'nt':
self.iconbitmap(os.path.abspath('./media/paw.ico'))
self.resizable(False,False)
self.check_this = {'F': [], 'D': []}
self.checked = {'Ok': [], 'Corrupted': [],
'No md5': [], 'Missing file': [], 'New file': []}
self.button_frame = tk.Frame(self)
self.button_frame.grid(row=1, column=0, pady=5, padx=5)
self.recursive_button = tk.Button(
self.button_frame, text=' All in one folder ', command=self.add_all_in_directory)
self.recursive_button.grid(
row=1, column=0, sticky='N', padx=2, pady=10)
self.folder_button = tk.Button(
self.button_frame, text='Single folder', command=self.add_directory)
self.folder_button.grid(row=2, column=0, sticky='N', padx=2, pady=2)
self.file_button = tk.Button(
self.button_frame, text='Single file', command=self.add_file)
self.file_button.grid(row=3, column=0, sticky='N', pady=2)
self.start_button = tk.Button(self.button_frame, text='Start', command=lambda: threading.Thread(
target=self.start, args=()).start())
self.start_button.grid(row=5, sticky='N', pady=2)
self.status_label = tk.Label(self.button_frame, text='Ready')
self.status_label.grid(row=6, sticky='N', pady=20)
self.sammy = tk.PhotoImage(file='media/dog.png')
self.sammy_frame = tk.Frame(self.button_frame)
self.sammy_frame.grid(row=4, column=0)
self.sammy_label = tk.Label(self.sammy_frame, image=self.sammy)
self.sammy_label.grid(pady=10)
self.batch_frame = tk.Frame(self, width=1700)
self.batch_frame.grid(row=0, column=1, rowspan=2)
self.batch_yscrollbar = tk.Scrollbar(
self.batch_frame, orient='vertical')
self.batch_yscrollbar.grid(row=1, column=3, rowspan=2, sticky='NS')
self.batch_xscrollbar = tk.Scrollbar(
self.batch_frame, orient='horizontal')
self.batch_xscrollbar.grid(row=2, column=0, columnspan=3, sticky='WE')
self.batch_label = tk.Label(
self.batch_frame, text='Queue (0)', borderwidth=4, relief='groove', width=100)
self.batch_label.grid(row=0, column=2, sticky='W', pady=5)
self.batch_remove_button = tk.Button(
self.batch_frame, text='Remove', command=self.remove_item)
self.batch_remove_button.grid(row=0, column=0, sticky='W', pady=5, padx=10)
self.batch_tranfer_button = tk.Button(
self.batch_frame, text='Safe transfer', command=self.open_safe_transfer)
self.batch_tranfer_button.grid(row=0, column=1, sticky='W', pady=5, padx=10)
self.batch_listbox = tk.Listbox(self.batch_frame, yscrollcommand=self.batch_yscrollbar.set,
xscrollcommand=self.batch_xscrollbar.set, width=180, height=23)
self.batch_listbox.configure(activestyle='none', highlightthickness=0)
self.batch_yscrollbar.configure(command=self.batch_listbox.yview)
self.batch_xscrollbar.configure(command=self.batch_listbox.xview)
self.batch_listbox.grid(row=1, column=0, columnspan=3)
self.batch_frame.bind(
'<Leave>', lambda x: self.batch_listbox.selection_clear(0, END))
self.control_frame = tk.Frame(self)
self.control_frame.grid(row=0, column=0)
self.reset_button = tk.Button(
self.control_frame, text='Reset', command=self.reset)
self.reset_button.grid(sticky='N', pady=10)
self.operation_type = IntVar()
self.calculate = tk.Radiobutton(self.control_frame, text='Calculate md5', variable=self.operation_type,
value=1, tristatevalue=4, command=lambda: self.status_label.configure(text='Ready'))
self.calculate.grid(row=1, column=0, sticky='w')
self.difference = tk.Radiobutton(self.control_frame, text='Check difference', variable=self.operation_type,
value=2, tristatevalue=4, command=lambda: self.status_label.configure(text='Ready'))
self.difference.grid(row=2, column=0, sticky='w')
self.difference.grid(row=3, column=0, sticky='w')
self.operation_type.set(1)
def open_safe_transfer(self):
x = self.winfo_x()
y = self.winfo_y()
self.transfer_window = tk.Toplevel()
self.transfer_window.grab_set()
self.transfer_window.title('Safe Transfer')
if os.name == 'nt':
self.transfer_window.iconbitmap(os.path.abspath('./media/paw.ico'))
self.transfer_window.geometry(f'650x160+{x+145}+{y+80}')
self.transfer_window.resizable(False, False)
self.transfer_dst_button = tk.Button(self.transfer_window, text='Select target folder:',command=self.select_target_directory)
self.transfer_dst_button.place(x=250,y=20,width=150)
self.transfer_dst_entry = tk.Entry(self.transfer_window,state=DISABLED,width=100)
self.transfer_dst_entry.place(x=15,y=70,width=620)
self.transfer_start_button = tk.Button(self.transfer_window, text='Start transfer',command=lambda: threading.Thread(
target=self.safe_transfer, args=()).start())
self.transfer_start_button.place(x=275,y=110,width=100)
def select_target_directory(self):
dst = filedialog.askdirectory()
self.transfer_dst_entry.configure(state=NORMAL)
self.transfer_dst_entry.insert(0,dst)
self.transfer_dst_entry.configure(state=DISABLED)
def remove_item(self):
# Deletes the selected item from the batch listbox.
try:
item_text = self.batch_listbox.get(
self.batch_listbox.curselection())
if item_text[2] == 'F':
self.check_this['F'].remove(item_text.split('"')[1])
elif item_text[2] == 'D':
self.check_this['D'].remove(item_text.split('"')[1])
self.batch_listbox.delete(self.batch_listbox.curselection())
self.batch_label.configure(
text='Queue (%s)' % str(self.batch_listbox.size()))
except:
pass
def add_file(self):
# Opens filedialog window for selecting files to add to the batch.
files = filedialog.askopenfilenames()
for file in files:
if not os.path.abspath(file) in self.check_this['F'] and file != '':
self.check_this['F'].append(os.path.abspath(file))
self.update_batch()
def add_directory(self):
# Opens filedialog window for selecting a folder to add to the batch.
# All the files in the folder (and recursively in the subfolders) will
# be checksummed individually.
dir = filedialog.askdirectory()
if not dir in self.check_this['D']:
if dir != '':
self.check_this['D'].append(os.path.abspath(dir))
self.update_batch()
def add_all_in_directory(self):
# Opens filedialog window for selecting a folder.
# Every file and/or folder inside the chosen directory will be added
# to the batch.
dir = filedialog.askdirectory()
if dir != '':
root, dirs, files = next(os.walk(dir))
for d in dirs:
self.check_this['D'].append(
os.path.abspath(self.checksummer.join_path(root, d)))
for f in files:
if not '.md5' in f:
self.check_this['F'].append(
os.path.abspath(self.checksummer.join_path(root, f)))
self.update_batch()
def update_batch(self):
# Updates the batch listbox.
self.batch_listbox.delete(0, END)
for file in self.check_this['F']:
self.batch_listbox.insert(END, ' -F - "%s"' % file)
for folder in self.check_this['D']:
self.batch_listbox.insert(END, ' -D - "%s"' % folder)
self.status_label.configure(text='Ready')
self.batch_label.configure(text='Queue (%s)' %
str(self.batch_listbox.size()))
def report(self,transfer=False):
# Generates the report of the fixity check.
ok_count = len(self.checked['Ok'])
corrupted_count = len(self.checked['Corrupted'])
no_checksum_count = len(self.checked['No md5'])
missing_count = len(self.checked['Missing file'])
new_file_count = len(self.checked['New file'])
total_count = ok_count + corrupted_count + no_checksum_count + missing_count + new_file_count
self.report_window = tk.Toplevel(self)
if os.name == 'nt':
self.report_window.iconbitmap(os.path.abspath('./media/paw.ico'))
self.report_window.title('Report')
self.report_yscrollbar = tk.Scrollbar(
self.report_window, orient='vertical')
self.report_yscrollbar.grid(row=0, column=1, sticky='NS')
self.report_text = tk.Text(self.report_window, width=100, height=30,
yscrollcommand=self.report_yscrollbar.set, state=DISABLED, wrap=WORD)
self.report_text.grid(row=0, column=0)
self.report_yscrollbar.configure(command=self.report_text.yview)
self.report_button = tk.Button(
self.report_window, text='Save report', command=self.save_report)
self.report_button.grid(row=1, column=0, pady=5)
self.report_text.configure(state=NORMAL)
self.report_text.delete(1.0, END)
operation = 'checked' if transfer == False else 'transferred'
self.report_text.insert(END, 'Fixity check summary:\n\n---\n%s files/folders %s.\n---\n\nOk: %s.\nCorrupted: %s.\nMissing: %s.\nNew/Unknown: %s.\n---\n\n' %
(str(total_count), operation, str(ok_count), str(corrupted_count), str(missing_count), str(new_file_count)))
if no_checksum_count > 0:
self.report_text.insert(
END, "Sammy couldn't find a valid .md5 for %s files/folders.\n------------\n\n\n" % str(no_checksum_count))
else:
self.report_text.insert(
END, 'All the .md5 were found.\n------------\n\n\n')
if corrupted_count > 0:
self.report_text.insert(
END, 'The following files/folders are corrupted:\n\n')
for obj in self.checked['Corrupted']:
self.report_text.insert(END, "'" + obj + "'\n")
self.report_text.insert(END, '---\n\n\n')
if missing_count > 0:
self.report_text.insert(
END, 'The following files/folders are missing:\n\n')
for obj in self.checked['Missing file']:
self.report_text.insert(END, "'" + obj + "'\n")
self.report_text.insert(END, '---\n\n\n')
if new_file_count > 0:
self.report_text.insert(
END, 'The following files/folders are new/unknown:\n\n')
for obj in self.checked['New file']:
self.report_text.insert(END, "'" + obj + "'\n")
self.report_text.insert(END, '---\n\n\n')
if no_checksum_count > 0:
self.report_text.insert(
END, 'The following .md5 files are missing:\n\n')
for obj in self.checked['No md5']:
self.report_text.insert(END, "'" + obj + "'\n")
self.report_text.insert(END, '---\n\n\n')
if ok_count > 0:
self.report_text.insert(
END, 'The following files/folders are ok:\n\n')
for obj in self.checked['Ok']:
self.report_text.insert(END, "'" + obj + "'\n")
self.report_text.insert(END, '---\n\n\n')
self.report_text.insert(END, 'Report generated by \'Check Sammy %s\' on %s' % (
self.version, str(datetime.date.today())))
self.report_text.configure(state=DISABLED)
self.status_label.configure(text='Ready')
self.checked = {'Ok': [], 'Corrupted': [],
'No md5': [], 'Missing file': [], 'New file': []}
def save_report(self):
# Stores report in a .txt file.
try:
with open(filedialog.asksaveasfilename(defaultextension='.txt', filetypes=(('Text file', '*.txt'), ('All files', '*.*'))), 'w+', encoding='utf8') as dot_txt:
dot_txt.write(self.report_text.get(1.0, END))
except FileNotFoundError:
pass
def reset(self):
# Empties the batch
self.check_this = {'F': [], 'D': []}
self.checked = {'Ok': [], 'Corrupted': [],
'No md5': [], 'Missing file': [], 'New file': []}
self.batch_listbox.delete(0, END)
self.update_batch()
self.status_label.configure(text='Ready')
def start(self):
# This method starts the selected operation (either create checksums or
# check their difference) for all of the files/folders in the batch listbox.
if self.check_this == {'F': [], 'D': []}:
self.status_label.configure(text='Batch empty')
else:
if self.operation_type.get() == 1:
self.create_md5()
elif self.operation_type.get() == 2:
self.compare_checksums()
else:
self.status_label.configure(text="Sammy's confused...")
def create_md5(self,transfer=False,dst=None):
self.status_label.configure(text='Working...')
before = datetime.datetime.now()
workers = mp.Pool(8)
if transfer == False:
workers.map(self.checksummer.save_md5, self.check_this['F'])
else:
args = []
for file in self.check_this['F']:
args.append((file,dst))
workers.starmap(self.checksummer.transfer_save_md5, args)
for dir in self.check_this['D']:
self.hash_dict = {}
self.hash_dict['PARENT FOLDER'] = os.path.basename(dir)
for root, folders, files in os.walk(dir):
a = []
for file in files:
to_hash = self.checksummer.join_path(root, file)
a.append((dir, to_hash))
workers.starmap(self.checksummer.get_hash_dict, a)
js = json.dumps(self.hash_dict, indent=4)
if transfer == False:
with open(dir + '.md5', 'w+') as dot_md5:
dot_md5.write(js)
else:
path = self.checksummer.join_path(dst,dir.split(os.sep)[-1])
with open(path + '.md5', 'w+') as dot_md5:
dot_md5.write(js)
workers.close()
workers.join()
print('Finished after: ' + str(datetime.datetime.now() - before))
self.status_label.configure(text='Done')
def compare_checksums(self, transfer=False, check_transferred=None):
self.status_label.configure(text='Working...')
to_check = self.check_this if transfer == False else check_transferred
workers = mp.Pool(8)
workers.map(self.checksummer.check_md5, to_check['F'])
a = []
for dir in to_check['D']:
a.append((dir, 1))
workers.starmap(self.checksummer.check_md5, a)
workers.close()
workers.join()
self.report(transfer)
self.status_label.configure(text='Done')
def safe_transfer(self):
if self.transfer_dst_entry.get() != '':
dst = self.transfer_dst_entry.get()
self.transfer_window.destroy()
try:
if self.check_this == {'F': [], 'D': []}:
self.status_label.configure(text='Batch empty')
else:
check_transferred = {'F': [], 'D': []}
print('Calculating checksums...')
self.create_md5(True,dst)
print('Done\n')
print('Transferring files...')
for file in self.check_this['F']:
new_copy = self.checksummer.join_path(dst,file.split(os.sep)[-1])
if not os.path.isfile(self.checksummer.join_path(dst,file.split(os.sep)[-1])):
shutil.copy(file,dst)
else:
raise FileExistsError
check_transferred['F'].append(new_copy)
print('Done\n')
print('Transferring folders...')
for dir in self.check_this['D']:
new_copy = self.checksummer.join_path(dst,dir.split(os.sep)[-1])
shutil.copytree(dir,new_copy)
check_transferred['D'].append(new_copy)
print('Done\n')
print('Comparing difference...')
self.compare_checksums(True,check_transferred)
print('Done')
print('----------')
except FileExistsError:
print('The destination directory is not empty')
class CheckSammy():
# This class is the actual 'checksum' handler.
def join_path(self,a,b):
return a + '/' + b
def calculate_md5(self, file):
# Calculates the md5 for the selected file.
h = hashlib.md5()
with open(file, 'rb') as file_data:
for chunk in iter(lambda: file_data.read(4096), b''):
h.update(chunk)
return(h.hexdigest())
def check_md5(self, path, switch=0):
# Calculates a new checksum and compares it with the one stored in the json.
target_name = os.path.basename(path) # File or directory
if switch == 0:
try:
previous_checksum = json.load(open(path + '.md5'))[target_name]
new_checksum = self.calculate_md5(path)
if previous_checksum == new_checksum:
puppy.checked['Ok'].append(target_name)
else:
puppy.checked['Corrupted'].append(target_name)
except FileNotFoundError:
puppy.checked['No md5'].append(target_name + '.md5')
elif switch == 1:
new_dict = {'PARENT FOLDER': target_name}
try:
previous_dict = json.load(open(path + '.md5'))
for root, folders, files in os.walk(path):
for file in files:
to_hash = self.join_path(root, file)
new_dict[to_hash.replace(
path, '')[1:]] = self.calculate_md5(to_hash)
for obj in previous_dict:
if not obj in new_dict:
puppy.checked['Missing file'].append(
self.join_path(new_dict['PARENT FOLDER'], obj))
for obj in new_dict:
if not obj in previous_dict:
puppy.checked['New file'].append(
self.join_path(new_dict['PARENT FOLDER'], obj))
else:
if new_dict[obj] == previous_dict[obj]:
if obj != 'PARENT FOLDER':
puppy.checked['Ok'].append(self.join_path(
new_dict['PARENT FOLDER'], obj))
else:
puppy.checked['Corrupted'].append(
self.join_path(new_dict['PARENT FOLDER'], obj))
except FileNotFoundError:
puppy.checked['No md5'].append(new_dict['PARENT FOLDER'] + '.md5')
def save_md5(self, file):
# Starts the calculate_md5 method and stores the results in a dictionary.
# Then dumps the dictionary into a json file.
checksum_data = {os.path.basename(file): self.calculate_md5(file)}
js = json.dumps(checksum_data, indent=4)
with open(file + '.md5', 'w+') as file_data:
file_data.write(js)
def transfer_save_md5(self, file, dst):
# Starts the calculate_md5 method and stores the results in a dictionary.
# Then dumps the dictionary into a json file in the dst folder.
checksum_data = {os.path.basename(file): self.calculate_md5(file)}
js = json.dumps(checksum_data, indent=4)
path = self.join_path(dst,file.split(os.sep)[-1])
with open(path + '.md5', 'w+') as file_data:
file_data.write(js)
def get_hash_dict(self, dir, to_hash):
# Starts the calculate_md5 method and stores the results in a dictionary.
puppy.hash_dict[to_hash.replace(dir, '')[1:].replace(os.sep,'/')] = self.calculate_md5(to_hash)
puppy = SammyGUI()
puppy.mainloop()
<file_sep>/README.md
# Check-Sammy
Python GUI for calculating and monitoring md5 checksums
## Dependencies
* [Python 3.6](https://www.python.org/downloads/)
## Local setup
```bash
git clone <EMAIL>:cs-afm/Check-Sammy.git
cd Check-Sammy/
python3 CheckSammy.py
```
| 3deed18347df926d0b267a31fa10b8344c65138a | [
"Markdown",
"Python"
] | 2 | Python | kfrn/Check-Sammy | 3a2e7dd241c77d3131a8b38b0d14269872b1bf85 | 2026d7934bc0f88fe14ec5eb904ef38a6a89bffe | |
refs/heads/master | <repo_name>PedroHurtado/httpapi<file_sep>/src/services/userservice.js
import userprovider from '../providers/userprovider'
export class UserService{
constructor(userprovider){
this._userprovider = userprovider;
}
async refreshToken(refresh_token){
//TODO:refresh token
//await this._userprovider.add()
}
}
export default new UserService(userprovider);<file_sep>/src/providers/cacheprovider.js
const key = "api"
//TODO:cachestrategies
export class CacheProviders {
constructor(key,cacheProvider){
this._key = key;
this._cacheProvider = cacheProvider;
this._cache = null;
}
get async cache(){
if(!this._cache){
this._cache = await this._cacheProvider.open(this._key);
}
return this._cache;
}
async put(request,response){
await this.cache.put(request.clone(),response.clone());
}
async match(request){
return await this.cache.match(request);
}
}
export default new CacheProviders(key,caches)<file_sep>/src/providers/cultureprovider.js
import * idb from 'idb-keyval'
import userprovider from './userprovider'
const suportcultures = ['es','en']
const defaultculture = 'en'
const key="culture"
export class CultureProvider{
constructor(idb,userprovider,languages){
this._idb = idb;
this._userprovider=userprovider;
this._languajes = languages;
this._culture = null;
}
async add(culture){
await this._idb.set(key,culture);
this._culture = null;
}
async get culture(){
if(!this._culture){
this._culture = await this.get();
}
return this._culture;
}
_getDefaultCulture(){
for(let i=0;i<languages.length){
let language=languages[i];
if(suportcultures.includes(language)){
return language;
}
}
return defaultculture;
}
async get(){
let culture = await this._idb(key);
if(!culture){
const user = await this._userprovider.get();
if(user){
culture = user.culture;
}else{
culture = this._getDefaultCulture();
}
await this.add(culture);
}
return culture;
}
}
export default new CultureProvider(idb,userprovider,navigator.languages)<file_sep>/src/interceptors.js
import {
NotFound,
BadRequest,
Unauthorized,
ForBiden,
NotAllowed,
ServerError
} from './customerrors.js'
const OK = async (req, res) => await res.json();
const NOCONTENT = async (req,res)=>'';
const NOTFOUND = async (req, res) => {throw new NotFound(res.statusText);}
const BADREQUEST = async (req, res) => {
const data = await res.json()
throw new BadRequest(data,res.statusText)
};
const UNAUTHORIZED = async (req, res) => {throw new Unauthorized(res.statusText);}
const FORBIDEN = async (req, res) => {throw new ForBiden(res.statusText);}
const NOTALLOWED = async (req, res) => {throw new NotAllowed(res.statusText);}
const SERVERERROR = async (req, res) => {
const data = await res.json()
throw new ServerError(data,res.statusText);
};
const GLOBALERRORS = {
"400": BADREQUEST,
"401": UNAUTHORIZED,
"403": FORBIDEN,
"405": NOTALLOWED,
"500": SERVERERROR
}
export const DEFAULTINTERCEPTORS = {
"GET": {
"200" :OK,
"404": NOTFOUND,
...GLOBALERRORS
},
"POST": {
"201": OK,
...GLOBALERRORS
},
"PUT": {
"200": OK,
"204":NOCONTENT,
"404": NOTFOUND,
...GLOBALERRORS
},
"PATCH": {
"200": OK,
"204":NOCONTENT,
"404": NOTFOUND,
...GLOBALERRORS
},
"DELETE": {
"200": OK,
"204":NOCONTENT,
"404": NOTFOUND,
...GLOBALERRORS
}
}<file_sep>/src/after.js
import {validate} from './validate.js'
export default after = async (request, response, interceptors) => {
validate(request, 'request is required');
validate(response, 'response is required');
validate(interceptors, 'interceptors is required');
const { method, status } = response;
const methodinterceptors = interceptors[method];
validate(methodinterceptors, `${method} not defined in interceptors`)
const interceptor = interceptors[methodinterceptors];
validate(interceptor, `status code:${status} not defined in interceptor ${method}`)
return await interceptor(request, response)
}<file_sep>/src/customerrors.js
const Mixin = Base => class extends Base{
constructor(name,code,...params){
super(...params)
if(Error.captureStackTrace){
Error.captureStackTrace(this,NotFound)
}
this.name = name;
this.code = code;
this.date = Date.now();
}
}
export class NotFound extends Mixin(Error){
constructor(...params){
super("NotFound", 404,...params);
}
}
export class BadRequest extends Mixin(Error){
constructor(data,...params){
super("BadRequest",400,...params);
this.data = data;
}
}
export class Unauthorized extends Error{
constructor(...params){
super("Unauthorized",401,...params)
}
}
export class ForBiden extends Error{
constructor(...params){
super("ForBiden",403,...params)
}
}
export class NotAllowed extends Error{
constructor(...params){
super("NotAllowed",405,...params)
}
}
export class ServerError extends Error{
constructor(data,...params){
super("ServerError",500,...params)
this.data = data;
}
}<file_sep>/src/providers/userprovider.js
import * as idb from 'idb-keyval'
const KEY = 'USER'
export class UserProvider{
constructor(idb){
this._idb = idb;
}
async add(user){
await this._idb.set(KEY,user)
}
async get(){
return await this._idb.get(KEY)
}
async remove(){
await this._idb.del(KEY)
}
}
export default new UserProvider(idb);<file_sep>/src/ioccontainer.js
//TODO estrategies singleton,value,factory,instance,etc...
import { validate } from './validate.js'
export const singleton = function (key, ...dependecies) {
return () => { }
}
export const instance = function (key, ...dependecies) {
return () => { }
}
export const value = function (key,value) {
return () => { }
}
export const factory = function (key, ...dependecies) {
return () => { }
}
export class IocContainer {
constructor() {
this._dependencies = new Map();
this._caches = new Map();
}
set(key, strategy) {
validate(key, 'key is required');
validate(strategy, 'strategy is required');
this._dependencies.set(key, strategy.bind(this))
}
get(key) {
validate(key, 'key is required');
const strategy = this._dependencies.get(key)
if (!strategy) {
validate(`${key} dependecies is not defined`)
}
return strategy();
}
} | ab73f57e18b47387004ed1a5b115744ada32f78c | [
"JavaScript"
] | 8 | JavaScript | PedroHurtado/httpapi | a35657f4bf5e294b5783da7ec86368f5f3333dd5 | 7ffe11f362a27ab26519d662747bfdf2dae4b720 | |
refs/heads/master | <repo_name>wDiff/moshimo.com<file_sep>/js/Mdk.js
/*@cc_on
if (@_jscript_version < 9) {
var _d = document;
eval("var document = _d");
}
@*/
/**
* js/Mdk.js
*
* @author T.Mori <<EMAIL>>
* @package Mdk
* @version $Id$
*/
/**
* Mdk の既定クラス
*
* $ で始まる変数は Element を継承したオブジェクトを表現します
* $event は例外的に Event を継承したオブジェクトを表現します
*
* @author T.Mori <<EMAIL>>
* @package Mdk
* @access public
*/
var Mdk = Class.create(
{
/** @var Object <form ...> 関連のオブジェクト */
form: {
/**
* 確認ダイアログを出してからフォームを送信する
*
* @param Form $form フォーム要素 (フォームの ID も可)
* @param String message 確認メッセージ
*/
confirm: function ($form, message) {
message = message || "実行しますか?";
if (confirm(message)) {
this.submit($form);
}
},
/**
* フォームを送信する
*
* @param Form $form フォーム要素 (フォームの ID も可)
*/
submit: function ($form) {
var $form = $($form);
$form.submit();
},
/**
* Ajax なリクエストを送信する
*
* @param Form $form フォーム要素
* @param Function callback コールバックメソッド
*/
request: function ($form, callback, options) {
options = Object.extend(
{
onSuccess: function (response) {
callback(response, $form);
}
},
options || {}
);
$form = $($form);
// post じゃないと IE で重複送信が出来ない
$form.request(
options
);
},
/** @var Object <input ...> 関連のオブジェクト */
input: {
/** @var Object <input type="checkbox" ...> 関連のオブジェクト */
checkbox: {
/**
* チェックボックスを全てチェックする
*
* @param Array $elements checkbox の要素を含む配列
*/
checkAll: function ($elements) {
$elements.each(
function ($element) {
var call = false;
if (!$element.checked) {
call = true;
}
if ($element.tagName.toLowerCase() == 'input' && $element.readAttribute('type') == 'checkbox' && !$element.disabled) {
$element.checked = 1;
}
if (call) {
$element.fire('mdk:change');
}
}
);
},
/**
* チェックボックスを全てチェック解除する
*
* @param Array $elements checkbox の要素を含む配列
*/
releaseAll: function ($elements) {
if (!Object.isArray($elements)) {
return;
}
$elements.each(
function ($element) {
var call = false;
if ($element.checked) {
call = true;
}
if ($element.tagName.toLowerCase() == 'input' && $element.readAttribute('type') == 'checkbox') {
$element.checked = 0;
}
if (call) {
$element.fire('mdk:change');
}
}
);
},
/**
* チェックが付いているチェックボックスの個数をカウントする
*
* @param Array $elements checkbox の要素を含む配列
* @return Integer チェックが付いているチェックボックスの個数
*/
countChecked: function ($elements) {
if (!Object.isArray($elements)) {
return;
}
var counter = 0;
$elements.each(
function ($element) {
if ($element.tagName.toLowerCase() == 'input' && $element.readAttribute('type') == 'checkbox' && $element.checked) {
counter++;
}
}
);
return counter;
}
}
},
/**
* ダミーフォームを生成する
*
* @return String 生成したフォームの ID
*/
createDummy: function(action, parameters) {
var $form = new Element('form');
var form_id = $form.identify();
$form.writeAttribute('action', action);
$form.writeAttribute('mthod', 'post');
if (parameters) {
$H(parameters).each(
function(parameter) {
var $input = new Element('input');
$input.writeAttribute('type', 'hidden');
$input.writeAttribute('name', parameter.key);
$input.writeAttribute('value', parameter.value);
$form.insert({bottom: $input});
}
);
}
$$('body')[0].insert({bottom: $form});
return form_id;
},
/**
* サジェストするためのテキストをフォームに表示する
*
* @param Element $element フォームの INPUT TEXT
* @param Object options オプション
*/
suggestText: function($element) {
var options = Object.extend({
attribute: 'suggest',
suggest_color: '#AAAAAA',
normal_color: '#000000',
remove: true,
remove_onsubmit: true
}, arguments[1] || {});
var suggest_forcus = function(onsubmit) {
if($element.value == $element.readAttribute(options.attribute)){
if((onsubmit && options.remove_onsubmit) || (!onsubmit && options.remove)) {
$element.value="";
}
$element.setStyle({'color': options.normal_color});
}
}
var suggest_blur = function() {
if($element.value == "" || (!options.remove && $element.value == $element.readAttribute(options.attribute))) {
$element.setStyle({'color': options.suggest_color});
$element.value=$element.readAttribute(options.attribute);
}
}
Event.observe($element, 'focus', suggest_forcus.bind(this, false));
Event.observe($element, 'blur', suggest_blur.bind(this));
Event.observe($element.up('form'), 'submit', suggest_forcus.bind(this, true));
suggest_blur.bind(this)();
return $element;
}
},
/**
* コンストラクタ
*/
initialize: function() {
}
}
);
Mdk.PROTOCOL = location.protocol;
Mdk.SECURE = (Mdk.PROTOCOL.match(/^https/) ? true : false)
Mdk.HOSTNAME = location.hostname;
var a_hostname = location.hostname.split(/\./);
var tld = a_hostname.pop();
var sld = a_hostname.pop();
Mdk.DOMAIN = sld + '.' + tld;
var Mdk_Util = {
ClearElement: function() {
var e_div = new Element('div');
e_div.addClassName('clear-both');
e_div.update(' ');
return e_div;
},
CreateWindow: function(event, e_target, e_dummy_parent, x, y) {
var e_div, e_iframe, e_dummy, left, top, width, height;
e_div = new Element('div');
if (Prototype.Browser.IE) {
e_iframe = new Element('iframe', {frameborder: 0, src: 'javascript: false;'});
}
e_dummy = e_target.cloneNode(true);
var e_parent = e_dummy_parent ? $(e_dummy_parent) : $$('body')[0];
var parent_position = e_parent.getStyle('position');
e_parent.setStyle({position: 'relative'});
e_dummy.setStyle({position: 'absolute', top: 0, left: 0});
e_dummy.setOpacity(0);
e_parent.insert({top: e_dummy});
width = e_dummy.getWidth();
height = e_dummy.getHeight();
left = event.pointerX();
top = event.pointerY();
if (x == 'right') {
left = left - width - 15;
}
if (y == 'bottom') {
top = top - height - 15;
}
e_dummy.remove();
e_parent.setStyle({position: parent_position});
if (Prototype.Browser.IE) {
e_iframe.setStyle(
{
width : width + "px",
height : height + "px",
position : 'absolute',
color : '#ffffff',
left : left + "px",
top : top + "px",
zIndex : 10,
padding : 0,
margin : 0,
border : "none"
}
);
}
e_div.setStyle(
{
position : 'absolute',
zIndex : 20,
left : left + "px",
top : top + "px",
padding : 0,
margin : 0,
border : "none"
}
);
e_div.insert({bottom: e_target});
e_target.removeAttribute('id');
return {element: e_div, iframe: e_iframe};
},
/**
* 郵便番号検索を行う
* 郵便番号などの要素名は決め打ち
*
* @param String action アクション名
* @param Element e_form フォーム要素
* @param Function callback フィルインするためのコールバックメソッド
* @return void
*/
ZipcodeSearch: function(action, e_form, callback) {
var zipcode = '';
if (e_form.down('input[name="zipcode"]')) {
e_form.down('input[name="zipcode"]').fire('mdk:focus');
zipcode = '' + e_form.down('input[name="zipcode"]').getValue();
} else if (e_form.down('input[name="zipcode_list[0]"]') && e_form.down('input[name="zipcode_list[1]"]')) {
e_form.down('input[name="zipcode_list[0]"]').fire('mdk:focus');
e_form.down('input[name="zipcode_list[1]"]').fire('mdk:focus');
zipcode = '' + e_form.down('input[name="zipcode_list[0]"]').getValue() + e_form.down('input[name="zipcode_list[1]"]').getValue();
} else {
return;
}
// {{{ フィルするためのメソッド
this.FillAddress = function(response) {
r = response.responseJSON;
if (r.result) {
document.zipcode_list = r.zipcode_list;
if (r.zipcode_list.length == 1) {
this.callback.bind({ zipcode: r.zipcode_list[0], e_form: this.e_form })();
} else {
var e_div, e_p, e_a;
e_div = new Element('div');
e_div.addClassName('inline-left');
e_div.setStyle(
{
'width': '400px',
'height': '600px',
'overflowY': 'scroll',
'backgroundColor': '#ffffff',
'border': 'solid 1px #cccccc'
}
);
e_p = new Element('p');
e_p.addClassName('text-x-large');
e_p.addClassName('inline-center');
e_p.addClassName('bold');
e_p.setStyle(
{
'margin': '10px'
}
);
e_p.update('住所を選択してください');
e_div.insert({bottom: e_p});
for (var i = 0; i < r.zipcode_list.length; i++) {
e_p = new Element('p');
e_p.addClassName('text-large');
e_p.setStyle(
{
'margin': '10px'
}
);
e_a = new Element('a', { 'href': 'javascript: void(0);' });
e_a.observe('click', this.callback.bind({ zipcode: r.zipcode_list[i], e_form: this.e_form }));
e_a.update(r.zipcode_list[i].prefecture_label + r.zipcode_list[i].municipality + r.zipcode_list[i].town);
e_p.insert({bottom: e_a});
e_div.insert({bottom: e_p});
}
e_p = new Element('p');
e_p.addClassName('inline-center');
e_p.addClassName('text-large');
e_p.setStyle(
{
'margin': '10px'
}
);
e_a = new Element('a', { 'href': 'javascript: void(0);' });
e_a.addClassName('mdk-black-out-close');
e_a.update('閉じる');
e_p.insert({bottom: e_a});
e_div.insert({bottom: e_p});
Mdk_Globals.black_out = new Mdk_BlackOut(e_div, { keep_id: true });
}
} else {
alert('該当する住所が見付かりませんでした');
}
}.bind({callback: callback, e_form: e_form});
// }}}
new Ajax.Request(
action
, {
method: 'get'
, onSuccess: this.FillAddress
, parameters: {
zipcode: zipcode
}
}
);
},
ZipcodeDecideHelper: {
joined: function() {
if (this.e_form.down('input[name="zipcode_list[0]"]')) {
this.e_form.down('input[name="zipcode_list[0]"]').setValue(this.zipcode.zipcode_list[0]);
}
if (this.e_form.down('input[name="zipcode_list[1]"]')) {
this.e_form.down('input[name="zipcode_list[1]"]').setValue(this.zipcode.zipcode_list[1]);
}
if (this.e_form.down('input[name="zipcode"]')) {
this.e_form.down('input[name="zipcode"]').setValue(this.zipcode.zipcode);
}
if (this.e_form.down('select[name="prefecture"]')) {
this.e_form.down('select[name="prefecture"]').setValue(this.zipcode.prefecture);
}
if (this.e_form.down('input[name="address"]')) {
this.e_form.down('input[name="address"]').setValue(this.zipcode.municipality + this.zipcode.town);
this.e_form.down('input[name="address"]').fire('mdk:focus');
this.e_form.down('input[name="address"]').fire('mdk:blur');
this.e_form.down('input[name="address"]').focus();
this.e_form.down('input[name="address"]').setValue(this.e_form.down('input[name="address"]').getValue());
}
var input_house_number = this.e_form.down('input[name="house_number"]');
if (input_house_number) {
input_house_number.focus();
}
if (Mdk_Globals.black_out) {
Mdk_Globals.black_out.hide();
}
},
splited: function() {
if (this.e_form.down('input[name="zipcode_list[0]"]')) {
this.e_form.down('input[name="zipcode_list[0]"]').setValue(this.zipcode.zipcode_list[0]);
}
if (this.e_form.down('input[name="zipcode_list[1]"]')) {
this.e_form.down('input[name="zipcode_list[1]"]').setValue(this.zipcode.zipcode_list[1]);
}
if (this.e_form.down('input[name="zipcode"]')) {
this.e_form.down('input[name="zipcode"]').setValue(this.zipcode.zipcode);
}
if (this.e_form.down('select[name="prefecture"]')) {
this.e_form.down('select[name="prefecture"]').setValue(this.zipcode.prefecture);
}
if (this.e_form.down('input[name="municipality"]')) {
this.e_form.down('input[name="municipality"]').setValue(this.zipcode.municipality);
this.e_form.down('input[name="municipality"]').fire('mdk:focus');
this.e_form.down('input[name="municipality"]').fire('mdk:blur');
this.e_form.down('input[name="municipality"]').setValue(this.e_form.down('input[name="municipality"]').getValue());
}
if (this.e_form.down('input[name="town"]')) {
this.e_form.down('input[name="town"]').setValue(this.zipcode.town);
this.e_form.down('input[name="town"]').fire('mdk:focus');
this.e_form.down('input[name="town"]').fire('mdk:blur');
this.e_form.down('input[name="town"]').focus();
this.e_form.down('input[name="town"]').setValue(this.e_form.down('input[name="town"]').getValue());
}
if (Mdk_Globals.black_out) {
Mdk_Globals.black_out.hide();
}
}
},
SwitchImage: function(element, _switch) {
element = $(element);
if (element.readAttribute('src')) {
element.writeAttribute('src', element.readAttribute('src').sub(/(on|off)\.(gif|jpe?g|png)(\?|$)/i, (_switch ? 'on' : 'off') + '.#{2}#{3}'));
}
}
};
var Mdk_Alert = Class.create(
{
/**
* @var Object static 変数を格納するオブジェクト
* @static
*/
Statics: {
/** @var Number 表示オブジェクトのインデックス */
index: 0,
/** @var Number 表示しているオブジェクトの数 */
displayed_number: 0,
/** @var Number 表示オブジェクトの高さ合計 */
composited_height: 0
},
/**
* 実際に表示する
*/
show: function() {
// 要素の構築
this.Statics.index++;
this.base = new Element(
'div',
{
id: 'mdk-alert-base-' + this.Statics.index
}
);
if (Prototype.Browser.IE) {
this.iframe = new Element(
'iframe',
{
id: 'mdk-alert-iframe' + this.Statics.index,
src: '/images/spacer.gif',
frameborder: "0"
}
);
}
this.div = new Element(
'div',
{
id: 'mdk-alert-div-' + this.Statics.index
}
);
// 中身をセット
this.div.insert({bottom: this.$element});
// style を設定
var position = 'fixed';
if (Prototype.Browser.IE) {
position = 'absolute';
}
this.base.setStyle(
{
display: 'none',
position: position,
zIndex: 105,
padding: 0,
margin: 0,
border: "none"
}
);
if (Prototype.Browser.IE) {
this.iframe.setStyle(
{
position: position,
zIndex: 110,
padding: 0,
margin: 0,
border: "none"
}
);
}
this.div.setStyle(
{
position: position,
zIndex: 120,
border: 'solid 1px #aaaaaa',
backgroundColor: '#ffffff'
}
);
// 要素を追加
if (Prototype.Browser.IE) {
this.base.insert({bottom: this.iframe});
}
this.base.insert({bottom: this.div});
$$('body')[0].insert({bottom: this.base});
// エフェクトを設定
new Effect.Parallel(
[
Effect.Appear(
this.base,
{
duration: 0.5,
beforeStartInternal: function() {
this.Statics.displayed_number++;
this.base.setOpacity(0.1);
this.base.show();
this.updateSize();
this.updatePosition();
}.bind(this)
}
),
Effect.Fade(
this.base,
{
duration: 1,
delay: 3,
afterFinishInternal: function() {
this.div.hide();
if (Prototype.Browser.IE) {
this.iframe.hide();
}
this.base.hide();
this.Statics.displayed_number--;
if (this.Statics.displayed_number <= 0) {
this.Statics.composited_height = 0;
}
}.bind(this)
}
)
],
{delay: 3}
);
},
/**
* 位置を更新する
*
* @param Number left 横位置
* @param Number top 縦位置
*/
updatePosition: function(left, top) {
if (!this.base) {
return;
}
if (!left) {
left = document.viewport.getScrollOffsets().left + document.viewport.getDimensions().width - this.$element.getWidth() - 2;
}
if (!top) {
top = this.Statics.composited_height;
}
this.Statics.composited_height += this.$element.getHeight();
if (Prototype.Browser.IE) {
this.base.setStyle({left: document.viewport.getScrollOffsets().left + left + 'px', top: document.viewport.getScrollOffsets().top + top + 'px'});
} else {
this.base.setStyle({left: left + 'px', top: top + 'px'});
}
},
/**
* サイズを更新する
*
* @param Number width 横幅
* @param Number height 縦幅
*/
updateSize: function(width, height) {
if (!this.base) {
return;
}
width = width || this.$element.getWidth();
height = height || this.$element.getHeight();
this.base.setStyle({width: width + 'px', height: height + 'px'});
if (Prototype.Browser.IE) {
this.iframe.setStyle({width: width + 'px', height: height + 'px'});
}
this.div.setStyle({width: width + 'px', height: height + 'px'});
},
/**
* コンストラクタ
*/
initialize: function($element) {
var div = new Element('div');
if (Object.isString($element)) {
div.update($element);
} else {
div.insert({bottom: $element});
}
div.setStyle({padding: '5px 10px', whiteSpace: 'nowrap'});
this.$element = div;
this.show();
}
}
);
var Mdk_Induce = Class.create(
{
focus: function() {
if (this.element.getValue().gsub(/\r|\n/, '') == this.induce_message.gsub(/\r|\n/, '')) {
this.element.setValue('');
}
this.element.removeClassName('silver');
},
blur: function() {
if (this.element.getValue().gsub(/\r|\n/, '') === '' || this.element.getValue().gsub(/\r|\n/, '') == this.induce_message.gsub(/\r|\n/, '')) {
this.element.addClassName('silver');
this.element.setValue(this.induce_message);
}
},
submit: function() {
if (this.element.getValue().gsub(/\r|\n/, '') == this.induce_message.gsub(/\r|\n/, '')) {
this.element.setValue('');
}
},
initialize: function(element, induce_message) {
this.element = $(element);
this.induce_message = induce_message;
this.element.observe('focus', this.focus.bind(this));
this.element.observe('mdk:focus', this.focus.bind(this));
this.element.observe('blur', this.blur.bind(this));
this.element.observe('mdk:blur', this.blur.bind(this));
this.element.up('form').observe('submit', this.submit.bind(this));
this.element.up('form').observe('mdk:submit', this.submit.bind(this));
this.element.mdk_induce = this;
this.element.fire('mdk:focus');
this.element.fire('mdk:blur');
}
}
);
var Mdk_Tooltip = Class.create(
{
show: function(event) {
this.o_tooltip = Mdk_Util.CreateWindow(event, this.e_tooltip, false, 'left', 'bottom');
if (Object.isElement(this.o_tooltip.element)) {
this.o_tooltip.element.addClassName('mdk-tooltip');
this.o_tooltip.element.addClassName('inline-left');
$$('body')[0].insert({bottom: this.o_tooltip.element});
}
if (Object.isElement(this.o_tooltip.iframe)) {
$$('body')[0].insert({bottom: this.o_tooltip.iframe});
}
this.hide_timer = setTimeout(this.hide.bindAsEventListener(this), this.display_second * 1000);
},
hide: function(event) {
if (Object.isUndefined(this.o_tooltip)) {
return;
}
if (Object.isElement(this.o_tooltip.element)) {
this.o_tooltip.element.remove();
this.o_tooltip.element = undefined;
}
if (Object.isElement(this.o_tooltip.iframe)) {
this.o_tooltip.iframe.remove();
this.o_tooltip.iframe = undefined;
}
this.o_tooltip = undefined;
if (!Object.isUndefined(this.hide_timer)) {
clearTimeout(this.hide_timer);
}
this.hide_timer = undefined;
},
update: function(event) {
if (Object.isUndefined(this.o_tooltip)) {
return;
}
var left, top;
left = event.pointerX();
top = event.pointerY();
if (Object.isElement(this.o_tooltip.element)) {
this.o_tooltip.element.setStyle({left: left + 'px', top: (top - this.o_tooltip.element.getHeight() - 15) + 'px'});
}
if (Object.isElement(this.o_tooltip.iframe)) {
this.o_tooltip.iframe.setStyle({left: left + 'px', top: (top - this.o_tooltip.element.getHeight() - 15) + 'px'});
}
if (!Object.isUndefined(this.hide_timer)) {
clearTimeout(this.hide_timer);
}
this.hide_timer = setTimeout(this.hide.bindAsEventListener(this), this.display_second * 1000);
},
initialize: function(element, content, display_second) {
element = $(element);
if (!element) {
return;
}
if (Object.isString(content)) {
this.e_tooltip = new Element('div');
this.e_tooltip.update(content);
} else if (Object.isElement(content)) {
this.e_tooltip = content.cloneNode(true);
} else {
return;
}
this.e_tooltip.setStyle(
{
border: 'solid 1px #000000',
backgroundColor: '#ffffe7',
padding: '5px'
}
);
if (display_second) {
this.display_second = display_second;
} else {
this.display_second = 3;
}
$$('body')[0].setStyle({position: 'relative'});
element.observe('mouseover', this.show.bindAsEventListener(this));
element.observe('mousemove', this.update.bindAsEventListener(this));
element.observe('mouseout', this.hide.bindAsEventListener(this));
element.observe(
'mdk:dummy',
function() {
this.show.bindAsEventListener(this)();
this.hide.bindAsEventListener(this)();
}.bind(this)
);
element.observe('mdk:tooltip:show', this.show.bindAsEventListener(this));
element.observe('mdk:tooltip:hide', this.hide.bindAsEventListener(this));
}
}
);
var Mdk_NowLoading = {
show: function() {
var e_loading_mask = new Element('div', {id: 'mdk-now-loading-mask'});
var e_loading = new Element('div', {id: 'mdk-now-loading'});
var e_loading_indicator = new Element('div', {id: 'mdk-now-loading-indicator'});
var e_loading_message = new Element('p');
var e_loading_image = new Element('img', {src: '/images/common/now-loading.gif', width: 48, height: 48});
e_loading_mask.setOpacity(0.5);
e_loading_message.update('ただいま読み込み中です');
e_loading_indicator.insert({bottom: e_loading_image});
e_loading_indicator.insert({bottom: e_loading_message});
e_loading.insert({bottom: e_loading_indicator});
$$('body')[0].insert({top: e_loading});
$$('body')[0].insert({top: e_loading_mask});
},
hide: function() {
$('mdk-now-loading').remove();
$('mdk-now-loading-mask').remove();
if ($('mdk-now-loading-iframe')) {
$('mdk-now-loading-iframe').remove();
}
}
};
var Mdk_BlackOut = Class.create(
{
show: function() {
if ($('mdk-black-out-mask') || $('mdk-black-out')) {
return;
}
var dummy = this.element.cloneNode(true);
dummy.setOpacity(0);
dummy.setStyle(
{
position: 'absolute'
}
);
$$('body')[0].insert({bottom: dummy});
var width, height, left, top, body_position;
width = dummy.getWidth();
height = dummy.getHeight();
left = (document.viewport.getWidth() / 2) - (width / 2);
top = (document.viewport.getHeight() / 2) - (height / 2);
if (top < 0) {
top = 0;
}
dummy.remove();
if (Prototype.Browser.IE) {
top += document.viewport.getScrollOffsets().top;
}
body_position = $$('body')[0].getStyle('position');
$$('body')[0].setStyle('position', 'relative');
this.e_black_out_mask = new Element('div', {id: 'mdk-black-out-mask'});
if (Prototype.Browser.IE) {
this.e_black_out_iframe = new Element('iframe', {id: 'mdk-black-out-iframe', src: "javascript: false;", frameborder: 0});
}
this.e_black_out = new Element('div', {id: 'mdk-black-out'});
this.e_black_out_indicator = new Element('div', {id: 'mdk-black-out-indicator'});
if (!Object.isUndefined(this.options) && this.options.hide_at_mask) {
this.e_black_out_mask.observe('click', this.hide.bind(this));
}
if (Object.isElement(this.element) && this.element.down('.mdk-black-out-close')) {
this.element.select('.mdk-black-out-close').each(
function(e_close) {
e_close.observe('click', this.hide.bind(this));
}.bind(this)
);
}
this.e_black_out_mask.setStyle(
{
height: ($('container') ? $('container').getHeight() : $$('body')[0].getHeight()) + 'px'
}
);
if (Prototype.Browser.IE) {
this.e_black_out_iframe.setStyle(
{
height: ($('container') ? $('container').getHeight() : $$('body')[0].getHeight()) + 'px'
}
);
}
this.e_black_out.setStyle(
{
position: 'absolute',
width: width + 'px',
height: height + 'px',
left: left + 'px',
top: top + 'px'
}
);
this.element.setStyle('position', 'relative');
this.e_black_out_indicator.setStyle(
{
width: width + 'px'
}
);
this.e_black_out_indicator.insert({bottom: this.element});
this.e_black_out.insert({bottom: this.e_black_out_indicator});
this.e_black_out.hide();
$$('body')[0].insert({top: this.e_black_out});
$$('body')[0].insert({top: this.e_black_out_mask});
if (Prototype.Browser.IE) {
$$('body')[0].insert({top: this.e_black_out_iframe});
}
Effect.BlindDown(this.e_black_out, {duration: 1.0});
$$('body')[0].setStyle('position', body_position);
},
hide: function() {
if (this.e_black_out_mask) {
this.e_black_out_mask.remove();
}
if (this.e_black_out_iframe) {
this.e_black_out_iframe.remove();
}
if (this.e_black_out) {
this.e_black_out.remove();
}
},
initialize: function(element, options) {
element = $(element);
if (!Object.isElement(element)) {
return;
}
this.options = options || {};
if (this.options && !this.options.keep_id) {
this.element = element.cloneNode(true);
this.element.removeAttribute('id');
this.element.identify();
} else {
this.element = element;
}
this.show.bind(this)();
}
}
);
var Mdk_Decrypt = Class.create(
{
/** @var Integer 固定シード */
FIXED_SEED: [7, 13],
/**
* 複合化
*
* @return void
*/
decrypt: function() {
if (!this.text_only) {
document.write('<a href="ma' + 'il' + 'to:');
this.value[0].each(
function(character) {
document.write(this._decrypt(character, 0));
}.bind(this)
);
document.write('">');
}
this.value[1].each(
function(character) {
document.write(this._decrypt(character, 1));
}.bind(this)
);
if (!this.text_only) {
document.write('<' + '/a' + '>');
}
},
/**
* 文字単位の複合化
*
* @param String character 一文字
* @param Integer index インデックス
* @return String 複合した文字
*/
_decrypt: function(character, index) {
return String.fromCharCode(character - this.seed + this.FIXED_SEED[index]);
},
/**
* コンストラクタ
*
* @param Array value 文字の配列
* @param Integer seed シード
* @param Boolean text_only テキスト表示のみにするかどうか
* @return void
*/
initialize: function(value, seed, text_only) {
this.value = value;
this.seed = seed;
this.text_only = text_only;
this.decrypt();
}
}
);
var Mdk_Globals = {};
var mdk = new Mdk;
/**
* 数字 3 桁ごとにカンマを入れる
*
* @return String カンマを入れた数値
*/
Number.prototype.commify = function() {
var s = this.toString().split("\.");
return s[0].replace(/((^[+-])?(\d)+?)(?=(\d{3})+$)/g, "$1,") + (s[1]? "." + s[1].replace(/(\d{3})(?=\d+)/g, "$1,") : "");
}
Number.prototype.roundByDigit = function(digit) {
var value = this;
value = value * Math.pow(10, digit);
value = parseInt((Math.round(value)).toString());
value = value / Math.pow(10, digit);
return value;
};
/**
* ゼロ埋めする
*
* @param Number digit 埋める桁数
* @return String 埋めた文字列
*/
Number.prototype.zerofill = function(digit) {
var string = ('0'.repeat(digit) + this.toString());
return string.substr(string.length - digit, digit);
};
/**
* 文字列を繰り返す
*
* @param Number length 繰り返す回数
* @return String 構築した文字列
*/
String.prototype.repeat = function(length) {
var s = [];
while (s.length < length) {
s.push(this);
}
return s.join('');
}
/**
* 改行コードを BR タグに置換する
*
* @param Boolen xhtml 対象とする文字列
* @return String 置換後の文字列
*/
String.prototype.nl2br = function(xhtml) {
xhtml = Object.isUndefined(xhtml) || xhtml ? true : false;
br = xhtml ? '<br />' : '<br>';
return this.gsub(/\r\n|\r|\n/i, br);
}
/**
* URL的な文字列をアンカータグに置換する
*
* @param String target ターゲットフレーム
* @return String 置換後の文字列
*/
String.prototype.anchorize = function(target) {
target = Object.isUndefined(target) ? false : ' target="' + target + '"';
var string = this.toString().gsub(/(https?:\/\/[a-zA-Z0-9#$%&,.\/;=?@^_\-\[\]]+)/m, '<a href="#{0}"' + target + '>#{0}</a>');
return string;
}
/**
* prototypeUtils.js from http://jehiah.com/
* Licensed under Creative Commons.
* version 1.0 December 20 2005
*
* Contains:
* + Form.Element.setValue()
* + unpackToForm()
*/
/* Form.Element.setValue("fieldname/id","valueToSet") */
Form.Element.Methods.setValue = function(element,newValue) {
element_id = element;
element = $(element);
if (!element){element = document.getElementsByName(element_id)[0];}
if (!element){return false;}
var method = element.tagName.toLowerCase();
var parameter = Form.Element.SetSerializers[method](element,newValue);
}
Form.Element.SetSerializers = {
input: function(element,newValue) {
switch (element.type.toLowerCase()) {
case 'submit':
case 'hidden':
case 'password':
case 'text':
return Form.Element.SetSerializers.textarea(element,newValue);
case 'checkbox':
case 'radio':
return Form.Element.SetSerializers.inputSelector(element,newValue);
}
return false;
},
inputSelector: function(element,newValue) {
fields = document.getElementsByName(element.name);
for (var i=0;i<fields.length;i++){
if (Object.isArray(newValue)) {
if (newValue.include(fields[i].value)) {
fields[i].checked = true;
}
} else {
if (fields[i].value == newValue){
fields[i].checked = true;
}
}
}
},
textarea: function(element,newValue) {
element.value = newValue;
},
select: function(element,newValue) {
var value = '', opt, index = element.selectedIndex;
for (var i=0;i< element.options.length;i++){
if (Object.isArray(newValue)) {
if (newValue.include(element.options[i].value)) {
element.options[i].selected = true;
}
} else {
if (element.options[i].value == newValue){
element.options[i].selected = true;
return true;
}
}
}
}
}
/* Form.Element.clear("fieldname/id") */
Form.Element.Methods.clear = function(element) {
element_id = element;
element = $(element);
if (!element){element = document.getElementsByName(element_id)[0];}
if (!element){return false;}
var method = element.tagName.toLowerCase();
var parameter = Form.Element.ClearSerializers[method](element);
return parameter;
}
Form.Element.Methods.selectAll = function(element) {
element = $(element);
setTimeout(
function() {
this.select();
}.bind(element)
, 10
);
return element;
};
Form.Element.ClearSerializers = {
input: function(element) {
switch (element.type.toLowerCase()) {
case 'submit':
case 'hidden':
case 'password':
case 'text':
return Form.Element.ClearSerializers.textarea(element);
case 'checkbox':
case 'radio':
return Form.Element.ClearSerializers.inputSelector(element);
}
return false;
},
inputSelector: function(element) {
if (!$(element).up('form').select('[name="' + element.name + '"]')) {
return false;
}
fields = $(element).up('form').select('[name="' + element.name + '"]');
for (var i=0;i<fields.length;i++){
fields[i].checked = false;
fields[i].removeAttribute('checked');
}
return element;
},
textarea: function(element) {
element.value = '';
return element;
},
select: function(element,newValue) {
var value = '', opt, index = element.selectedIndex;
for (var i=0;i< element.options.length;i++){
element.options[i].selected = false;
element.options[i].removeAttribute('selected');
}
}
}
Element.addMethods();
function unpackToForm(data){
for (i in data){
Form.Element.setValue(i,data[i].toString());
}
}
document.viewport.getDimensions = function() {
var dimensions = { }, B = Prototype.Browser;
$w('width height').each(function(d) {
var D = d.capitalize();
if (B.WebKit && !document.evaluate) {
// Safari <3.0 needs self.innerWidth/Height
dimensions[d] = self['inner' + D];
} else if (B.Opera && parseFloat(window.opera.version()) < 9.5) {
// Opera <9.5 needs document.body.clientWidth/Height
dimensions[d] = document.body['client' + D];
//} else if (B.IE) {
// dimensions[d] = document.body['client' + D];
} else {
dimensions[d] = document.documentElement['client' + D];
}
});
return dimensions;
}
if (typeof jQuery != 'undefined') {
void function ($) {
$.extend({
MSMconfirm: function (title, msg, buttons_list) {
var confirm_html = $('<div id="moshimo-confirm" style="width:200px; display:none;">TEST!</div>');
$(confirm_html).html(msg);
$(confirm_html).dialog({
autoOpen: false,
draggable: false,
title: title,
//height: 140,
closeOnEscape: false,
modal: true,
show: "clip",
buttons: buttons_list
});
$(confirm_html).dialog('open');
}
, MSMalert: function (title, msg, func) {
var alert_html = $('<div id="moshimo-confirm" style="width:200px; background-color: #d8f090; display:none;">TEST!</div>');
$(alert_html).text(msg);
$(alert_html).dialog({
autoOpen: false,
title: title,
height: 140,
draggable: false,
closeOnEscape: false,
modal: true,
show: "clip",
buttons: {
"OK": function () {
func();
$(this).dialog('close');
}
}
});
$(alert_html).dialog('open');
}
});
}(jQuery);
}
<file_sep>/js/1.0.0.js
/**
* jQuery.induce - jQuery Plugin
*
* Under The MIT License
* Copyright (c) 2011 <NAME>. (http://monry.jp/)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Version: 1.0.0
* Revision: $Rev$
* Date: $Date$
*/
(
function($) {
$.B = {};
$.B.check = function() {
// {{{ 初期化
// 新しいブラウザかどうか
$.B.modern = false;
// 古いブラウザかどうか
$.B.legacy = false;
// Internet Explorer かどうか
$.B.IE = false;
// Internet Explorer 5.5 以下かどうか
$.B.IE55l = false;
// Internet Explorer 6 かどうか
$.B.IE6 = false;
// Internet Explorer 7 かどうか
$.B.IE7 = false;
// Internet Explorer 8 かどうか
$.B.IE8 = false;
// Internet Explorer 9 かどうか
$.B.IE9 = false;
// Internet Explorer (Quirks モード) かどうか
$.B.IEQuirks = false;
// Internet Explorer 7 (互換モード) かどうか
$.B.IE7Emulated = false;
// Internet Explorer 8 (互換モード) かどうか
$.B.IE8Emulated = false;
// Mozilla Firefox かどうか
$.B.FF = false;
// エンジンが WebKit かどうか
$.B.WK = false;
// Google Chrome かどうか
$.B.GC = false;
// Safari かどうか
$.B.SF = false;
// Opera かどうか
$.B.OP = false;
// それ以外のブラウザかどうか
$.B.other = false;
// }}}
// {{{ 判定処理
if (!document.uniqueID && !window.opera && !window.globalStorage && window.localStorage) {
/* WebKit */
$.B.WK = true;
} else if (window.globalStorage) {
/* Firefox */
$.B.FF = true;
} else if (window.opera) {
/* Opera */
$.B.OP = true;
} else if (typeof window.ActiveXObject != 'undefined' || typeof window.document.all != 'undefined') {
/* Internet Explorer */
if (typeof document.documentMode != 'undefined') {
if (document.documentMode == '8') {
$.B.IE8Emulated = true;
} else if (document.documentMode == '7') {
$.B.IE7Emulated = true;
} else if (document.documentMode == '5') {
$.B.IEQuirks = true;
}
}
if ($.support.opacity) {
/* Internet Explorer 9 */
$.B.IE9 = true;
} else if (typeof window.addEventListener == 'undefined' && typeof document.documentElement.style.maxHeight == 'undefined') {
/* Internet Explorer 6 */
$.B.IE6 = true;
} else if (typeof window.addEventListener == 'undefined' && typeof document.querySelectorAll == 'undefined') {
/* Internet Explorer 7 */
$.B.IE7 = true;
} else if (typeof window.addEventListener == 'undefined' && typeof document.getElementsByClassName == 'undefined') {
/* Internet Explorer 8 */
$.B.IE8 = true;
} else {
/* Internet Explorer 5.5 以下 */
$.B.IE55l = true;
}
} else {
/* 判別不能 */
$.B.other = true;
}
// }}}
// {{{ 条件が重複するモノを一括で判定
$.B.IE = $.B.IE55l || $.B.IE6 || $.B.IE7 || $.B.IE8 || $.B.IE9;
$.B.modern = !$.B.IE55l && !$.B.IE6 && !$.B.IE7 && !$.B.IE8 && !$.B.other;
$.B.legacy = !$.B.modern;
$.B.GC = $.B.WK;
$.B.SF = $.B.WK;
// }}}
// {{{ 冗長な名前でも値を持っておく
$.B.InternetExplorer = $.B.IE;
$.B.InternetExplorer55Lower = $.B.IE55l;
$.B.InternetExplorer6 = $.B.IE6;
$.B.InternetExplorer7 = $.B.IE7;
$.B.InternetExplorer8 = $.B.IE8;
$.B.InternetExplorer9 = $.B.IE9;
$.B.Firefox = $.B.FF;
$.B.WebKit = $.B.WK;
$.B.Safari = $.B.WK;
$.B.GoogleChrome = $.B.WK;
$.B.Opera = $.B.OP;
// }}}
};
$.B.check();
}
)(jQuery);
<file_sep>/js/common.js
void function($) {
$(
function(event) {
// {{{ 画面最上部へスクロール
$('#totop').click(function (event) {
event.preventDefault();
$.scrollTo(
'#container'
, 800
);
});
// }}}
}
);
}(jQuery);
<file_sep>/js/1.0.0_2.js
/**
* jQuery.heightAlign - jQuery Plugin
*
* Under The MIT License
* Copyright (c) 2011 <NAME>. (http://monry.jp/)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Version: 1.0.0
* Revision: $Rev$
* Date: $Date$
*/
(
function($) {
// {{{ 高さ調節
$.fn.heightAlign = function(options) {
var
// デフォルトの設定
_defaults = {
'group_by_attribute': false
},
// 設定確定
_setting = $.extend(_defaults, options),
_targets = $(this),
// 呼出時のコンテキスト
_context = $(this).context,
// 呼出時のセレクタ
_selector = $(this).selector,
// 実処理
_align = function() {
// {{{ 高さリスト構築
var height_list = {};
_targets.each(
function(index, element) {
var key = '';
if (_setting.group_by_attribute) {
key = $(element).attr(_setting.group_by_attribute);
}
if (typeof height_list[key] == 'undefined') {
height_list[key] = 0;
}
if (height_list[key] < $(element).height()) {
height_list[key] = $(element).height();
}
}
);
// }}}
// {{{ 高さリストを元に高さを実際に調整
$.each(
height_list
, function(key, value) {
var __selector = _selector;
if (_setting.group_by_attribute) {
__selector += '[' + _setting.group_by_attribute + '="' + key + '"]';
}
$(__selector, _context).height(value);
}
);
// }}}
}
;
_align();
return this;
}
// }}}
}
)(jQuery);
<file_sep>/46.html
<!doctype html>
<html lang="ja">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="株式会社もしも 実藤裕史 1979年4月21日生まれ。埼玉県出身。一橋大学商学部中退。大学在学中にECベンチャー「オイシックス」のインターンとしてスタートアッ..." />
<meta name="keywords" content="株式会社もしも、実藤裕史、ビジョナリー、社長、取締役、経営者、CEO、インタビュー、転職、求人、仕事、採用" />
<meta property="og:type" content="article" />
<meta property="og:title" content="モノを売る仕組みの提供で個人を応援!" />
<meta property="og:description" content="株式会社もしも 実藤裕史氏 のインタビュー記事を公開中!他にも、魅力的な経営者たちのインタビュー記事を多数掲載しています。" />
<meta property="og:image" content="http://lvimg.jp/job-link/img/visionary/46/profile_image_circle_large.jpg?_=431686020" />
<meta property="og:url" content="http://job.j-sen.jp/visionary/president/article/46/" />
<meta property="og:site_name" content="ビジョナリー" />
<meta name="viewport" content="width=1060">
<title>株式会社もしも 実藤裕史 モノを売る仕組みの提供で個人を応援! | ビジョナリー</title>
<link rel="stylesheet" href="/css/visionary/visionary.css" media="all">
<script src="/js/dist/app/visionary/template/layout.js?rel=2da181bc10b274f38a7d6218f21288af"></script>
<script src="/js/dist/app/visionary/module/article/index.js?rel=2a0c40298c2160486edf94c76d220961"></script>
<!--[if lte IE 8]>
<script type="text/javascript" src="/js/2009/selectivizr-min.js"></script>
<![endif]-->
<link rel="shortcut icon" href="/favicon.ico">
</head>
<body>
<!-- Google Tag Manager -->
<noscript><iframe src="http://www.googletagmanager.com/ns.html?id=GTM-8CP5"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
<script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});
var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;
j.src='http://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-8CP5');</script>
<!-- End Google Tag Manager -->
<div id="header">
<div class="center-container">
<div class="site-logo"><a href="/visionary/president/">ビジョナリー</a></div>
<div class="site-txt">
<h1>株式会社もしも 実藤裕史 モノを売る仕組みの提供で個人を応援! ビジョナリー</h1>
<p>[<a href="/visionary/president/guide/">このサイトについて</a>]</p>
</div>
<form action="/visionary/president/search/" method="get">
<input type="text" name="freewords" value="" placeholder="上場、IT、経営など">
<input type="submit" value="検索">
</form>
</div>
</div>
<div id="contents">
<div class="article-profile">
<div class="heading-wrap">
<h2>“モノを売る仕組みの提供で個人を応援!”</h2>
</div>
<div class="content">
<p class="name">株式会社もしも<br>代表取締役<br>実藤裕史</p>
<p class="mod-txt-muted mod-right">インタビュー: 2014/03/14</p>
<p class="txt">1979年4月21日生まれ。埼玉県出身。一橋大学商学部中退。大学在学中にECベンチャー「オイシックス」のインターンとしてスタートアップを経験。その後ブランド品のネットショップを立ち上げ、月間2,000万円の売り上げを達成するまでに成長。ECに大きな可能性を見出し、2004年有限会社ウェブデパを設立、代表取締役に就任する。2006年に社名を㈱もしもに変更し、ドロップシッピングによる新しいEC市場の確立を目指している。<br />
<a href="https://www.moshimo.com/" rel="nofollow" target="blank">もしもドロップシッピング</a></p>
<dl class="mod-dl-inline">
<dt>生年月日:</dt>
<dd>1979年</dd>
<dt>出身:</dt>
<dd>埼玉県</dd>
<dt>出身校:</dt>
<dd>一橋大学</dd>
</dl>
<div class="figure">
<img src="http://lvimg.jp/job-link/img/visionary/46/profile_image_circle_large.jpg" height="500" width="500" alt="" /> </div>
</div>
</div>
<div class="article-main">
<div class="article-block">
<div class="center-container">
<div class="txt">
<div class="section">
<h3>- 小さい時はどんなお子さんでしたか?</h3>
<p>一番古い記憶は、保育園の柵を乗り越えて逃げようとして、鉄条網に頭が引っかかり血だらけになった記憶です。それ以降ずーっと脱走癖があり、逃げなくなったのは社長になってからですかね(笑)。小学校4年生の時に『うわさのズッコケ株式会社』という本を読んで夢中になりました。仲良し3人組が釣り客相手にお弁当などを売るビジネスに着眼して、クラスメートからお金を集めて株式会社をつくるという話で、「会社をつくるって面白そうだ」と漠然と思いました。それに影響を受けて、家で手伝いの料金一覧表をつくり、細々とした家事仕事を母から請負ってお小遣いを稼いだほどです。</p>
</div>
<div class="section">
<h3>- 起業のきっかけはどのようなことだったんですか?</h3>
<p>経営の勉強をしようと大学に入り、在学中に起業を目指していた時に、インターネットベンチャーの有機野菜宅配「オイシックス」の立ち上げに参加しました。自分で野菜のコピーなどを考えて工夫すると、お客様が反応して買ってくれることにやり甲斐を感じました。当時、傷やサイズ不揃いで捨てられていたB級野菜を「ふぞろいの野菜たち」という名前で売り出して大ヒットしたのを見て、言葉ひとつで大きな違いが出ることを体感しました。1年半ほど勤めて、「もう起業できる!」と質屋のショップサイト運営を請負いました。実際は流通のことも、ネットショップのシステムの仕組みも分からず、ゼロから学びながら売上を伸ばしました。丁度流行り始めた価格comで全ての商品がギリギリ1位になるように設定し、最安店ランキング1位つまり「日本で一番ブランド品が安い店」と認知されるようになり、1年半で2億2,000万円くらい売り上げました。「モノを売る」楽しさをもっと人に伝えたいと思っていましたが、実際に販売するとなると商品梱包や伝票処理などの煩雑な仕事が大きなネック。アメリカではその面倒な部分を代わりにやってくれるというドロップシッピングのシステムがあると聞き、これは日本でも必要なサービスだと考え、2006年8月に“もしもドロップシッピング”のサービスを開始しました。</p>
</div>
<div class="section">
<h3>- モノを売る楽しさというのはどんな部分なのでしょうか?</h3>
<p>究極のコミュニケーションだと思っています。「この値段で売りたい」と商品を提示する売り手側と、「それがほしい」と思って購入する買い手側。その値段や商品が適していないと、相手には届かず買ってもらえない。お客さまの心に響いた時に、初めて「売買」につながるという部分が楽しいですね。</p>
</div>
<div class="section">
<h3>- 会社設立に際しては、どんな思いがありましたか?</h3>
<p>「個人の未来を応援する」という理念のもと、ブログやTwitterで情報発信するのと同じように「モノを売る」ことができるようにしたかったです。アメリカではドロップシッピングの会社は100社以上、1つの会社で扱える商品も100万点以上と規模は大きいんですが、売る側は「売り主」として住所掲載を義務づけられ、返品代金を負担したりとリスクも高い。日本でやるからには「大変な部分」と「リスク」、つまり法的な責任と返品商品を弊社で請負い、気軽に始められる環境を整備しなければなりませんでした。</p>
</div>
<div class="section">
<h3>- 今後、事業はどう展開される予定ですか?</h3>
<p>現在当社サービスを使われている会員が40万人、流通している商品も40万点。この規模を3年で100万人、100万商品にしたいと思っています。またTopSellerという新しいサービスは、楽天やYahoo!、STORES.jpなどの他社のショッピングカートで販売できるシステムです。昨年からYahoo!の出店料が無料になったので、TopSellerを使うとYahoo!の集客力も利用しながら、商品量も顧客層も増やせるので、さらに利用者増を目指しています。</p>
</div>
</div>
<div class="figure">
<img src="http://lvimg.jp/job-link/img/visionary/46/block1_image.jpg" width="380" alt="" /> </div>
</div>
</div>
<div class="article-block">
<div class="center-container">
<div class="txt">
<div class="section">
<h3>- ドロップシッピングで売上を増やすコツは?</h3>
<p>現在トップセールスの半数は主婦の方。SEOやブログ、メルマガなど皆さん独自の工夫があるようです。特別なスキルがなくても続けることで成果が出ること、家事や子育てをしながらでも合間の時間をかければ成果に比例することなどが、主婦会員が多い理由だと思います。その中でも目立つためには、見る人の役に立つコンテンツを多くすること。トップセールス常連のコスプレショップのオーナーさんは、他にはないコスプレのアイデアや実際に装着した写真などをたっぷり掲載しています。主婦の方が活躍する裏には、「コレいいわよ!」というおススメおばちゃん的な人の心に刺さるコメントが上手なことがあると思います。</p>
</div>
<div class="section">
<h3>- 会社のなかで大切にしている文化はどんなことでしょうか?</h3>
<p>会員様のなかには、弊社のドロップシッピングの収入で生活をしている会員様がたくさんいらっしゃいます。つまり弊社のビジネスと会員様たちの生活が直結している、「その責任は自分たちにある」という考えは社員隅々まで浸透させています。</p>
</div>
<div class="section">
<h3>- 起業を志す人へのメッセージをお願いします。</h3>
<p>起業はリスクもありますが、得られるものも多い。やりたい気持ちがあれば、できるだけ早くやった方がよいと思います。体力やエネルギーがあるうちに取りかかる方が有利なこと、守るものが多くなると踏み出せないことから、若い時の起業がおススメです。</p>
</div>
<div class="section">
<h3>- 失敗談はありますか?</h3>
<p>ドロップシッピングを開始した当初、物流費用をよく理解しておらずに失敗しました。商品が売れた時の利益より、梱包・出荷の代金の方が高くて、売れれば売れる程赤字という事態になったこと。立ち上げてすぐは、これで倒産しそうになりました。</p>
</div>
<div class="section">
<h3>- 座右の銘を教えてください。</h3>
<p>「男子三日会わざれば刮目してみよ」という三国志に出てくる言葉で、「若者に三日会わなければ目をよく見開いて見よ、なぜなら驚くほど成長しているから」という意味です。これに自分たちを重ねあわせ、自分たちの可能性を信じて急成長を目指したいですね。</p>
</div>
</div>
<div class="figure">
<img src="http://lvimg.jp/job-link/img/visionary/46/block2_image.jpg" width="380" alt="" /> </div>
<div class="article-footer">
<p class="interviewee">代表取締役<br>
<span>実藤裕史</span></p>
<ul class="sns">
<li><div class="fb-like" data-href="http://job.j-sen.jp/visionary/president/article/46/" data-layout="button_count" data-action="like" data-show-faces="false" data-share="true"></div></li>
<li><a href="https://twitter.com/share" class="twitter-share-button" data-url="http://job.j-sen.jp/visionary/president/article/46/" data-text="株式会社もしも 実藤裕史 モノを売る仕組みの提供で個人を応援! | ビジョナリー" data-width="107" data-lang="ja">ツイート</a></li>
<li><a href="http://b.hatena.ne.jp/entry/http://job.j-sen.jp/visionary/president/article/46/" class="hatena-bookmark-button" data-hatena-bookmark-title="株式会社もしも 実藤裕史 モノを売る仕組みの提供で個人を応援! | ビジョナリー" data-hatena-bookmark-layout="standard-balloon" data-hatena-bookmark-lang="ja" title="このエントリーをはてなブックマークに追加"><img src="http://b.st-hatena.com/images/entry-button/button-<EMAIL>" alt="このエントリーをはてなブックマークに追加" width="20" height="20"></a></li>
<li class="gplus"><div class="g-plusone" data-size="medium" data-href="http://job.j-sen.jp/visionary/president/article/46/"></div>
</li>
</ul>
</div>
<img src="http://lvimg.jp/job-link/img/visionary/46/profile_image_footer.jpg" height="340" width="1000" alt="" /> </div>
</div>
</div>
<div class="center-container">
<div class="section">
<h2 class="mod-heading01">他の経営者インタビュー</h2>
<div class="mod-col4">
<div class="item">
<div class="figure">
<a href="/visionary/president/article/17/"><img src="http://lvimg.jp/job-link/img/visionary/17/profile_image_circle_middle.jpg" height="120" width="120" alt="" /></a>
</div>
<h3><a href="/visionary/president/article/17/">ベンチャービジネスを支援する法律事務所</a></h3>
<p class="mod-txt-muted">GVA法律事務所<br>
<em>山本俊</em></p>
</div>
<div class="item">
<div class="figure">
<a href="/visionary/president/article/133/"><img src="http://lvimg.jp/job-link/img/visionary/133/profile_image_circle_middle.jpg" height="120" width="120" alt="" /></a>
</div>
<h3><a href="/visionary/president/article/133/">顧客の課題を「可視化」し、新たな価値を見つけだす</a></h3>
<p class="mod-txt-muted">株式会社ウィナス<br>
<em>浜辺拓</em></p>
</div>
<div class="item">
<div class="figure">
<a href="/visionary/president/article/118/"><img src="http://lvimg.jp/job-link/img/visionary/118/profile_image_circle_middle.jpg" height="120" width="120" alt="" /></a>
</div>
<h3><a href="/visionary/president/article/118/">メールが変れば会社が変わるマナー向上で広がるチャンス</a></h3>
<p class="mod-txt-muted">株式会社アイ・コミュニケーション<br>
<em>平野友朗</em></p>
</div>
<div class="item">
<div class="figure">
<a href="/visionary/president/article/49/"><img src="http://lvimg.jp/job-link/img/visionary/49/profile_image_circle_middle.jpg" height="120" width="120" alt="" /></a>
</div>
<h3><a href="/visionary/president/article/49/">「女性」×「ソーシャルメディア」で新たなライフスタイルを提案</a></h3>
<p class="mod-txt-muted">トレンダーズ株式会社<br>
<em>経沢香保子</em></p>
</div>
</div>
</div>
</div>
</div>
<div id="footer">
<div class="area1">
<div class="center-container">
<div class="section">
<h2>関連リンク</h2>
<ul>
<li><a href="https://j-sen.jp/" target="_blank">アルバイトならジョブセンス</a></li>
<li><a href="http://haken.j-sen.jp/" target="_blank">派遣の求人ならジョブセンス派遣</a></li>
<li><a href="http://chintai.door.ac/" target="_blank">賃貸情報ならdoor賃貸</a></li>
<li><a href="https://jobtalk.jp/" target="_blank">転職のクチコミなら転職会議</a></li>
<li><a href="https://imitsu.jp/" target="_blank">比較・見積もりサイトならアイミツ</a></li>
<li><a href="https://syukatsu-kaigi.jp/" target="_blank">就職活動なら就活会議</a></li>
</ul>
</div>
<div class="section">
<h2>転職コンテンツ</h2>
<ul>
<li><a href="http://job.j-sen.jp/jobpedia/index.htm" target="_blank">職種大辞典</a></li>
<li><a href="http://job.j-sen.jp/qualificationpedia/index.htm" target="_blank">資格大辞典</a></li>
<li><a href="http://job.j-sen.jp/hellowork/index.htm" target="_blank">ハローワークPedia</a></li>
<li><a href="http://job.j-sen.jp/contents/syokureki.htm" target="_blank">職務経歴書の書き方</a></li>
<li><a href="http://job.j-sen.jp/contents/rirekisyo.htm" target="_blank">履歴書の書き方</a></li>
<li><a href="http://job.j-sen.jp/contents/interview.htm" target="_blank">面接Q&A</a></li>
</ul>
</div>
<div class="section about">
<h2><span>ABOUT</span>
<a href="/visionary/president/guide/">ビジョナリーとは?</a></h2>
<p class="mod-txt-muted">ビジョナリーは、様々な分野で活躍している「ビジョナリー=先見の明をもつ優れた経営者」のインタビューを集めたサイトです。<br>
『世の中の魅力あふれる経営者の想いやエピソードを発信し、より多くの人に伝えていきたい』<br>
ビジョナリーには、そんな想いが込められています。<br>
<a href="https://job.j-sen.jp/support/ask.htm?category=7">インタビュー掲載をご希望の企業様へ</a></p>
</div>
<ul class="sns">
<li><div class="fb-like" data-href="http://job.j-sen.jp/visionary/president/" data-layout="button_count" data-action="like" data-show-faces="false" data-share="true"></div></li>
<li><a href="https://twitter.com/share" class="twitter-share-button" data-url="http://job.j-sen.jp/visionary/president/" data-text="経営者インタビューサイト【ビジョナリー】 | 転職ならジョブセンスリンク" data-width="107" data-lang="ja">ツイート</a></li>
<li><a href="http://b.hatena.ne.jp/entry/http://job.j-sen.jp/visionary/president/" class="hatena-bookmark-button" data-hatena-bookmark-title="経営者インタビューサイト【ビジョナリー】 | 転職ならジョブセンスリンク" data-hatena-bookmark-layout="standard-balloon" data-hatena-bookmark-lang="ja" title="このエントリーをはてなブックマークに追加"><img src="http://b.st-hatena.com/images/entry-button/[email protected]" alt="このエントリーをはてなブックマークに追加" width="20" height="20"></a></li>
<li class="gplus"><div class="g-plusone" data-size="medium" data-href="http://job.j-sen.jp/visionary/president/"></div>
</li>
</ul>
</div>
</div>
<div class="area2">
<div class="center-container">
<p class="logo">powered by<br>
<a href="http://job.j-sen.jp/" target="_blank"><img src="/img/visionary/president/logo_footer.png" height="29" width="206" alt="ジョブセンスリンク(転職サイト)"></a></p>
<p class="mod-txt-s">推奨ブラウザ:Internet Explorer9.0以降 Safari Firefox4以降 Google Chrome<br>
※上記以外のブラウザでは最適なレイアウトで閲覧できない可能性がございます。</p>
<p><small>Copyright (C) Livesense Inc.</small></p>
</div>
</div>
</div>
<div id="to-top"><img src="/img/visionary/president/img_totop.png" height="48" width="48" alt=""></div>
<div id="fb-root"></div>
<script>
;(function (w, d) {
w.___gcfg = {lang: 'ja'};
var s, e = d.getElementsByTagName('script')[0],
a = function (u, i) {
if (!d.getElementById(i)) {
s = d.createElement('script');
s.src = u;
if (i) {s.id = i;}
e.parentNode.insertBefore(s, e);
}
};
a('//connect.facebook.net/ja_JP/all.js#xfbml=1', 'facebook-jssdk');
a('//platform.twitter.com/widgets.js', 'twitter-wjs');
a('//b.st-hatena.com/js/bookmark_button_wo_al.js');
a('https://apis.google.com/js/plusone.js');
})(this, document);
</script>
</body>
</html>
<file_sep>/js/index.js
void function($) {
$(
function(event) {
// {{{ メイン画像のスライダー
$( '#main-img' ).backstretch([
'http://image.' + Mdk.DOMAIN + '/static/img/ds/www/index/img-catch.jpg',
'http://image.' + Mdk.DOMAIN + '/static/img/ds/www/index/img-main02.jpg',
'http://image.' + Mdk.DOMAIN + '/static/img/ds/www/index/img-main03.jpg',
'http://image.' + Mdk.DOMAIN + '/static/img/ds/www/index/img-main01.jpg',
'http://image.' + Mdk.DOMAIN + '/static/img/ds/www/index/img-main04.jpg'
], {duration: 5000, fade: 1000});
// }}}
}
);
}(jQuery);
<file_sep>/js/1.0.0_1.js
/**
* jQuery.util - jQuery Plugin
*
* Under The MIT License
* Copyright (c) 2011 <NAME>. (http://monry.jp/)
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
* OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Version: 1.0.0
* Revision: $Rev$
* Date: $Date$
*/
(
function($) {
$.extend(
{
'stripTags': function(text) {
return $('<div>').html(text).text();
},
'escapeHTML': function(text) {
return $('<div>').text(text).html();
}
}
);
$.fn.extend(
{
'replaceAttr': function(attribute_name, pattern, replacement) {
$(this).each(
function(index, element) {
$(element).attr(attribute_name, ($(element).attr(attribute_name) || '').replace(pattern, replacement));
}
);
return this;
}
}
);
}
)(jQuery);
| c7cbd77d337797fab641b4413d422f32b5b97542 | [
"JavaScript",
"HTML"
] | 7 | JavaScript | wDiff/moshimo.com | 3d77f114d6aac2971b8fc82db5d9e9f2ac230f4a | 0b887611bab12b1e0f8f5f1deb84412b32ee4eb8 | |
refs/heads/master | <repo_name>MPinpa/vagapython<file_sep>/app.py
def quantidade(tipo: list, troco_restante: float) -> list:
"""
Quantidade de notas e moedas do troco recebido.
"""
tipo_de_valor = "cedulas"
if troco_restante < 1 and troco_restante > 0:
tipo_de_valor = "moedas"
valores_usados = []
for valor in tipo:
if troco_restante - valor < 0:
continue
else:
quantidade_de_valores = int(troco_restante / valor)
troco_restante = troco_restante - valor * quantidade_de_valores
cont = 0
while cont < quantidade_de_valores:
valores_usados.append(valor)
cont += 1
return {tipo_de_valor: valores_usados, "troco": troco_restante}
def vender(valor_produto: float, valor_pago: float) -> dict:
"""
função responsavel pela venda do produto e trazer o troco.
retorna o
"""
troco = valor_produto - valor_pago
if troco <= 0:
troco = troco * - 1
else:
return "Falta Dinheiro"
cedulas = [100, 50, 10, 5, 1]
moedas = [0.50, 0.10, 0.05, 0.01]
notas = quantidade(cedulas, troco)
moedas = quantidade(moedas, notas['troco'])
return {"troco": troco, "notas": notas["cedulas"], "moedas": moedas["moedas"]}
print(vender.__annotations__)
| bfb14b5aff4d248fea71e57d6076652439e9ad04 | [
"Python"
] | 1 | Python | MPinpa/vagapython | 04a132c0c31e5e8f1c7bcdb1d7f3331eaddc7fee | 89c6194aa16c19cfd498b13f1f2edda1ffea86f0 | |
refs/heads/master | <file_sep>ProGauge-in-Java
================
The original project in java<file_sep>import java.lang.*;
import java.lang.reflect.*;
import java.util.*;
import com.google.gson.*;
//import com.google.gson.*;
import com.google.gson.JsonElement.*;
import com.google.gson.JsonArray.*;
import com.google.gson.Gson;
/*
* file: Tester.java
*
* This is a control file to test my code for the Junior Delvoper position at ProGauge.
*
* @author <NAME>
* @see HashMap
* @see Arrays
* @see Vector
* @see Calendar
* @see Collection
* @see Iterator
*
########## DO NOT EDIT ABOVE THIS LINE ########## */
public class Tester
{
/*
* <p>Function RunProgram
* Run Program takes an incoming list of Devices and processes them
* to produce an indexed output List.
*
* <p> Notes, This implementation takes in a list of devices. The devices are copied into an Array.
* The array is then sorted using Arrays.sort(); The logic for the sort can be found in the
* Device subclasses(NumericalDevice and StateDevice) in the compareTo functions. The data is sorted by timeStamps
* simplifying the Accumulate process. The sorted array is then used to replace the data in Vector DeviceList.
*
* <p> The devices are now sorted by their recorded TimeStamp and can now be processed.
* The data is processed by indexing the device names. On the first occurrence of a device
* The Object device is recorded into a hashmap. The hashmap allows easy tracking of first occurrence
* of each device. In the event of additional occurrences of any given device, the data from the additional
* occurrence is appended to the existing Device object and the additional occurrence is dropped.
* Any occurrence of a device that is not dated for the current date, is rejected from the list and ignored.
*
*
*
* <p> Finally the Devices stored in the hashmap (the orginal list has now been been condensed) are copied back into an array where they are
* sorted by their Tag_Name. Then the array is passed back as output.
*
* @parm deviceList list of devices to be processed
* @return Device[] List of processed devices sorted by their Tag_Name
*/
public Device[] RunProgram(Vector<Device> deviceList)
{
HashMap<String,Device> myMap = new HashMap<String,Device>();
int inputDeviceCount = deviceList.size() -1;
Device deviceProcessor = new Device();
Calendar TimeStamp = new GregorianCalendar();
String testDate = new String(TimeStamp.get(Calendar.YEAR) + "" + TimeStamp.get(Calendar.MONTH) + "" + TimeStamp.get(Calendar.DAY_OF_MONTH));
Collection<Device> myViewer;
Device[] outList;
int counter = 0;
outList = new Device[deviceList.size()];
deviceList.toArray(outList);
Arrays.sort(outList);
Arrays.sort(outList);
counter = 0;
deviceList.clear();
while(counter <= inputDeviceCount)
{ deviceList.add(outList[counter]);
counter++;
}
counter = 0;
while(counter <= inputDeviceCount)
{
deviceProcessor = deviceList.get(counter);//;inputDeviceCount);
counter++;//inputDeviceCount--;
if(deviceProcessor.isCurrent())
{
if(!myMap.containsKey(deviceProcessor.getTagName()))
{
myMap.put(deviceProcessor.getTagName(),deviceProcessor);
}
else
{
Device temp = myMap.get(deviceProcessor.getTagName());
if(deviceProcessor.equals(myMap.get(deviceProcessor.getTagName())))
{
temp.Accumulate(deviceProcessor);
myMap.remove(deviceProcessor.getTagName());
myMap.put(deviceProcessor.getTagName(),temp);
}
else
{
System.out.println("type miss match error");//+ deviceProcessor.getType() +" -->" + temp.getType());
}
}
}
}
myViewer = myMap.values();
outList = new Device[myMap.size()];
counter = 0;
Iterator<Device> iter = myViewer.iterator();
while (iter.hasNext())
{
Object reader = iter.next();
outList[counter++] = (Device) reader;
}
Arrays.sort(outList);
return outList;
}
/*
* Function Main
* <p> Notes, Generates and stores several Devices into a vector, the vector is then
* passed into the RUNPROGRAM function. The purpose of this is to set up conditons
* to test this programm.
*
*
*
*/
public static void main (String[] args)
{
Device test = new Device();
Vector<Device> myList = new Vector<Device>();
Device generator = new Device();
Tester testme =new Tester();
int counter;
Device[] outList;
String testToken;
Gson mySon = new Gson();
JsonObject temp = new JsonObject();
int numOfTags;
myList.add(generator = new NumericalDevice("Pump2","39.4362",6,9,5,0));
myList.add(generator = new NumericalDevice("AWT3","510",6,9,5,0));
myList.add(generator = new NumericalDevice("Exhaust2","1537.164",6,9,5,0));
myList.add(generator = new StateDevice("Cooler2","ON" ,6,9,5,0));
myList.add(generator = new StateDevice("Cooler2","OFF" ,6,9,3,0));
myList.add(generator = new StateDevice("Cooler2","OFF" ,6,9,9,1));
myList.add(generator = new StateDevice("Cooler2","ON",6,9,1,0));
myList.add(generator = new StateDevice("Cooler1","on" ,6,1,9,1));
myList.add(generator = new StateDevice("Heater5","active",6,9,5,0));
myList.add(generator = new StateDevice("PRS2","FAIL" ,6,9,5,0));
myList.add(generator = new StateDevice("PRS1","Active" ,6,9,6,0));
myList.add(generator = new StateDevice("PRS1","INACTIVE",6,9,7,0));
myList.add(generator = new StateDevice("GPS","BakersField",6,9,5,1));
outList = testme.RunProgram(myList);
numOfTags = Array.getLength(outList);
counter = 0;
while(counter < numOfTags)
{
if(outList[counter].getType() == 0)
temp.addProperty(outList[counter].getTagName(),outList[counter].getFloatData());
else
temp.addProperty(outList[counter].getTagName(),outList[counter].getStringData());
counter++;
}
String outputString = mySon.toJson(temp);
outputString = outputString.replaceAll(",",",\n" + " " );
outputString = outputString.replaceAll("\\{","\\{\n" +" ");
outputString = outputString.replaceAll(":",": ");
outputString = outputString.replaceAll("}",",\n}");
StringTokenizer output2 = new StringTokenizer(outputString,", ",true);
while(output2.hasMoreTokens())
{
testToken = output2.nextToken();
System.out.print(testToken);
}
}
}
<file_sep>import java.*;
import java.lang.*;
import java.util.*;
import com.google.gson.*;
import com.google.*;
public class StateDevice extends Device implements Comparable //implements DeviceInterface
{
private String tagName;
private String stringData;
private int deviceType = 1;
StateDevice(String tag,String data)
{
tagName = tag;
Boolean result = false;
stringData = data;
}
StateDevice(String tag,String data,int month,int day,int hour, int am_pm)
{
tagName = tag;
Boolean result = false;
stringData = data;
timeStamp.set(Calendar.MONTH,month);
timeStamp.set(Calendar.DATE,day);
timeStamp.set(Calendar.HOUR,hour);
timeStamp.set(Calendar.AM_PM,am_pm);
}
public String getData()
{
return stringData;
}
public void Accumulate(Device merge)
{
StateDevice temp = (StateDevice) merge;
stringData = (stringData + "\n" + temp.getStringData());
}
public String getStringData()
{
return stringData.toString();
}
public int compareTo(Object otherDevice)
{
/*
If passed object is of type other than Device, throw ClassCastException.
*/
if(!(otherDevice instanceof Device))
{
throw new ClassCastException("Invalid object");
}
String cTagName = ((Device) otherDevice).getTagName();
if(this.getTagName().compareToIgnoreCase(cTagName) !=0)
{
return((this.getTagName()).compareToIgnoreCase(cTagName));
}
if( ((StateDevice) otherDevice).getAM_PM() - this.getAM_PM() != 0)
{
return( (this.getAM_PM()) - ((StateDevice) otherDevice).getAM_PM());
}
return(this.getHour() - ((StateDevice) otherDevice).getHour() );
}
private int getAM_PM()
{ return this.timeStamp.get(Calendar.AM_PM);}
private int getHour()
{
return timeStamp.get(Calendar.HOUR);
}
public int getDay()
{
return this.timeStamp.get(Calendar.DATE);
}
public int getMonth()
{
return this.timeStamp.get(Calendar.MONTH);
}
public String getTagName()
{
return tagName.toString();
}
public Boolean equals(Device otherDevice)
{
if (otherDevice.getType() == this.getType())
return true;
return false;
}
public int getType()
{return deviceType;}
public String toString()
{
return(tagName.toString() + " " + stringData.toString());
}
public JsonObject toJson()
{
Gson mySon = new Gson();
JsonObject temp = new JsonObject();
temp.addProperty(tagName,stringData);
return temp;
}
public void SetData()
{}
}
<file_sep>public interface DeviceInterface
{
void GetData();
void SetData();
void Accumulate();
}
| 9840e497ae136a301129d513f2eb14131fc279ed | [
"Markdown",
"Java"
] | 4 | Markdown | DanielHaro/ProGauge-in-Java | f8812ad1f97b636808bb9a9a12619e2a638e3769 | 504e6706e426f3fa9d342c607cb9b250777585e7 | |
refs/heads/master | <repo_name>wannasmile/FlashAnimationToAndroid<file_sep>/settings.gradle
include ':app', ':fatalib'
<file_sep>/fatalib/src/main/java/org/osdg/fata/FlashAnimationView.java
package org.osdg.fata;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by plter on 9/24/15.
*/
public class FlashAnimationView extends SurfaceView {
private JSONArray configFramesArray = null;
private List<FlashAnimationFrame> frames = new ArrayList<>();
private double fps = 20;
private boolean released = false;
private Bitmap bitmap = null;
private Timer timer = new Timer();
private TimerTask task = null;
private boolean playing = false;
private int delay = 50;
private int currentFrameIndex = 0;
private boolean autoPlay = false;
private boolean repeat = true;
private SurfaceHolder.Callback surfaceViewHolderCallback = new SurfaceHolder.Callback() {
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (isAutoPlay()){
start();
}
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
stop();
}
};
public FlashAnimationView(Context context, int drawableId, int configId) {
this(context, drawableId, configId, 20, true, true);
}
public FlashAnimationView(Context context, int drawableId, int configId, float fps, boolean autoPlay, boolean repeat) {
super(context);
InputStream in = context.getResources().openRawResource(configId);
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
StringBuilder content = new StringBuilder();
String line = null;
while ((line = br.readLine()) != null) {
content.append(line);
}
initWithDrawableAndConfigJSON(BitmapFactory.decodeResource(context.getResources(), drawableId), new JSONObject(content.toString()), fps, autoPlay, repeat);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
throw new RuntimeException("UnsupportedEncodingException");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException");
} catch (JSONException e) {
e.printStackTrace();
}
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("IOException");
}
}
public FlashAnimationView(Context context, Bitmap drawable, JSONObject jsonObject, float fps) {
super(context);
initWithDrawableAndConfigJSON(drawable, jsonObject, fps, true, true);
}
public FlashAnimationView(Context context, Bitmap drawable, JSONObject jsonObject) {
super(context);
initWithDrawableAndConfigJSON(drawable, jsonObject, 20, true, true);
}
private void initWithDrawableAndConfigJSON(Bitmap bitmap, JSONObject jsonObject, double fps, boolean autoPlay, boolean repeat) {
try {
setFps(fps);
setAutoPlay(autoPlay);
setRepeat(repeat);
configFramesArray = jsonObject.getJSONArray("frames");
for (int i = 0; i < configFramesArray.length(); i++) {
frames.add(new FlashAnimationFrame(configFramesArray.getJSONObject(i).getJSONObject("frame")));
}
this.bitmap = bitmap;
System.out.println(bitmap.getWidth() + "," + bitmap.getHeight());
getHolder().addCallback(surfaceViewHolderCallback);
} catch (JSONException e) {
e.printStackTrace();
throw new RuntimeException("Wrong config file!");
}
}
public void setFps(double fps) {
this.fps = fps;
delay = (int) (1000 / fps);
}
public double getFps() {
return fps;
}
public void play() {
if (!playing) {
task = new TimerTask() {
@Override
public void run() {
drawFrame();
}
};
timer.schedule(task, delay, delay);
playing = true;
}
}
public void start() {
currentFrameIndex = 0;
play();
}
public void stop() {
if (playing) {
pause();
currentFrameIndex = 0;
}
}
private void pause() {
if (playing) {
task.cancel();
playing = false;
}
}
private void drawFrame() {
if (currentFrameIndex >= frames.size()) {
currentFrameIndex = 0;
if (!isRepeat()){
stop();
}
}
Canvas canvas = getHolder().lockCanvas();
if (canvas!=null) {
canvas.save();
canvas.drawColor(Color.TRANSPARENT, PorterDuff.Mode.CLEAR);
frames.get(currentFrameIndex).drawOnCanvas(bitmap, canvas);
currentFrameIndex++;
canvas.restore();
getHolder().unlockCanvasAndPost(canvas);
}
}
public boolean isPlaying() {
return playing;
}
/**
* Release the bitmap data
*/
public void release() {
bitmap.recycle();
released = true;
}
public boolean isReleased() {
return released;
}
public void setAutoPlay(boolean autoPlay) {
this.autoPlay = autoPlay;
}
public boolean isAutoPlay() {
return autoPlay;
}
public void setRepeat(boolean repeat) {
this.repeat = repeat;
}
public boolean isRepeat() {
return repeat;
}
}
<file_sep>/README.md
# FlashAnimationToAndroid
fata(Flash animation to android)
[使用视频教程](http://www.tudou.com/programs/view/SuJbORhqJPY/)<file_sep>/fatalib/src/main/java/org/osdg/fata/FlashAnimationFrame.java
package org.osdg.fata;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by plter on 9/25/15.
*/
class FlashAnimationFrame {
private int x, y, width, height;
private Rect sourceRect = new Rect(0, 0, 0, 0), distRect = new Rect(0, 0, 0, 0);
private Paint paint = new Paint();
FlashAnimationFrame(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
sourceRect.set(x, y, x + width, y + height);
distRect.set(0, 0, width, width);
}
FlashAnimationFrame(JSONObject frameJsonObject) throws JSONException {
this(frameJsonObject.getInt("x"), frameJsonObject.getInt("y"), frameJsonObject.getInt("w"), frameJsonObject.getInt("h"));
}
public void drawOnCanvas(Bitmap source, Canvas canvas) {
canvas.save();
canvas.drawBitmap(source,sourceRect,distRect,paint);
canvas.restore();
}
}
| bd48edeecf88b519809bb0922c60d39873ef4c14 | [
"Markdown",
"Java",
"Gradle"
] | 4 | Gradle | wannasmile/FlashAnimationToAndroid | 2e3d790ae98aace1b6035a6aaaa02a071723fb4f | 0f46fa8dba7553f47d3ba6649819e2531a47caba | |
refs/heads/master | <file_sep><?php
$post = $_POST;
echo json_encode($post);<file_sep>// <?php
// $db = new SQLite3('test.db');
// // class myDB extends SQLite3
// // {
// // function __construct()
// // {
// // $this->open('test.db');
// // }
// // }
// // $db = new MyDB();
// // if(!$db){
// // echo $db->lastErrorMsg();
// // } else {
// // echo "Opened database successfully\n";
// // }
// // $sql =<<<EOF
// // CREATE TABLE COMPANY
// // (ID INT PRIMARY KEY NOT NULL,
// // NAME TEXT NOT NULL,
// // AGE INT NOT NULL,
// // ADDRESS CHAR(50),
// // SALARY REAL);
// // EOF;
// // $db->exec($sql);
// // $sql =<<<EOF
// // INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
// // VALUES (1, 'Paul', 32, 'California', 20000.00 );
// // INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
// // VALUES (2, 'Allen', 25, 'Texas', 15000.00 );
// // INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
// // VALUES (3, 'Teddy', 23, 'Norway', 20000.00 );
// // INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY)
// // VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 );
// // EOF;
// // $ret = $db->exec($sql);
// // if(!$ret){
// // echo $db->lastErrorMsg();
// // } else {
// // echo "Records created successfully\n";
// // }
// // $db->close();
// $sql =<<<EOF
// SELECT * from COMPANY;
// EOF;
// $ret = $db->query($sql);
// while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
// echo "ID = ". $row['ID'] . "\n";
// echo "NAME = ". $row['NAME'] ."\n";
// echo "ADDRESS = ". $row['ADDRESS'] ."\n";
// echo "SALARY = ".$row['SALARY'] ."\n\n";
// }
// echo "Operation done successfully\n";
// $db->close();
header('Content-Type:text/html;charset=utf-8');
// define("mDELETE",8);
// define("mUPLOAD",4);
// define("mWRITE",2);
// define("mREAD",1);
// $key = 13;//13=8+4+1
// if($key & mDELETE)
// echo "有删除权限<br />"
// ; //8
// if($key & mUPLOAD)
// echo "有上传权限<br />"
// ;//4
// $a=$key & mWRITE;
// echo "有写权限<br />
// ".$a; //无此权限
// if($key & mREAD)
// echo "有读权限<br />
// "; //1
// $x=3;
// $y=5;
// echo ($x&$y)+(($x^$y)>>1).'<br />';
// echo ($x&$y).'<br />';
// echo (($x^$y)>>1).'<br />';
$url = 'http://www.jb51.net/article/22720.htm';
if (function_exists('file_get_contents')) {
$file_content = @file_get_contents($url);
} elseif (ini_get('allow_url_fopen') && ($file = @fopen($url, 'rb'))){
$i = 0;
while (!feof($file) && $i++ < 1000) {
$file_content .= strtolower(fread($file, 4096));
}
fclose($file);
} elseif (function_exists('curl_init')) {
$curl_handle = curl_init();
curl_setopt($curl_handle, CURLOPT_URL, $url);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_FAILONERROR,1);
curl_setopt($curl_handle, CURLOPT_USERAGENT, 'Trackback Spam Check'); //引用垃圾邮件检查
$file_content = curl_exec($curl_handle);
curl_close($curl_handle);
} else {
$file_content = '';
}
echo $file_content;
<file_sep><?php
$callback = $_GET['callback'];
$data = array(1, 2, 3);
echo $callback.'('.json_encode($data).')';
<file_sep><?php
class Test extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$this->load->Model('test');
echo('ok');
}
}
<file_sep><?php
class email
{
}
$('#pp_tabs a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
var pane_sel = $(e.target).attr('href');
switch (pane_sel) {
case '#comment':
$(this).off('shown.bs.tab');
$(pane_sel).load('<{link app=b2c ctl=site_comment act=show args0=$data_detail.goods_id}>');
$(pane_sel).on('click', 'a', function (e) {
e.stopPropagation();
$(pane_sel).load(this.href);
});
break;
}
})<file_sep><?php
use framework\web\helpers\CHtml;
echo 'ok';
CHtml::encode($message)?><file_sep><?php
class Test extends CI_Model {
function __construct() {
parent::__construct();
}
function read($id){
$query = $this->db->get('newstable',$id);
return $query;
}
}<file_sep><?php
$url = 'http://e.jb51.net/';
//echo $url, '<br />';
//echo(preg_replace('/http\:\/\/e\.jb51\.net\//', 'http://e.jb51.net/w3c/', $url));
//匹配邮箱
//"^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$"
//'\s' 匹配任何空白字符,包括空格、制表符、换页符等等。
//'\w' 匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”。
$preg = '/^[A-Z]/';
$array = array('ABC', 'abc', 'Abc', '123');
$result = preg_grep($preg, $array, PREG_GREP_INVERT);
var_dump($result);<file_sep><?php
// +----------------------------------------------------------------------
// | memCache
// +----------------------------------------------------------------------
$memcache = new Memcache;
$memcache ->connect( "localhost" ,11211); #根据情况要把 "localhost" 改为 "127.0.0.1"
echo "Server's version: " . $memcache ->getVersion() . "<br />\n" ;
$tmp_object = new stdClass;
$tmp_object ->str_attr = "test" ;
$tmp_object ->int_attr = 123;
$memcache ->set( "key" , $tmp_object ,false,10);
echo "Store data in the cache (data will expire in 10 seconds)<br />\n" ;
echo "Data from the cache:<br />\n" ;
var_dump( $memcache ->get( "key" ));<file_sep>UPDATE config SET confvalue='4.12' WHERE confname='VersionNumber';
<file_sep><?php
header("Content-Type:text/html;charset=utf-8");
class sendSms
{
private $_url = 'http://api2.santo.cc/submit?command=MT_REQUEST&cpid=test1&cppwd=<PASSWORD>1<PASSWORD>';
private $_fileds = Array();
protected $method = 'POST';
private $_uName = 'test1';
private $_pwd = '<PASSWORD>';
/*
public function __construct($params)
{
$this->_fileds = $params;
}
*/
public function send()
{
//if(empty($this->fileds)) return array();
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
//$this->_url .= '&da=8615221546554&dc=15&sm=d1e9d6a4c2eb31323334';
/*if($this->method == 'post')
{
curl_setopt($ch, CURL_POST, true);
curl_setopt($ch, CURL_POSTFILEDS, $this->fileds);
}
else
{
$this->_url .= '?';
}*/
curl_setopt($ch, CURLOPT_URL, $this->_url);
//curl_setopt($ch, CURLOPT_URL, 'http://dev.msk.com');
$result = curl_exec($ch);
//$content = curl_getinfo($ch);
curl_close($ch);
return $result;
}
}
$sms = new sendSms();
echo '<pre>';
print_r($sms->send());<file_sep><?php
$data1 = array(
'0' => array(
'store' => array(
'id' => '1',
'name' => '幻灯1',
'url' => 'aaaa'
),
)
);
$data2 = array(
'store' => array(
'id' => '2',
'name' => '幻灯2',
'url' => 'bbbb'
),
);
echo('<pre>');
array_unshift($data1, $data2);
print_r($data1);
?><file_sep><?php
function m($s, $z)
{
echo $s;
$y = $z();
var_dump($z);
var_dump($y);
}
$x = m (1, $v=function(){return 2;});
echo $x;<file_sep><?php
return array(
'VERSION'=>'0.5.1',
'RELEASE'=>'20150511',
);<file_sep>
<?php
header('Content-Type:text/html;charset=utf-8');
$fp = fopen("demo_csv.csv","a"); //打开csv文件,如果不存在则创建
$data_arr1 = array("10001","10002","10003","10004","10005"); //第一行数据
$data_arr2 = array("20001","20002","20003","20004","20005"); //第二行数据
$data_str1 = implode(",",$data_arr1); //用 ' 分割成字符串
$data_str2 = implode(",",$data_arr2); //用 ' 分割成字符串
$data_str = $data_str1."\r\n".$data_str2."\r\n"; //加入换行符
fwrite($fp,$data_str); //写入数据
fclose($fp); //关闭文件句柄
echo "生成成功";
$open = fopen('test.txt','r');
//var_dump(filesize('test.txt'));exit;
$content = fread($open, filesize('test.txt'));
fclose($open);
var_dump($content);
?><file_sep><?php
header('Content-Type:text/html;charset=utf-8');
$content = file_get_contents('demo.csv');
$csv = fopen('demo.csv', 'r');
//while(){
// $contentCsv = fgetcsv($csv);
// var_dump($contentCsv);
//}
echo(2<<1).'<br/>';
echo(2<<2).'<br/>';
echo(2<<3).'<br/>';
echo(2<<4).'<br/>';
<file_sep><?php
header('Content-Type:text/html; charset=utf-8');
$items = array(
1 => array('id' => 1, 'pid' => 0, 'name' => '安徽省'),
2 => array('id' => 2, 'pid' => 0, 'name' => '浙江省'),
3 => array('id' => 3, 'pid' => 1, 'name' => '合肥市'),
4 => array('id' => 4, 'pid' => 3, 'name' => '长丰县'),
5 => array('id' => 5, 'pid' => 1, 'name' => '安庆市'),
6 => array('id' => 6, 'pid' => 0, 'name' => '湖南省'),
);
function generateTree($items){
$tree = array();
foreach($items as $item){
if(isset($items[$item['pid']])){ // itemrs[0][] =
$items[$item['pid']]['son'][] = &$items[$item['id']];
}else{
$tree[] = &$items[$item['id']];
}
}
//print_r($items);
return $tree;
}
function generateTree1($items){
foreach($items as $key => $item){
$items[$item['pid']]['son'][$item['id']] = &$items[$item['id']];
}
return isset($items[0]['son']) ? $items: array();
}
//echo '<pre>=========================================';
//print_r(generateTree($items));
//echo '=====================================';
//print_r(generateTree1($items));
/*
$tree = generateTree($items);
function getTreeData($tree){
foreach($tree as $t){
echo $t['name'].'<br>';
if(isset($t['son'])){
getTreeData($t['son']);
}
}
}
getTreeData($tree);
*/
// echo '<pre>';
// print_r(generateTree($items));
/*
$arr = array("one", "two", "three");
foreach ($arr as &$value) {
echo "Value: $value<br />\n";
}
echo $value.'<br />'; //three
foreach ($arr as $value) {
echo "Value: $value<br />\n";
}
echo $value.'<br />';
*/
$params = array(
'name' => 'aaa',
'age' => '22',
'sex' => '1',
'scores' => '99',
);
$config = array(
'age' => '',
'name' => '',
'scores' => '',
'sex' => '',
'height' => ''
);
array_walk($config, 'study', $params);
function study(&$v, $k, $p)
{
if(@$p[$k])
{
$v = $p[$k];
}else{
unset($k);
}
}
print_r($config);<file_sep><!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>悟空CRM安装向导</title>
<link rel="stylesheet" href="./css/install.css?v=9.0" />
</head>
<body>
<div class="wrap">
<?php require './templates/header.php'; ?>
<div class="section">
<div><img src="./images/install4.jpg" style="width:750px;"></div>
<div class="main cc">
<pre class="pact" readonly="readonly">
建立数据表 pre_common_domain ... 成功
建立数据表 pre_common_failedip ... 成功
建立数据表 pre_common_failedlogin ... 成功
建立数据表 pre_common_friendlink ... 成功
建立数据表 pre_common_grouppm ... 成功
建立数据表 pre_common_invite ... 成功
建立数据表 pre_common_magic ... 成功
建立数据表 pre_common_magiclog ... 成功
建立数据表 pre_common_mailcron ... 成功
建立数据表 pre_common_mailqueue ... 成功
建立数据表 pre_common_member ... 成功
建立数据表 pre_common_member_action_log ... 成功
建立数据表 pre_common_member_connect ... 成功
建立数据表 pre_common_member_count ... 成功
建立数据表 pre_common_member_crime ... 成功
建立数据表 pre_common_member_field_forum ... 成功
建立数据表 pre_common_member_field_home ... 成功
建立数据表 pre_common_member_forum_buylog ... 成功
建立数据表 pre_common_member_grouppm ... 成功
建立数据表 pre_common_member_log ... 成功
建立数据表 pre_common_member_magic ... 成功
建立数据表 pre_common_member_medal ... 成功
建立数据表 pre_common_member_newprompt ... 成功
建立数据表 pre_common_member_profile ... 成功
建立数据表 pre_common_member_profile_setting ... 成功
建立数据表 pre_common_member_security ... 成功
建立数据表 pre_common_member_secwhite ... 成功
建立数据表 pre_common_member_stat_field ... 成功
建立数据表 pre_common_member_status ... 成功
建立数据表 pre_common_member_validate ... 成功
建立数据表 pre_common_member_verify ... 成功
建立数据表 pre_common_member_verify_info ... 成功
建立数据表 pre_common_myapp ... 成功
建立数据表 pre_common_myinvite ... 成功
建立数据表 pre_common_mytask ... 成功
建立数据表 pre_common_nav ... 成功
建立数据表 pre_common_onlinetime ... 成功
建立数据表 pre_common_optimizer ... 成功
建立数据表 pre_common_patch ... 成功
建立数据表 pre_common_plugin ... 成功
建立数据表 pre_common_pluginvar ... 成功
建立数据表 pre_common_process ... 成功
建立数据表 pre_common_regip ... 成功
建立数据表 pre_common_relatedlink ... 成功
建立数据表 pre_common_remote_port ... 成功
建立数据表 pre_common_report ... 成功
建立数据表 pre_common_searchindex ... 成功
建立数据表 pre_common_seccheck ... 成功
建立数据表 pre_common_secquestion ... 成功
建立数据表 pre_common_session ... 成功
建立数据表 pre_common_setting ... 成功
建立数据表 pre_common_smiley ... 成功
建立数据表 pre_common_sphinxcounter ... 成功
建立数据表 pre_common_stat ... 成功
建立数据表 pre_common_statuser ... 成功
建立数据表 pre_common_style ... 成功
建立数据表 pre_common_stylevar ... 成功
建立数据表 pre_common_syscache ... 成功
建立数据表 pre_common_tag ... 成功
建立数据表 pre_common_tagitem ... 成功
建立数据表 pre_common_task ... 成功
建立数据表 pre_common_taskvar ... 成功
建立数据表 pre_common_template ... 成功
建立数据表 pre_common_template_block ... 成功
建立数据表 pre_common_template_permission ... 成功
建立数据表 pre_common_uin_black ... 成功
建立数据表 pre_common_usergroup ... 成功
建立数据表 pre_common_usergroup_field ... 成功
建立数据表 pre_common_visit ... 成功
建立数据表 pre_common_word ... 成功
建立数据表 pre_common_word_type ... 成功
建立数据表 pre_connect_disktask ... 成功
建立数据表 pre_connect_feedlog ... 成功
建立数据表 pre_connect_memberbindlog ... 成功
建立数据表 pre_connect_postfeedlog ... 成功
建立数据表 pre_connect_tthreadlog ... 成功
建立数据表 pre_forum_access ... 成功
建立数据表 pre_forum_activity ... 成功
建立数据表 pre_forum_activityapply ... 成功
建立数据表 pre_forum_announcement ... 成功
建立数据表 pre_forum_attachment ... 成功
建立数据表 pre_forum_attachment_0 ... 成功
建立数据表 pre_forum_attachment_1 ... 成功
建立数据表 pre_forum_attachment_2 ... 成功
建立数据表 pre_forum_attachment_3 ... 成功
建立数据表 pre_forum_attachment_4 ... 成功
建立数据表 pre_forum_attachment_5 ... 成功
建立数据表 pre_forum_attachment_6 ... 成功
建立数据表 pre_forum_attachment_7 ... 成功
建立数据表 pre_forum_attachment_8 ... 成功
建立数据表 pre_forum_attachment_9 ... 成功
建立数据表 pre_forum_attachment_exif ... 成功
建立数据表 pre_forum_attachment_unused ... 成功
建立数据表 pre_forum_attachtype ... 成功
建立数据表 pre_forum_bbcode ... 成功
建立数据表 pre_forum_collection ... 成功
建立数据表 pre_forum_collectioncomment ... 成功
建立数据表 pre_forum_collectionfollow ... 成功
建立数据表 pre_forum_collectioninvite ... 成功
建立数据表 pre_forum_collectionrelated ... 成功
建立数据表 pre_forum_collectionteamworker ... 成功
建立数据表 pre_forum_collectionthread ... 成功
建立数据表 pre_forum_creditslog ... 成功
建立数据表 pre_forum_debate ... 成功
建立数据表 pre_forum_debatepost ... 成功
建立数据表 pre_forum_faq ... 成功
建立数据表 pre_forum_filter_post ... 成功
建立数据表 pre_forum_forum ... 成功
建立数据表 pre_forum_forum_threadtable ... 成功
建立数据表 pre_forum_forumfield ... 成功
建立数据表 pre_forum_forumrecommend ... 成功
建立数据表 pre_forum_groupcreditslog ... 成功
建立数据表 pre_forum_groupfield ... 成功
建立数据表 pre_forum_groupinvite ... 成功
建立数据表 pre_forum_grouplevel ... 成功
建立数据表 pre_forum_groupuser ... 成功
建立数据表 pre_forum_hotreply_member ... 成功
建立数据表 pre_forum_hotreply_number ... 成功
建立数据表 pre_forum_imagetype ... 成功
建立数据表 pre_forum_medal ... 成功
建立数据表 pre_forum_medallog ... 成功
建立数据表 pre_forum_memberrecommend ... 成功
建立数据表 pre_forum_moderator ... 成功
建立数据表 pre_forum_modwork ... 成功
建立数据表 pre_forum_newthread ... 成功
建立数据表 pre_forum_onlinelist ... 成功
建立数据表 pre_forum_order ... 成功
建立数据表 pre_forum_poll ... 成功
建立数据表 pre_forum_polloption ... 成功
建立数据表 pre_forum_polloption_image ... 成功
建立数据表 pre_forum_pollvoter ... 成功
建立数据表 pre_forum_post ... 成功
建立数据表 pre_forum_post_location ... 成功
建立数据表 pre_forum_post_moderate ... 成功
建立数据表 pre_forum_post_tableid ... 成功
建立数据表 pre_forum_postcache ... 成功
建立数据表 pre_forum_postcomment ... 成功
建立数据表 pre_forum_postlog ... 成功
建立数据表 pre_forum_poststick ... 成功
建立数据表 pre_forum_promotion ... 成功
建立数据表 pre_forum_ratelog ... 成功
建立数据表 pre_forum_relatedthread ... 成功
建立数据表 pre_forum_replycredit ... 成功
建立数据表 pre_forum_rsscache ... 成功
建立数据表 pre_forum_sofa ... 成功
建立数据表 pre_forum_spacecache ... 成功
建立数据表 pre_forum_statlog ... 成功
建立数据表 pre_forum_thread ... 成功
建立数据表 pre_forum_thread_moderate ... 成功
建立数据表 pre_forum_threadaddviews ... 成功
建立数据表 pre_forum_threadcalendar ... 成功
建立数据表 pre_forum_threadclass ... 成功
建立数据表 pre_forum_threadclosed ... 成功
建立数据表 pre_forum_threaddisablepos ... 成功
建立数据表 pre_forum_threadhidelog ... 成功
建立数据表 pre_forum_threadhot ... 成功
建立数据表 pre_forum_threadimage ... 成功
建立数据表 pre_forum_threadlog ... 成功
建立数据表 pre_forum_threadmod ... 成功
建立数据表 pre_forum_threadpartake ... 成功
建立数据表 pre_forum_threadpreview ... 成功
建立数据表 pre_forum_threadprofile ... 成功
建立数据表 pre_forum_threadprofile_group ... 成功
建立数据表 pre_forum_threadrush ... 成功
建立数据表 pre_forum_threadtype ... 成功
建立数据表 pre_forum_trade ... 成功
建立数据表 pre_forum_tradecomment ... 成功
建立数据表 pre_forum_tradelog ... 成功
建立数据表 pre_forum_typeoption ... 成功
建立数据表 pre_forum_typeoptionvar ... 成功
建立数据表 pre_forum_typevar ... 成功
建立数据表 pre_forum_warning ... 成功
建立数据表 pre_home_album ... 成功
建立数据表 pre_home_album_category ... 成功
建立数据表 pre_home_appcreditlog ... 成功
建立数据表 pre_home_blacklist ... 成功
建立数据表 pre_home_blog ... 成功
建立数据表 pre_home_blog_category ... 成功
建立数据表 pre_home_blog_moderate ... 成功
建立数据表 pre_home_blogfield ... 成功
建立数据表 pre_home_class ... 成功
建立数据表 pre_home_click ... 成功
建立数据表 pre_home_clickuser ... 成功
建立数据表 pre_home_comment ... 成功
建立数据表 pre_home_comment_moderate ... 成功
建立数据表 pre_home_docomment ... 成功
建立数据表 pre_home_doing ... 成功
建立数据表 pre_home_doing_moderate ... 成功
建立数据表 pre_home_favorite ... 成功
建立数据表 pre_home_feed ... 成功
建立数据表 pre_home_feed_app ... 成功
建立数据表 pre_home_follow ... 成功
建立数据表 pre_home_follow_feed ... 成功
建立数据表 pre_home_follow_feed_archiver ... 成功
建立数据表 pre_home_friend ... 成功
建立数据表 pre_home_friend_request ... 成功
建立数据表 pre_home_friendlog ... 成功
建立数据表 pre_home_notification ... 成功
建立数据表 pre_home_pic ... 成功
建立数据表 pre_home_pic_moderate ... 成功
建立数据表 pre_home_picfield ... 成功
建立数据表 pre_home_poke ... 成功
建立数据表 pre_home_pokearchive ... 成功
建立数据表 pre_home_share ... 成功
建立数据表 pre_home_share_moderate ... 成功
建立数据表 pre_home_show ... 成功
建立数据表 pre_home_specialuser ... 成功
建立数据表 pre_home_userapp ... 成功
建立数据表 pre_home_userappfield ... 成功
建立数据表 pre_home_visitor ... 成功
建立数据表 pre_mobile_setting ... 成功
建立数据表 pre_portal_article_content ... 成功
建立数据表 pre_portal_article_count ... 成功
建立数据表 pre_portal_article_moderate ... 成功
建立数据表 pre_portal_article_related ... 成功
建立数据表 pre_portal_article_title ... 成功
建立数据表 pre_portal_article_trash ... 成功
建立数据表 pre_portal_attachment ... 成功
建立数据表 pre_portal_category ... 成功
建立数据表 pre_portal_category_permission ... 成功
建立数据表 pre_portal_comment ... 成功
建立数据表 pre_portal_comment_moderate ... 成功
建立数据表 pre_portal_rsscache ... 成功
建立数据表 pre_portal_topic ... 成功
建立数据表 pre_portal_topic_pic ... 成功
建立数据表 pre_security_evilpost ... 成功
建立数据表 pre_security_eviluser ... 成功
建立数据表 pre_security_failedlog ... 成功
正在安装数据 ... 成功
正在安装附加数据 ... 成功
初始化记录 201503_ratelog
初始化记录 201503_illegallog
初始化记录 201503_modslog
初始化记录 201503_cplog
初始化记录 201503_errorlog
初始化记录 201503_banlog
清空目录 ./data/template
清空目录 ./data/cache
清空目录 ./data/threadcache
清空目录 ./uc_client/data
清空目录 ./uc_client/data/cache
</pre>
</div>
<div class="bottom tac"> <a href="#" class="btn">正在安装</a></div>
</div>
</div>
<?php require './templates/footer.php'; ?>
</body>
</html><file_sep><?php
class explame
{
private $_di;
public function __construct(Di $di)
{
$this->_id = $di;
echo $this->_id->study();
}
}
$di = new Di();
$di->setDi('test', function(){echo 'aaaaaaaaaaaaaaaaaaaaa'});
$explame = new explame($di);
class Di
{
public $func = Array();
public function setDi($key, $value)
{
if(func_exists)
$this->func[$key] = $value;
}
public function getDi($key)
{
if(empty($this->func[$key])) return null;
return call_user_func_array($this->func[$key]);
}
}
| fd0da3e3b0f424108d7a4d02827a52e437399ffe | [
"SQL",
"PHP"
] | 19 | PHP | hellosnake/snkStudy | 730d4a0ddbfa2bc8b75a818de1bd840a46383f12 | 77541a8609899254c2258dd20ea6ddf33d0d79a9 | |
refs/heads/master | <repo_name>f059074251/interested<file_sep>/7-Zip/CPP/7zip/Archive/Nsis/NsisIn.cpp
// NsisIn.cpp
#include "StdAfx.h"
#include "../../../../C/CpuArch.h"
#include "Common/IntToString.h"
#include "../../Common/StreamUtils.h"
#include "NsisIn.h"
#define Get32(p) GetUi32(p)
namespace NArchive {
namespace NNsis {
Byte kSignature[kSignatureSize] = NSIS_SIGNATURE;
#ifdef NSIS_SCRIPT
static const char *kCrLf = "\x0D\x0A";
#endif
#define NS_UN_SKIP_CODE 0xE000
#define NS_UN_VAR_CODE 0xE001
#define NS_UN_SHELL_CODE 0xE002
#define NS_UN_LANG_CODE 0xE003
#define NS_UN_CODES_START NS_UN_SKIP_CODE
#define NS_UN_CODES_END NS_UN_LANG_CODE
Byte CInArchive::ReadByte()
{
if (_posInData >= _size)
throw 1;
return _data[_posInData++];
}
UInt32 CInArchive::ReadUInt32()
{
UInt32 value = 0;
for (int i = 0; i < 4; i++)
value |= ((UInt32)(ReadByte()) << (8 * i));
return value;
}
void CInArchive::ReadBlockHeader(CBlockHeader &bh)
{
bh.Offset = ReadUInt32();
bh.Num = ReadUInt32();
}
#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; }
static int CompareItems(void *const *p1, void *const *p2, void * /* param */)
{
const CItem &i1 = **(CItem **)p1;
const CItem &i2 = **(CItem **)p2;
RINOZ(MyCompare(i1.Pos, i2.Pos));
if (i1.IsUnicode)
{
RINOZ(i1.PrefixU.Compare(i2.PrefixU));
RINOZ(i1.NameU.Compare(i2.NameU));
}
else
{
RINOZ(i1.PrefixA.Compare(i2.PrefixA));
RINOZ(i1.NameA.Compare(i2.NameA));
}
return 0;
}
static AString UIntToString(UInt32 v)
{
char sz[32];
ConvertUInt64ToString(v, sz);
return sz;
}
static AString IntToString(Int32 v)
{
char sz[32];
ConvertInt64ToString(v, sz);
return sz;
}
AString CInArchive::ReadStringA(UInt32 pos) const
{
AString s;
if (pos >= _size)
return IntToString((Int32)pos);
UInt32 offset = GetOffset() + _stringsPos + pos;
for (;;)
{
if (offset >= _size)
break; // throw 1;
char c = _data[offset++];
if (c == 0)
break;
s += c;
}
return s;
}
UString CInArchive::ReadStringU(UInt32 pos) const
{
UString s;
UInt32 offset = GetOffset() + _stringsPos + (pos * 2);
for (;;)
{
if (offset >= _size || offset + 1 >= _size)
return s; // throw 1;
char c0 = _data[offset++];
char c1 = _data[offset++];
wchar_t c = (c0 | ((wchar_t)c1 << 8));
if (c == 0)
break;
s += c;
}
return s;
}
/*
static AString ParsePrefix(const AString &prefix)
{
AString res = prefix;
if (prefix.Length() >= 3)
{
if ((Byte)prefix[0] == 0xFD && (Byte)prefix[1] == 0x95 && (Byte)prefix[2] == 0x80)
res = "$INSTDIR" + prefix.Mid(3);
else if ((Byte)prefix[0] == 0xFD && (Byte)prefix[1] == 0x96 && (Byte)prefix[2] == 0x80)
res = "$OUTDIR" + prefix.Mid(3);
}
return res;
}
*/
#define SYSREGKEY "Software\\Microsoft\\Windows\\CurrentVersion"
/*
# define CSIDL_PROGRAMS 0x2
# define CSIDL_PRINTERS 0x4
# define CSIDL_PERSONAL 0x5
# define CSIDL_FAVORITES 0x6
# define CSIDL_STARTUP 0x7
# define CSIDL_RECENT 0x8
# define CSIDL_SENDTO 0x9
# define CSIDL_STARTMENU 0xB
# define CSIDL_MYMUSIC 0xD
# define CSIDL_MYVIDEO 0xE
# define CSIDL_DESKTOPDIRECTORY 0x10
# define CSIDL_NETHOOD 0x13
# define CSIDL_FONTS 0x14
# define CSIDL_TEMPLATES 0x15
# define CSIDL_COMMON_STARTMENU 0x16
# define CSIDL_COMMON_PROGRAMS 0x17
# define CSIDL_COMMON_STARTUP 0x18
# define CSIDL_COMMON_DESKTOPDIRECTORY 0x19
# define CSIDL_APPDATA 0x1A
# define CSIDL_PRINTHOOD 0x1B
# define CSIDL_LOCAL_APPDATA 0x1C
# define CSIDL_ALTSTARTUP 0x1D
# define CSIDL_COMMON_ALTSTARTUP 0x1E
# define CSIDL_COMMON_FAVORITES 0x1F
# define CSIDL_INTERNET_CACHE 0x20
# define CSIDL_COOKIES 0x21
# define CSIDL_HISTORY 0x22
# define CSIDL_COMMON_APPDATA 0x23
# define CSIDL_WINDOWS 0x24
# define CSIDL_SYSTEM 0x25
# define CSIDL_PROGRAM_FILES 0x26
# define CSIDL_MYPICTURES 0x27
# define CSIDL_PROFILE 0x28
# define CSIDL_PROGRAM_FILES_COMMON 0x2B
# define CSIDL_COMMON_TEMPLATES 0x2D
# define CSIDL_COMMON_DOCUMENTS 0x2E
# define CSIDL_COMMON_ADMINTOOLS 0x2F
# define CSIDL_ADMINTOOLS 0x30
# define CSIDL_COMMON_MUSIC 0x35
# define CSIDL_COMMON_PICTURES 0x36
# define CSIDL_COMMON_VIDEO 0x37
# define CSIDL_RESOURCES 0x38
# define CSIDL_RESOURCES_LOCALIZED 0x39
# define CSIDL_CDBURN_AREA 0x3B
*/
struct CCommandPair
{
int NumParams;
const char *Name;
};
enum
{
// 0
EW_INVALID_OPCODE, // zero is invalid. useful for catching errors. (otherwise an all zeroes instruction
// does nothing, which is easily ignored but means something is wrong.
EW_RET, // return from function call
EW_NOP, // Nop/Jump, do nothing: 1, [?new address+1:advance one]
EW_ABORT, // Abort: 1 [status]
EW_QUIT, // Quit: 0
EW_CALL, // Call: 1 [new address+1]
EW_UPDATETEXT, // Update status text: 2 [update str, ui_st_updateflag=?ui_st_updateflag:this]
EW_SLEEP, // Sleep: 1 [sleep time in milliseconds]
EW_BRINGTOFRONT, // BringToFront: 0
EW_CHDETAILSVIEW, // SetDetailsView: 2 [listaction,buttonaction]
// 10
EW_SETFILEATTRIBUTES, // SetFileAttributes: 2 [filename, attributes]
EW_CREATEDIR, // Create directory: 2, [path, ?update$INSTDIR]
EW_IFFILEEXISTS, // IfFileExists: 3, [file name, jump amount if exists, jump amount if not exists]
EW_SETFLAG, // Sets a flag: 2 [id, data]
EW_IFFLAG, // If a flag: 4 [on, off, id, new value mask]
EW_GETFLAG, // Gets a flag: 2 [output, id]
EW_RENAME, // Rename: 3 [old, new, rebootok]
EW_GETFULLPATHNAME, // GetFullPathName: 2 [output, input, ?lfn:sfn]
EW_SEARCHPATH, // SearchPath: 2 [output, filename]
EW_GETTEMPFILENAME, // GetTempFileName: 2 [output, base_dir]
// 20
EW_EXTRACTFILE, // File to extract: 6 [overwriteflag, output filename, compressed filedata, filedatetimelow, filedatetimehigh, allow ignore]
// overwriteflag: 0x1 = no. 0x0=force, 0x2=try, 0x3=if date is newer
EW_DELETEFILE, // Delete File: 2, [filename, rebootok]
EW_MESSAGEBOX, // MessageBox: 5,[MB_flags,text,retv1:retv2,moveonretv1:moveonretv2]
EW_RMDIR, // RMDir: 2 [path, recursiveflag]
EW_STRLEN, // StrLen: 2 [output, input]
EW_ASSIGNVAR, // Assign: 4 [variable (0-9) to assign, string to assign, maxlen, startpos]
EW_STRCMP, // StrCmp: 5 [str1, str2, jump_if_equal, jump_if_not_equal, case-sensitive?]
EW_READENVSTR, // ReadEnvStr/ExpandEnvStrings: 3 [output, string_with_env_variables, IsRead]
EW_INTCMP, // IntCmp: 6 [val1, val2, equal, val1<val2, val1>val2, unsigned?]
EW_INTOP, // IntOp: 4 [output, input1, input2, op] where op: 0=add, 1=sub, 2=mul, 3=div, 4=bor, 5=band, 6=bxor, 7=bnot input1, 8=lnot input1, 9=lor, 10=land], 11=1%2
// 30
EW_INTFMT, // IntFmt: [output, format, input]
EW_PUSHPOP, // Push/Pop/Exchange: 3 [variable/string, ?pop:push, ?exch]
EW_FINDWINDOW, // FindWindow: 5, [outputvar, window class,window name, window_parent, window_after]
EW_SENDMESSAGE, // SendMessage: 6 [output, hwnd, msg, wparam, lparam, [wparamstring?1:0 | lparamstring?2:0 | timeout<<2]
EW_ISWINDOW, // IsWindow: 3 [hwnd, jump_if_window, jump_if_notwindow]
EW_GETDLGITEM, // GetDlgItem: 3: [outputvar, dialog, item_id]
EW_SETCTLCOLORS, // SerCtlColors: 3: [hwnd, pointer to struct colors]
EW_SETBRANDINGIMAGE, // SetBrandingImage: 1: [Bitmap file]
EW_CREATEFONT, // CreateFont: 5: [handle output, face name, height, weight, flags]
EW_SHOWWINDOW, // ShowWindow: 2: [hwnd, show state]
// 40
EW_SHELLEXEC, // ShellExecute program: 4, [shell action, complete commandline, parameters, showwindow]
EW_EXECUTE, // Execute program: 3,[complete command line,waitflag,>=0?output errorcode]
EW_GETFILETIME, // GetFileTime; 3 [file highout lowout]
EW_GETDLLVERSION, // GetDLLVersion: 3 [file highout lowout]
EW_REGISTERDLL, // Register DLL: 3,[DLL file name, string ptr of function to call, text to put in display (<0 if none/pass parms), 1 - no unload, 0 - unload]
EW_CREATESHORTCUT, // Make Shortcut: 5, [link file, target file, parameters, icon file, iconindex|show mode<<8|hotkey<<16]
EW_COPYFILES, // CopyFiles: 3 [source mask, destination location, flags]
EW_REBOOT, // Reboot: 0
EW_WRITEINI, // Write INI String: 4, [Section, Name, Value, INI File]
EW_READINISTR, // ReadINIStr: 4 [output, section, name, ini_file]
// 50
EW_DELREG, // DeleteRegValue/DeleteRegKey: 4, [root key(int), KeyName, ValueName, delkeyonlyifempty]. ValueName is -1 if delete key
EW_WRITEREG, // Write Registry value: 5, [RootKey(int),KeyName,ItemName,ItemData,typelen]
// typelen=1 for str, 2 for dword, 3 for binary, 0 for expanded str
EW_READREGSTR, // ReadRegStr: 5 [output, rootkey(int), keyname, itemname, ==1?int::str]
EW_REGENUM, // RegEnum: 5 [output, rootkey, keyname, index, ?key:value]
EW_FCLOSE, // FileClose: 1 [handle]
EW_FOPEN, // FileOpen: 4 [name, openmode, createmode, outputhandle]
EW_FPUTS, // FileWrite: 3 [handle, string, ?int:string]
EW_FGETS, // FileRead: 4 [handle, output, maxlen, ?getchar:gets]
EW_FSEEK, // FileSeek: 4 [handle, offset, mode, >=0?positionoutput]
EW_FINDCLOSE, // FindClose: 1 [handle]
// 60
EW_FINDNEXT, // FindNext: 2 [output, handle]
EW_FINDFIRST, // FindFirst: 2 [filespec, output, handleoutput]
EW_WRITEUNINSTALLER, // WriteUninstaller: 3 [name, offset, icon_size]
EW_LOG, // LogText: 2 [0, text] / LogSet: [1, logstate]
EW_SECTIONSET, // SectionSetText: 3: [idx, 0, text]
// SectionGetText: 3: [idx, 1, output]
// SectionSetFlags: 3: [idx, 2, flags]
// SectionGetFlags: 3: [idx, 3, output]
EW_INSTTYPESET, // InstTypeSetFlags: 3: [idx, 0, flags]
// InstTypeGetFlags: 3: [idx, 1, output]
// instructions not actually implemented in exehead, but used in compiler.
EW_GETLABELADDR, // both of these get converted to EW_ASSIGNVAR
EW_GETFUNCTIONADDR,
EW_LOCKWINDOW
};
#ifdef NSIS_SCRIPT
static CCommandPair kCommandPairs[] =
{
{ 0, "Invalid" },
{ 0, "Return" },
{ 1, "Goto" },
{ 0, "Abort" },
{ 0, "Quit" },
{ 1, "Call" },
{ 2, "UpdateSatusText" },
{ 1, "Sleep" },
{ 0, "BringToFront" },
{ 2, "SetDetailsView" },
{ 2, "SetFileAttributes" },
{ 2, "SetOutPath" },
{ 3, "IfFileExists" },
{ 2, "SetFlag" },
{ 4, "IfFlag" },
{ 2, "GetFlag" },
{ 3, "Rename" },
{ 2, "GetFullPathName" },
{ 2, "SearchPath" },
{ 2, "GetTempFileName" },
{ 6, "File" },
{ 2, "Delete" },
{ 5, "MessageBox" },
{ 2, "RMDir" },
{ 2, "StrLen" },
{ 4, "StrCpy" },
{ 5, "StrCmp" },
{ 3, "ReadEnvStr" },
{ 6, "IntCmp" },
{ 4, "IntOp" },
{ 3, "IntFmt" },
{ 3, "PushPop" },
{ 5, "FindWindow" },
{ 6, "SendMessage" },
{ 3, "IsWindow" },
{ 3, "GetDlgItem" },
{ 3, "SerCtlColors" },
{ 1, "SetBrandingImage" },
{ 5, "CreateFont" },
{ 2, "ShowWindow" },
{ 4, "ShellExecute" },
{ 3, "Execute" },
{ 3, "GetFileTime" },
{ 3, "GetDLLVersion" },
{ 3, "RegisterDLL" },
{ 5, "CreateShortCut" },
{ 3, "CopyFiles" },
{ 0, "Reboot" },
{ 4, "WriteINIStr" },
{ 4, "ReadINIStr" },
{ 4, "DelReg" },
{ 5, "WriteReg" },
{ 5, "ReadRegStr" },
{ 5, "RegEnum" },
{ 1, "FileClose" },
{ 4, "FileOpen" },
{ 3, "FileWrite" },
{ 4, "FileRead" },
{ 4, "FileSeek" },
{ 1, "FindClose" },
{ 2, "FindNext" },
{ 2, "FindFirst" },
{ 3, "WriteUninstaller" },
{ 2, "LogText" },
{ 3, "Section?etText" },
{ 3, "InstType?etFlags" },
{ 6, "GetLabelAddr" },
{ 2, "GetFunctionAddress" },
{ 6, "LockWindow" }
};
#endif
static const char *kShellStrings[] =
{
"",
"",
"SMPROGRAMS",
"",
"PRINTERS",
"DOCUMENTS",
"FAVORITES",
"SMSTARTUP",
"RECENT",
"SENDTO",
"",
"STARTMENU",
"",
"MUSIC",
"VIDEO",
"",
"DESKTOP",
"",
"",
"NETHOOD",
"FONTS",
"TEMPLATES",
"COMMONSTARTMENU",
"COMMONFILES",
"COMMON_STARTUP",
"COMMON_DESKTOPDIRECTORY",
"QUICKLAUNCH",
"PRINTHOOD",
"LOCALAPPDATA",
"ALTSTARTUP",
"ALTSTARTUP",
"FAVORITES",
"INTERNET_CACHE",
"COOKIES",
"HISTORY",
"APPDATA",
"WINDIR",
"SYSDIR",
"PROGRAMFILES",
"PICTURES",
"PROFILE",
"",
"",
"COMMONFILES",
"",
"TEMPLATES",
"DOCUMENTS",
"ADMINTOOLS",
"ADMINTOOLS",
"",
"",
"",
"",
"MUSIC",
"PICTURES",
"VIDEO",
"RESOURCES",
"RESOURCES_LOCALIZED",
"",
"CDBURN_AREA"
};
static const int kNumShellStrings = sizeof(kShellStrings) / sizeof(kShellStrings[0]);
/*
# define CMDLINE 20 // everything before here doesn't have trailing slash removal
# define INSTDIR 21
# define OUTDIR 22
# define EXEDIR 23
# define LANGUAGE 24
# define TEMP 25
# define PLUGINSDIR 26
# define HWNDPARENT 27
# define _CLICK 28
# define _OUTDIR 29
*/
static const char *kVarStrings[] =
{
"CMDLINE",
"INSTDIR",
"OUTDIR",
"EXEDIR",
"LANGUAGE",
"TEMP",
"PLUGINSDIR",
"EXEPATH", // test it
"EXEFILE", // test it
"HWNDPARENT",
"_CLICK",
"_OUTDIR"
};
static const int kNumVarStrings = sizeof(kVarStrings) / sizeof(kVarStrings[0]);
static AString GetVar(UInt32 index)
{
AString res = "$";
if (index < 10)
res += UIntToString(index);
else if (index < 20)
{
res += "R";
res += UIntToString(index - 10);
}
else if (index < 20 + kNumVarStrings)
res += kVarStrings[index - 20];
else
{
res += "[";
res += UIntToString(index);
res += "]";
}
return res;
}
#define NS_SKIP_CODE 252
#define NS_VAR_CODE 253
#define NS_SHELL_CODE 254
#define NS_LANG_CODE 255
#define NS_CODES_START NS_SKIP_CODE
static AString GetShellString(int index)
{
AString res = "$";
if (index < kNumShellStrings)
{
const char *sz = kShellStrings[index];
if (sz[0] != 0)
return res + sz;
}
res += "SHELL[";
res += UIntToString(index);
res += "]";
return res;
}
// Based on <NAME>'s simplified process_string
AString GetNsisString(const AString &s)
{
AString res;
for (int i = 0; i < s.Length();)
{
unsigned char nVarIdx = s[i++];
if (nVarIdx > NS_CODES_START && i + 2 <= s.Length())
{
int nData = s[i++] & 0x7F;
unsigned char c1 = s[i++];
nData |= (((int)(c1 & 0x7F)) << 7);
if (nVarIdx == NS_SHELL_CODE)
res += GetShellString(c1);
else if (nVarIdx == NS_VAR_CODE)
res += GetVar(nData);
else if (nVarIdx == NS_LANG_CODE)
res += "NS_LANG_CODE";
}
else if (nVarIdx == NS_SKIP_CODE)
{
if (i < s.Length())
res += s[i++];
}
else // Normal char
res += (char)nVarIdx;
}
return res;
}
UString GetNsisString(const UString &s)
{
UString res;
for (int i = 0; i < s.Length();)
{
wchar_t nVarIdx = s[i++];
if (nVarIdx > NS_UN_CODES_START && nVarIdx <= NS_UN_CODES_END)
{
if (i == s.Length())
break;
int nData = s[i++] & 0x7FFF;
if (nVarIdx == NS_UN_SHELL_CODE)
res += GetUnicodeString(GetShellString(nData >> 8));
else if (nVarIdx == NS_UN_VAR_CODE)
res += GetUnicodeString(GetVar(nData));
else if (nVarIdx == NS_UN_LANG_CODE)
res += L"NS_LANG_CODE";
}
else if (nVarIdx == NS_UN_SKIP_CODE)
{
if (i == s.Length())
break;
res += s[i++];
}
else // Normal char
res += (char)nVarIdx;
}
return res;
}
AString CInArchive::ReadString2A(UInt32 pos) const
{
return GetNsisString(ReadStringA(pos));
}
UString CInArchive::ReadString2U(UInt32 pos) const
{
return GetNsisString(ReadStringU(pos));
}
AString CInArchive::ReadString2(UInt32 pos) const
{
if (IsUnicode)
return UnicodeStringToMultiByte(ReadString2U(pos));
else
return ReadString2A(pos);
}
AString CInArchive::ReadString2Qw(UInt32 pos) const
{
return "\"" + ReadString2(pos) + "\"";
}
#define DEL_DIR 1
#define DEL_RECURSE 2
#define DEL_REBOOT 4
// #define DEL_SIMPLE 8
static const int kNumEntryParams = 6;
struct CEntry
{
UInt32 Which;
UInt32 Params[kNumEntryParams];
AString GetParamsString(int numParams);
CEntry()
{
Which = 0;
for (UInt32 j = 0; j < kNumEntryParams; j++)
Params[j] = 0;
}
};
AString CEntry::GetParamsString(int numParams)
{
AString s;
for (int i = 0; i < numParams; i++)
{
s += " ";
UInt32 v = Params[i];
if (v > 0xFFF00000)
s += IntToString((Int32)Params[i]);
else
s += UIntToString(Params[i]);
}
return s;
}
#ifdef NSIS_SCRIPT
static AString GetRegRootID(UInt32 val)
{
const char *s;
switch(val)
{
case 0: s = "SHCTX"; break;
case 0x80000000: s = "HKCR"; break;
case 0x80000001: s = "HKCU"; break;
case 0x80000002: s = "HKLM"; break;
case 0x80000003: s = "HKU"; break;
case 0x80000004: s = "HKPD"; break;
case 0x80000005: s = "HKCC"; break;
case 0x80000006: s = "HKDD"; break;
case 0x80000050: s = "HKPT"; break;
case 0x80000060: s = "HKPN"; break;
default:
return UIntToString(val); break;
}
return s;
}
#endif
HRESULT CInArchive::ReadEntries(const CBlockHeader &bh)
{
_posInData = bh.Offset + GetOffset();
AString prefixA;
UString prefixU;
for (UInt32 i = 0; i < bh.Num; i++)
{
CEntry e;
e.Which = ReadUInt32();
for (UInt32 j = 0; j < kNumEntryParams; j++)
e.Params[j] = ReadUInt32();
#ifdef NSIS_SCRIPT
if (e.Which != EW_PUSHPOP && e.Which < sizeof(kCommandPairs) / sizeof(kCommandPairs[0]))
{
const CCommandPair &pair = kCommandPairs[e.Which];
Script += pair.Name;
}
#endif
switch (e.Which)
{
case EW_CREATEDIR:
{
if (IsUnicode)
{
prefixU.Empty();
prefixU = ReadString2U(e.Params[0]);
}
else
{
prefixA.Empty();
prefixA = ReadString2A(e.Params[0]);
}
#ifdef NSIS_SCRIPT
Script += " ";
if (IsUnicode)
Script += UnicodeStringToMultiByte(prefixU);
else
Script += prefixA;
#endif
break;
}
case EW_EXTRACTFILE:
{
CItem item;
item.IsUnicode = IsUnicode;
if (IsUnicode)
{
item.PrefixU = prefixU;
item.NameU = ReadString2U(e.Params[1]);
}
else
{
item.PrefixA = prefixA;
item.NameA = ReadString2A(e.Params[1]);
}
/* UInt32 overwriteFlag = e.Params[0]; */
item.Pos = e.Params[2];
item.MTime.dwLowDateTime = e.Params[3];
item.MTime.dwHighDateTime = e.Params[4];
/* UInt32 allowIgnore = e.Params[5]; */
if (Items.Size() > 0)
{
/*
if (item.Pos == Items.Back().Pos)
continue;
*/
}
Items.Add(item);
#ifdef NSIS_SCRIPT
Script += " ";
if (IsUnicode)
Script += UnicodeStringToMultiByte(item.NameU);
else
Script += item.NameA;
#endif
break;
}
#ifdef NSIS_SCRIPT
case EW_UPDATETEXT:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += UIntToString(e.Params[1]);
break;
}
case EW_SETFILEATTRIBUTES:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += UIntToString(e.Params[1]);
break;
}
case EW_IFFILEEXISTS:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += UIntToString(e.Params[1]);
Script += " ";
Script += UIntToString(e.Params[2]);
break;
}
case EW_RENAME:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += ReadString2(e.Params[1]);
Script += " ";
Script += UIntToString(e.Params[2]);
break;
}
case EW_GETFULLPATHNAME:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += ReadString2(e.Params[1]);
Script += " ";
Script += UIntToString(e.Params[2]);
break;
}
case EW_SEARCHPATH:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += ReadString2(e.Params[1]);
break;
}
case EW_GETTEMPFILENAME:
{
AString s;
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += ReadString2(e.Params[1]);
break;
}
case EW_DELETEFILE:
{
UInt64 flag = e.Params[1];
if (flag != 0)
{
Script += " ";
if (flag == DEL_REBOOT)
Script += "/REBOOTOK";
else
Script += UIntToString(e.Params[1]);
}
Script += " ";
Script += ReadString2(e.Params[0]);
break;
}
case EW_RMDIR:
{
UInt64 flag = e.Params[1];
if (flag != 0)
{
if ((flag & DEL_REBOOT) != 0)
Script += " /REBOOTOK";
if ((flag & DEL_RECURSE) != 0)
Script += " /r";
}
Script += " ";
Script += ReadString2(e.Params[0]);
break;
}
case EW_STRLEN:
{
Script += " ";
Script += GetVar(e.Params[0]);;
Script += " ";
Script += ReadString2Qw(e.Params[1]);
break;
}
case EW_ASSIGNVAR:
{
Script += " ";
Script += GetVar(e.Params[0]);;
Script += " ";
Script += ReadString2Qw(e.Params[1]);
AString maxLen, startOffset;
if (e.Params[2] != 0)
maxLen = ReadString2(e.Params[2]);
if (e.Params[3] != 0)
startOffset = ReadString2(e.Params[3]);
if (!maxLen.IsEmpty() || !startOffset.IsEmpty())
{
Script += " ";
if (maxLen.IsEmpty())
Script += "\"\"";
else
Script += maxLen;
if (!startOffset.IsEmpty())
{
Script += " ";
Script += startOffset;
}
}
break;
}
case EW_STRCMP:
{
Script += " ";
Script += " ";
Script += ReadString2Qw(e.Params[0]);
Script += " ";
Script += ReadString2Qw(e.Params[1]);
for (int j = 2; j < 5; j++)
{
Script += " ";
Script += UIntToString(e.Params[j]);
}
break;
}
case EW_INTCMP:
{
if (e.Params[5] != 0)
Script += "U";
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += ReadString2(e.Params[1]);
for (int i = 2; i < 5; i++)
{
Script += " ";
Script += UIntToString(e.Params[i]);
}
break;
}
case EW_INTOP:
{
Script += " ";
Script += GetVar(e.Params[0]);
Script += " ";
int numOps = 2;
AString op;
switch (e.Params[3])
{
case 0: op = '+'; break;
case 1: op = '-'; break;
case 2: op = '*'; break;
case 3: op = '/'; break;
case 4: op = '|'; break;
case 5: op = '&'; break;
case 6: op = '^'; break;
case 7: op = '~'; numOps = 1; break;
case 8: op = '!'; numOps = 1; break;
case 9: op = "||"; break;
case 10: op = "&&"; break;
case 11: op = '%'; break;
default: op = UIntToString(e.Params[3]);
}
AString p1 = ReadString2(e.Params[1]);
if (numOps == 1)
{
Script += op;
Script += p1;
}
else
{
Script += p1;
Script += " ";
Script += op;
Script += " ";
Script += ReadString2(e.Params[2]);
}
break;
}
case EW_PUSHPOP:
{
int isPop = (e.Params[1] != 0);
if (isPop)
{
Script += "Pop";
Script += " ";
Script += GetVar(e.Params[0]);;
}
else
{
int isExch = (e.Params[2] != 0);
if (isExch)
{
Script += "Exch";
}
else
{
Script += "Push";
Script += " ";
Script += ReadString2(e.Params[0]);
}
}
break;
}
case EW_SENDMESSAGE:
{
// SendMessage: 6 [output, hwnd, msg, wparam, lparam, [wparamstring?1:0 | lparamstring?2:0 | timeout<<2]
Script += " ";
// Script += ReadString2(e.Params[0]);
// Script += " ";
Script += ReadString2(e.Params[1]);
Script += " ";
Script += ReadString2(e.Params[2]);
Script += " ";
UInt32 spec = e.Params[5];
// if (spec & 1)
Script += IntToString(e.Params[3]);
// else
// Script += ReadString2(e.Params[3]);
Script += " ";
// if (spec & 2)
Script += IntToString(e.Params[4]);
// else
// Script += ReadString2(e.Params[4]);
if ((Int32)e.Params[0] >= 0)
{
Script += " ";
Script += GetVar(e.Params[1]);
}
spec >>= 2;
if (spec != 0)
{
Script += " /TIMEOUT=";
Script += IntToString(spec);
}
break;
}
case EW_GETDLGITEM:
{
Script += " ";
Script += GetVar(e.Params[0]);;
Script += " ";
Script += ReadString2(e.Params[1]);
Script += " ";
Script += ReadString2(e.Params[2]);
break;
}
case EW_REGISTERDLL:
{
Script += " ";
Script += ReadString2(e.Params[0]);
Script += " ";
Script += ReadString2(e.Params[1]);
Script += " ";
Script += UIntToString(e.Params[2]);
break;
}
case EW_CREATESHORTCUT:
{
AString s;
Script += " ";
Script += ReadString2Qw(e.Params[0]);
Script += " ";
Script += ReadString2Qw(e.Params[1]);
for (int j = 2; j < 5; j++)
{
Script += " ";
Script += UIntToString(e.Params[j]);
}
break;
}
/*
case EW_DELREG:
{
AString keyName, valueName;
keyName = ReadString2(e.Params[1]);
bool isValue = (e.Params[2] != -1);
if (isValue)
{
valueName = ReadString2(e.Params[2]);
Script += "Key";
}
else
Script += "Value";
Script += " ";
Script += UIntToString(e.Params[0]);
Script += " ";
Script += keyName;
if (isValue)
{
Script += " ";
Script += valueName;
}
Script += " ";
Script += UIntToString(e.Params[3]);
break;
}
*/
case EW_WRITEREG:
{
AString s;
switch(e.Params[4])
{
case 1: s = "Str"; break;
case 2: s = "ExpandStr"; break;
case 3: s = "Bin"; break;
case 4: s = "DWORD"; break;
default: s = "?" + UIntToString(e.Params[4]); break;
}
Script += s;
Script += " ";
Script += GetRegRootID(e.Params[0]);
Script += " ";
AString keyName, valueName;
keyName = ReadString2Qw(e.Params[1]);
Script += keyName;
Script += " ";
valueName = ReadString2Qw(e.Params[2]);
Script += valueName;
Script += " ";
valueName = ReadString2Qw(e.Params[3]);
Script += valueName;
Script += " ";
break;
}
case EW_WRITEUNINSTALLER:
{
Script += " ";
Script += ReadString2(e.Params[0]);
for (int j = 1; j < 3; j++)
{
Script += " ";
Script += UIntToString(e.Params[j]);
}
break;
}
default:
{
int numParams = kNumEntryParams;
if (e.Which < sizeof(kCommandPairs) / sizeof(kCommandPairs[0]))
{
const CCommandPair &pair = kCommandPairs[e.Which];
// Script += pair.Name;
numParams = pair.NumParams;
}
else
{
Script += "Unknown";
Script += UIntToString(e.Which);
}
Script += e.GetParamsString(numParams);
}
#endif
}
#ifdef NSIS_SCRIPT
Script += kCrLf;
#endif
}
{
Items.Sort(CompareItems, 0);
int i;
// if (IsSolid)
for (i = 0; i + 1 < Items.Size();)
{
bool sameName = IsUnicode ?
(Items[i].NameU == Items[i + 1].NameU) :
(Items[i].NameA == Items[i + 1].NameA);
if (Items[i].Pos == Items[i + 1].Pos && (IsSolid || sameName))
Items.Delete(i + 1);
else
i++;
}
for (i = 0; i + 1 < Items.Size(); i++)
{
CItem &item = Items[i];
item.EstimatedSizeIsDefined = true;
item.EstimatedSize = Items[i + 1].Pos - item.Pos - 4;
}
if (!IsSolid)
{
for (i = 0; i < Items.Size(); i++)
{
CItem &item = Items[i];
RINOK(_stream->Seek(GetPosOfNonSolidItem(i), STREAM_SEEK_SET, NULL));
const UInt32 kSigSize = 4 + 1 + 5;
BYTE sig[kSigSize];
size_t processedSize = kSigSize;
RINOK(ReadStream(_stream, sig, &processedSize));
if (processedSize < 4)
return S_FALSE;
UInt32 size = Get32(sig);
if ((size & 0x80000000) != 0)
{
item.IsCompressed = true;
// is compressed;
size &= ~0x80000000;
if (Method == NMethodType::kLZMA)
{
if (processedSize < 9)
return S_FALSE;
if (FilterFlag)
item.UseFilter = (sig[4] != 0);
item.DictionarySize = Get32(sig + 5 + (FilterFlag ? 1 : 0));
}
}
else
{
item.IsCompressed = false;
item.Size = size;
item.SizeIsDefined = true;
}
item.CompressedSize = size;
item.CompressedSizeIsDefined = true;
}
}
}
return S_OK;
}
HRESULT CInArchive::Parse()
{
// UInt32 offset = ReadUInt32();
// ???? offset == FirstHeader.HeaderLength
/* UInt32 ehFlags = */ ReadUInt32();
CBlockHeader bhPages, bhSections, bhEntries, bhStrings, bhLangTables, bhCtlColors, bhData;
// CBlockHeader bgFont;
ReadBlockHeader(bhPages);
ReadBlockHeader(bhSections);
ReadBlockHeader(bhEntries);
ReadBlockHeader(bhStrings);
ReadBlockHeader(bhLangTables);
ReadBlockHeader(bhCtlColors);
// ReadBlockHeader(bgFont);
ReadBlockHeader(bhData);
_stringsPos = bhStrings.Offset;
UInt32 pos = GetOffset() + _stringsPos;
int numZeros0 = 0;
int numZeros1 = 0;
int i;
const int kBlockSize = 256;
for (i = 0; i < kBlockSize; i++)
{
if (pos >= _size || pos + 1 >= _size)
break;
char c0 = _data[pos++];
char c1 = _data[pos++];
wchar_t c = (c0 | ((wchar_t)c1 << 8));
if (c >= NS_UN_CODES_START && c < NS_UN_CODES_END)
{
if (pos >= _size || pos + 1 >= _size)
break;
pos += 2;
numZeros1++;
}
else
{
if (c0 == 0 && c1 != 0)
numZeros0++;
if (c1 == 0)
numZeros1++;
}
// printf("\nnumZeros0 = %2x %2x", _data[pos + 0], _data[pos + 1]);
}
IsUnicode = (numZeros1 > numZeros0 * 3 + kBlockSize / 16);
// printf("\nnumZeros0 = %3d numZeros1 = %3d", numZeros0, numZeros1);
return ReadEntries(bhEntries);
}
static bool IsLZMA(const Byte *p, UInt32 &dictionary)
{
dictionary = Get32(p + 1);
return (p[0] == 0x5D && p[1] == 0x00 && p[2] == 0x00 && p[5] == 0x00);
}
static bool IsLZMA(const Byte *p, UInt32 &dictionary, bool &thereIsFlag)
{
if (IsLZMA(p, dictionary))
{
thereIsFlag = false;
return true;
}
if (IsLZMA(p + 1, dictionary))
{
thereIsFlag = true;
return true;
}
return false;
}
HRESULT CInArchive::Open2(
DECL_EXTERNAL_CODECS_LOC_VARS2
)
{
RINOK(_stream->Seek(0, STREAM_SEEK_CUR, &StreamOffset));
const UInt32 kSigSize = 4 + 1 + 5 + 1; // size, flag, lzma props, lzma first byte
BYTE sig[kSigSize];
RINOK(ReadStream_FALSE(_stream, sig, kSigSize));
UInt64 position;
RINOK(_stream->Seek(StreamOffset, STREAM_SEEK_SET, &position));
_headerIsCompressed = true;
IsSolid = true;
FilterFlag = false;
UInt32 compressedHeaderSize = Get32(sig);
if (compressedHeaderSize == FirstHeader.HeaderLength)
{
_headerIsCompressed = false;
IsSolid = false;
Method = NMethodType::kCopy;
}
else if (IsLZMA(sig, DictionarySize, FilterFlag))
{
Method = NMethodType::kLZMA;
}
else if (IsLZMA(sig + 4, DictionarySize, FilterFlag))
{
IsSolid = false;
Method = NMethodType::kLZMA;
}
else if (sig[3] == 0x80)
{
IsSolid = false;
Method = NMethodType::kDeflate;
}
else
{
Method = NMethodType::kDeflate;
}
_posInData = 0;
if (!IsSolid)
{
_headerIsCompressed = ((compressedHeaderSize & 0x80000000) != 0);
if (_headerIsCompressed)
compressedHeaderSize &= ~0x80000000;
_nonSolidStartOffset = compressedHeaderSize;
RINOK(_stream->Seek(StreamOffset + 4, STREAM_SEEK_SET, NULL));
}
UInt32 unpackSize = FirstHeader.HeaderLength;
if (_headerIsCompressed)
{
// unpackSize = (1 << 23);
_data.SetCapacity(unpackSize);
RINOK(Decoder.Init(
EXTERNAL_CODECS_LOC_VARS
_stream, Method, FilterFlag, UseFilter));
size_t processedSize = unpackSize;
RINOK(Decoder.Read(_data, &processedSize));
if (processedSize != unpackSize)
return S_FALSE;
_size = processedSize;
if (IsSolid)
{
UInt32 size2 = ReadUInt32();
if (size2 < _size)
_size = size2;
}
}
else
{
_data.SetCapacity(unpackSize);
_size = (size_t)unpackSize;
RINOK(ReadStream_FALSE(_stream, (Byte *)_data, unpackSize));
}
return Parse();
}
/*
NsisExe =
{
ExeStub
Archive // must start from 512 * N
#ifndef NSIS_CONFIG_CRC_ANAL
{
Some additional data
}
}
Archive
{
FirstHeader
Data
#ifdef NSIS_CONFIG_CRC_SUPPORT && FirstHeader.ThereIsCrc()
{
CRC
}
}
FirstHeader
{
UInt32 Flags;
Byte Signature[16];
// points to the header+sections+entries+stringtable in the datablock
UInt32 HeaderLength;
UInt32 ArchiveSize;
}
*/
HRESULT CInArchive::Open(
DECL_EXTERNAL_CODECS_LOC_VARS
IInStream *inStream, const UInt64 *maxCheckStartPosition)
{
Clear();
RINOK(inStream->Seek(0, STREAM_SEEK_SET, NULL));
UInt64 maxSize = ((maxCheckStartPosition != 0) ? *maxCheckStartPosition : 0);
const UInt32 kStep = 512;
Byte buffer[kStep];
UInt64 position = 0;
for (; position <= maxSize; position += kStep)
{
RINOK(ReadStream_FALSE(inStream, buffer, kStep));
if (memcmp(buffer + 4, kSignature, kSignatureSize) == 0)
break;
}
if (position > maxSize)
return S_FALSE;
const UInt32 kStartHeaderSize = 4 * 7;
RINOK(inStream->Seek(0, STREAM_SEEK_END, &_archiveSize));
RINOK(inStream->Seek(position + kStartHeaderSize, STREAM_SEEK_SET, 0));
FirstHeader.Flags = Get32(buffer);
FirstHeader.HeaderLength = Get32(buffer + kSignatureSize + 4);
FirstHeader.ArchiveSize = Get32(buffer + kSignatureSize + 8);
if (_archiveSize - position < FirstHeader.ArchiveSize)
return S_FALSE;
try
{
_stream = inStream;
HRESULT res = Open2(EXTERNAL_CODECS_LOC_VARS2);
if (res != S_OK)
Clear();
_stream.Release();
return res;
}
catch(...) { Clear(); return S_FALSE; }
}
void CInArchive::Clear()
{
#ifdef NSIS_SCRIPT
Script.Empty();
#endif
Items.Clear();
_stream.Release();
}
}}
<file_sep>/7-Zip/CPP/7zip/Archive/Wim/WimIn.cpp
// Archive/WimIn.cpp
#include "StdAfx.h"
#include "../../../../C/CpuArch.h"
#include "Common/IntToString.h"
#include "../../Common/StreamUtils.h"
#include "../../Common/StreamObjects.h"
#include "../../Common/LimitedStreams.h"
#include "../Common/OutStreamWithSha1.h"
#include "WimIn.h"
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
#define Get64(p) GetUi64(p)
namespace NArchive{
namespace NWim{
static const int kChunkSizeBits = 15;
static const UInt32 kChunkSize = (1 << kChunkSizeBits);
namespace NXpress {
class CDecoderFlusher
{
CDecoder *m_Decoder;
public:
bool NeedFlush;
CDecoderFlusher(CDecoder *decoder): m_Decoder(decoder), NeedFlush(true) {}
~CDecoderFlusher()
{
if (NeedFlush)
m_Decoder->Flush();
m_Decoder->ReleaseStreams();
}
};
HRESULT CDecoder::CodeSpec(UInt32 outSize)
{
{
Byte levels[kMainTableSize];
for (int i = 0; i < kMainTableSize; i += 2)
{
Byte b = m_InBitStream.DirectReadByte();
levels[i] = b & 0xF;
levels[i + 1] = b >> 4;
}
if (!m_MainDecoder.SetCodeLengths(levels))
return S_FALSE;
}
while (outSize > 0)
{
UInt32 number = m_MainDecoder.DecodeSymbol(&m_InBitStream);
if (number < 256)
{
m_OutWindowStream.PutByte((Byte)number);
outSize--;
}
else
{
if (number >= kMainTableSize)
return S_FALSE;
UInt32 posLenSlot = number - 256;
UInt32 posSlot = posLenSlot / kNumLenSlots;
UInt32 len = posLenSlot % kNumLenSlots;
UInt32 distance = (1 << posSlot) - 1 + m_InBitStream.ReadBits(posSlot);
if (len == kNumLenSlots - 1)
{
len = m_InBitStream.DirectReadByte();
if (len == 0xFF)
{
len = m_InBitStream.DirectReadByte();
len |= (UInt32)m_InBitStream.DirectReadByte() << 8;
}
else
len += kNumLenSlots - 1;
}
len += kMatchMinLen;
UInt32 locLen = (len <= outSize ? len : outSize);
if (!m_OutWindowStream.CopyBlock(distance, locLen))
return S_FALSE;
len -= locLen;
outSize -= locLen;
if (len != 0)
return S_FALSE;
}
}
return S_OK;
}
const UInt32 kDictSize = (1 << kNumPosSlots);
HRESULT CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, UInt32 outSize)
{
if (!m_OutWindowStream.Create(kDictSize) || !m_InBitStream.Create(1 << 16))
return E_OUTOFMEMORY;
CDecoderFlusher flusher(this);
m_InBitStream.SetStream(inStream);
m_OutWindowStream.SetStream(outStream);
m_InBitStream.Init();
m_OutWindowStream.Init(false);
RINOK(CodeSpec(outSize));
flusher.NeedFlush = false;
return Flush();
}
HRESULT CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, UInt32 outSize)
{
try { return CodeReal(inStream, outStream, outSize); }
catch(const CInBufferException &e) { return e.ErrorCode; } \
catch(const CLzOutWindowException &e) { return e.ErrorCode; }
catch(...) { return S_FALSE; }
}
}
static void GetFileTimeFromMem(const Byte *p, FILETIME *ft)
{
ft->dwLowDateTime = Get32(p);
ft->dwHighDateTime = Get32(p + 4);
}
HRESULT CUnpacker::Unpack(IInStream *inStream, const CResource &resource, bool lzxMode,
ISequentialOutStream *outStream, ICompressProgressInfo *progress)
{
RINOK(inStream->Seek(resource.Offset, STREAM_SEEK_SET, NULL));
CLimitedSequentialInStream *limitedStreamSpec = new CLimitedSequentialInStream();
CMyComPtr<ISequentialInStream> limitedStream = limitedStreamSpec;
limitedStreamSpec->SetStream(inStream);
if (!copyCoder)
{
copyCoderSpec = new NCompress::CCopyCoder;
copyCoder = copyCoderSpec;
}
if (!resource.IsCompressed())
{
if (resource.PackSize != resource.UnpackSize)
return S_FALSE;
limitedStreamSpec->Init(resource.PackSize);
return copyCoder->Code(limitedStreamSpec, outStream, NULL, NULL, progress);
}
if (resource.UnpackSize == 0)
return S_OK;
UInt64 numChunks = (resource.UnpackSize + kChunkSize - 1) >> kChunkSizeBits;
unsigned entrySize = ((resource.UnpackSize > (UInt64)1 << 32) ? 8 : 4);
UInt64 sizesBufSize64 = entrySize * (numChunks - 1);
size_t sizesBufSize = (size_t)sizesBufSize64;
if (sizesBufSize != sizesBufSize64)
return E_OUTOFMEMORY;
if (sizesBufSize > sizesBuf.GetCapacity())
{
sizesBuf.Free();
sizesBuf.SetCapacity(sizesBufSize);
}
RINOK(ReadStream_FALSE(inStream, (Byte *)sizesBuf, sizesBufSize));
const Byte *p = (const Byte *)sizesBuf;
if (lzxMode && !lzxDecoder)
{
lzxDecoderSpec = new NCompress::NLzx::CDecoder(true);
lzxDecoder = lzxDecoderSpec;
RINOK(lzxDecoderSpec->SetParams(kChunkSizeBits));
}
UInt64 baseOffset = resource.Offset + sizesBufSize64;
UInt64 outProcessed = 0;
for (UInt32 i = 0; i < (UInt32)numChunks; i++)
{
UInt64 offset = 0;
if (i > 0)
{
offset = (entrySize == 4) ? Get32(p): Get64(p);
p += entrySize;
}
UInt64 nextOffset = resource.PackSize - sizesBufSize64;
if (i + 1 < (UInt32)numChunks)
nextOffset = (entrySize == 4) ? Get32(p): Get64(p);
if (nextOffset < offset)
return S_FALSE;
RINOK(inStream->Seek(baseOffset + offset, STREAM_SEEK_SET, NULL));
UInt64 inSize = nextOffset - offset;
limitedStreamSpec->Init(inSize);
if (progress)
{
RINOK(progress->SetRatioInfo(&offset, &outProcessed));
}
UInt32 outSize = kChunkSize;
if (outProcessed + outSize > resource.UnpackSize)
outSize = (UInt32)(resource.UnpackSize - outProcessed);
UInt64 outSize64 = outSize;
if (inSize == outSize)
{
RINOK(copyCoder->Code(limitedStreamSpec, outStream, NULL, &outSize64, NULL));
}
else
{
if (lzxMode)
{
lzxDecoderSpec->SetKeepHistory(false);
RINOK(lzxDecoder->Code(limitedStreamSpec, outStream, NULL, &outSize64, NULL));
}
else
{
RINOK(xpressDecoder.Code(limitedStreamSpec, outStream, outSize));
}
}
outProcessed += outSize;
}
return S_OK;
}
HRESULT CUnpacker::Unpack(IInStream *inStream, const CResource &resource, bool lzxMode,
ISequentialOutStream *outStream, ICompressProgressInfo *progress, Byte *digest)
{
COutStreamWithSha1 *shaStreamSpec = new COutStreamWithSha1();
CMyComPtr<ISequentialOutStream> shaStream = shaStreamSpec;
shaStreamSpec->SetStream(outStream);
shaStreamSpec->Init(digest != NULL);
HRESULT result = Unpack(inStream, resource, lzxMode, shaStream, progress);
if (digest)
shaStreamSpec->Final(digest);
return result;
}
static HRESULT UnpackData(IInStream *inStream, const CResource &resource, bool lzxMode, CByteBuffer &buf, Byte *digest)
{
size_t size = (size_t)resource.UnpackSize;
if (size != resource.UnpackSize)
return E_OUTOFMEMORY;
buf.Free();
buf.SetCapacity(size);
CSequentialOutStreamImp2 *outStreamSpec = new CSequentialOutStreamImp2();
CMyComPtr<ISequentialOutStream> outStream = outStreamSpec;
outStreamSpec->Init((Byte *)buf, size);
CUnpacker unpacker;
return unpacker.Unpack(inStream, resource, lzxMode, outStream, NULL, digest);
}
static const UInt32 kSignatureSize = 8;
static const Byte kSignature[kSignatureSize] = { 'M', 'S', 'W', 'I', 'M', 0, 0, 0 };
void CResource::Parse(const Byte *p)
{
Flags = p[7];
PackSize = Get64(p) & (((UInt64)1 << 56) - 1);
Offset = Get64(p + 8);
UnpackSize = Get64(p + 16);
}
#define GetResource(p, res) res.Parse(p)
static void GetStream(const Byte *p, CStreamInfo &s)
{
s.Resource.Parse(p);
s.PartNumber = Get16(p + 24);
s.RefCount = Get32(p + 26);
memcpy(s.Hash, p + 30, kHashSize);
}
static HRESULT ParseDirItem(const Byte *base, size_t pos, size_t size,
const UString &prefix, CObjectVector<CItem> &items)
{
for (;;)
{
if (pos + 8 > size)
return S_FALSE;
const Byte *p = base + pos;
UInt64 length = Get64(p);
if (length == 0)
return S_OK;
if (pos + 102 > size || pos + length + 8 > size || length > ((UInt64)1 << 62))
return S_FALSE;
CItem item;
item.Attrib = Get32(p + 8);
// item.SecurityId = Get32(p + 0xC);
UInt64 subdirOffset = Get64(p + 0x10);
GetFileTimeFromMem(p + 0x28, &item.CTime);
GetFileTimeFromMem(p + 0x30, &item.ATime);
GetFileTimeFromMem(p + 0x38, &item.MTime);
memcpy(item.Hash, p + 0x40, kHashSize);
// UInt16 shortNameLen = Get16(p + 98);
UInt16 fileNameLen = Get16(p + 100);
size_t tempPos = pos + 102;
if (tempPos + fileNameLen > size)
return S_FALSE;
wchar_t *sz = item.Name.GetBuffer(prefix.Length() + fileNameLen / 2 + 1);
MyStringCopy(sz, (const wchar_t *)prefix);
sz += prefix.Length();
for (UInt16 i = 0; i + 2 <= fileNameLen; i += 2)
*sz++ = Get16(base + tempPos + i);
*sz++ = '\0';
item.Name.ReleaseBuffer();
if (fileNameLen == 0 && item.isDir() && !item.HasStream())
{
item.Attrib = 0x10; // some swm archives have system/hidden attributes for root
item.Name.Delete(item.Name.Length() - 1);
}
items.Add(item);
pos += (size_t)length;
if (item.isDir() && (subdirOffset != 0))
{
if (subdirOffset >= size)
return S_FALSE;
RINOK(ParseDirItem(base, (size_t)subdirOffset, size, item.Name + WCHAR_PATH_SEPARATOR, items));
}
}
}
static HRESULT ParseDir(const Byte *base, size_t size,
const UString &prefix, CObjectVector<CItem> &items)
{
size_t pos = 0;
if (pos + 8 > size)
return S_FALSE;
const Byte *p = base + pos;
UInt32 totalLength = Get32(p);
// UInt32 numEntries = Get32(p + 4);
pos += 8;
{
/*
CRecordVector<UInt64> entryLens;
UInt64 sum = 0;
for (UInt32 i = 0; i < numEntries; i++)
{
if (pos + 8 > size)
return S_FALSE;
UInt64 len = Get64(p + pos);
entryLens.Add(len);
sum += len;
pos += 8;
}
pos += sum; // skip security descriptors
while ((pos & 7) != 0)
pos++;
if (pos != totalLength)
return S_FALSE;
*/
pos = totalLength;
}
return ParseDirItem(base, pos, size, prefix, items);
}
static int CompareHashRefs(const int *p1, const int *p2, void *param)
{
const CRecordVector<CStreamInfo> &streams = *(const CRecordVector<CStreamInfo> *)param;
return memcmp(streams[*p1].Hash, streams[*p2].Hash, kHashSize);
}
static int CompareStreamsByPos(const CStreamInfo *p1, const CStreamInfo *p2, void * /* param */)
{
int res = MyCompare(p1->PartNumber, p2->PartNumber);
if (res != 0)
return res;
return MyCompare(p1->Resource.Offset, p2->Resource.Offset);
}
int CompareItems(void *const *a1, void *const *a2, void * /* param */)
{
const CItem &i1 = **((const CItem **)a1);
const CItem &i2 = **((const CItem **)a2);
if (i1.isDir() != i2.isDir())
return (i1.isDir()) ? 1 : -1;
if (i1.isDir())
return -MyStringCompareNoCase(i1.Name, i2.Name);
int res = MyCompare(i1.StreamIndex, i2.StreamIndex);
if (res != 0)
return res;
return MyStringCompareNoCase(i1.Name, i2.Name);
}
static int FindHash(const CRecordVector<CStreamInfo> &streams,
const CRecordVector<int> &sortedByHash, const Byte *hash)
{
int left = 0, right = streams.Size();
while (left != right)
{
int mid = (left + right) / 2;
int streamIndex = sortedByHash[mid];
UInt32 i;
const Byte *hash2 = streams[streamIndex].Hash;
for (i = 0; i < kHashSize; i++)
if (hash[i] != hash2[i])
break;
if (i == kHashSize)
return streamIndex;
if (hash[i] < hash2[i])
right = mid;
else
left = mid + 1;
}
return -1;
}
HRESULT CHeader::Parse(const Byte *p)
{
UInt32 haderSize = Get32(p + 8);
if (haderSize < 0x74)
return S_FALSE;
Version = Get32(p + 0x0C);
Flags = Get32(p + 0x10);
if (!IsSupported())
return S_FALSE;
UInt32 chunkSize = Get32(p + 0x14);
if (chunkSize != kChunkSize && chunkSize != 0)
return S_FALSE;
memcpy(Guid, p + 0x18, 16);
PartNumber = Get16(p + 0x28);
NumParts = Get16(p + 0x2A);
int offset = 0x2C;
if (IsNewVersion())
{
NumImages = Get32(p + offset);
offset += 4;
}
GetResource(p + offset, OffsetResource);
GetResource(p + offset + 0x18, XmlResource);
GetResource(p + offset + 0x30, MetadataResource);
/*
if (IsNewVersion())
{
if (haderSize < 0xD0)
return S_FALSE;
IntegrityResource.Parse(p + offset + 0x4C);
BootIndex = Get32(p + 0x48);
}
*/
return S_OK;
}
HRESULT ReadHeader(IInStream *inStream, CHeader &h)
{
const UInt32 kHeaderSizeMax = 0xD0;
Byte p[kHeaderSizeMax];
RINOK(ReadStream_FALSE(inStream, p, kHeaderSizeMax));
if (memcmp(p, kSignature, kSignatureSize) != 0)
return S_FALSE;
return h.Parse(p);
}
HRESULT ReadStreams(IInStream *inStream, const CHeader &h, CDatabase &db)
{
CByteBuffer offsetBuf;
RINOK(UnpackData(inStream, h.OffsetResource, h.IsLzxMode(), offsetBuf, NULL));
for (size_t i = 0; i + kStreamInfoSize <= offsetBuf.GetCapacity(); i += kStreamInfoSize)
{
CStreamInfo s;
GetStream((const Byte *)offsetBuf + i, s);
if (s.PartNumber == h.PartNumber)
db.Streams.Add(s);
}
return S_OK;
}
HRESULT OpenArchive(IInStream *inStream, const CHeader &h, CByteBuffer &xml, CDatabase &db)
{
RINOK(UnpackData(inStream, h.XmlResource, h.IsLzxMode(), xml, NULL));
RINOK(ReadStreams(inStream, h, db));
bool needBootMetadata = !h.MetadataResource.IsEmpty();
if (h.PartNumber == 1)
{
int imageIndex = 1;
for (int j = 0; j < db.Streams.Size(); j++)
{
// if (imageIndex > 1) break;
const CStreamInfo &si = db.Streams[j];
if (!si.Resource.IsMetadata() || si.PartNumber != h.PartNumber)
continue;
Byte hash[kHashSize];
CByteBuffer metadata;
RINOK(UnpackData(inStream, si.Resource, h.IsLzxMode(), metadata, hash));
if (memcmp(hash, si.Hash, kHashSize) != 0)
return S_FALSE;
wchar_t sz[16];
ConvertUInt32ToString(imageIndex++, sz);
UString s = sz;
s += WCHAR_PATH_SEPARATOR;
RINOK(ParseDir(metadata, metadata.GetCapacity(), s, db.Items));
if (needBootMetadata)
if (h.MetadataResource.Offset == si.Resource.Offset)
needBootMetadata = false;
}
}
if (needBootMetadata)
{
CByteBuffer metadata;
RINOK(UnpackData(inStream, h.MetadataResource, h.IsLzxMode(), metadata, NULL));
RINOK(ParseDir(metadata, metadata.GetCapacity(), L"0" WSTRING_PATH_SEPARATOR, db.Items));
}
return S_OK;
}
HRESULT SortDatabase(CDatabase &db)
{
db.Streams.Sort(CompareStreamsByPos, NULL);
{
CRecordVector<int> sortedByHash;
{
for (int j = 0; j < db.Streams.Size(); j++)
sortedByHash.Add(j);
sortedByHash.Sort(CompareHashRefs, &db.Streams);
}
for (int i = 0; i < db.Items.Size(); i++)
{
CItem &item = db.Items[i];
item.StreamIndex = -1;
if (item.HasStream())
item.StreamIndex = FindHash(db.Streams, sortedByHash, item.Hash);
}
}
{
CRecordVector<bool> used;
int j;
for (j = 0; j < db.Streams.Size(); j++)
{
const CStreamInfo &s = db.Streams[j];
used.Add(s.Resource.IsMetadata() && s.PartNumber == 1);
}
for (int i = 0; i < db.Items.Size(); i++)
{
CItem &item = db.Items[i];
if (item.StreamIndex >= 0)
used[item.StreamIndex] = true;
}
for (j = 0; j < db.Streams.Size(); j++)
if (!used[j])
{
CItem item;
item.StreamIndex = j;
item.HasMetadata = false;
db.Items.Add(item);
}
}
db.Items.Sort(CompareItems, NULL);
return S_OK;
}
}}
<file_sep>/FingerSuite/FingerSuiteCPL/FingerSuiteCPL.cpp
// FingerSuiteCPL.cpp : Defines the entry point for the DLL application.
//
#include "stdafx.h"
#include "..\Common\atlcplapplet.h"
#include "resource.h"
#include "Commons.h"
static UINT UWM_UPDATECONFIGURATION = ::RegisterWindowMessage(UWM_UPDATECONFIGURATION_MSG);
#include "FingerMenuCPLDlg.h"
#include "AboutDlg.h"
class CFingerSuiteApplet : public CCPlAppletBase<CFingerSuiteApplet>
{
public:
CFingerMenuCPLDlg1 dlg1;
CFingerMenuCPLDlg2 dlg2;
CFingerMenuCPLDlg3 dlg3;
CFingerMenuCPLDlg4 dlg4;
CFingerMenuCPLDlg5 dlg5;
CFingerMenuCPLDlg6 dlg6;
CFingerMenuCPLDlg7 dlg7;
CFingerMenuCPLDlg8 dlg8;
CAboutDlg dlgAbout;
BOOL ShowApplet(HWND hWnd, LONG_PTR /*lData*/, LPCTSTR pstrCommand)
{
BOOL bWithFingerMenu = FALSE;
CString szPath;
CString szProgramFilesFolder;
WCHAR szInstallDir[MAX_PATH];
WCHAR szValue[MAX_PATH];
ZeroMemory(szValue, sizeof(szValue));
if (SHGetSpecialFolderPath(NULL, szValue, CSIDL_PROGRAM_FILES, FALSE))
{
szProgramFilesFolder.Format(L"%s", szValue);
}
if (RegistryGetString(HKEY_LOCAL_MACHINE, L"Software\\FingerMenu", L"InstallDir", szInstallDir, MAX_PATH) == S_OK)
{
szPath.Format(L"%s\\FingerMenu.exe", szInstallDir);
}
else
{
szPath = szProgramFilesFolder + L"\\FingerMenu\\FingerMenu.exe";
}
CFindFile finder;
if (finder.FindFile(szPath))
{
bWithFingerMenu = TRUE;
}
dlg1.SetTitle(L"Startup");
dlg1.m_bWithFingerMenu = bWithFingerMenu;
if (bWithFingerMenu)
{
dlg2.SetTitle(L"Menu options");
dlg3.SetTitle(L"Menu exclusions");
dlg7.SetTitle(L"Menu wnd exclusions");
}
dlg5.SetTitle(L"Msgbox options");
dlg6.SetTitle(L"Msgbox exclusions");
dlg8.SetTitle(L"Msgbox wnd exclusions");
dlg4.SetTitle(L"Skins");
dlg4.m_bWithFingerMenu = bWithFingerMenu;
dlgAbout.SetTitle(L"About");
// about box
CString strCredits = "\n\n"
"\tFingerMenu v1.12\n\n"
"\tFingerMsgBox v1.01\n\n"
"\rdeveloped by:\n"
"<NAME>\n"
"<<EMAIL>>\n"
"\n\n"
"http://forum.xda-developers.com/\n"
" showthread.php?t=459125\n";
dlgAbout.SetCredits(strCredits);
CPropertySheet sheet;
sheet.AddPage(dlg1);
if (bWithFingerMenu)
{
sheet.AddPage(dlg2);
sheet.AddPage(dlg3);
sheet.AddPage(dlg7);
}
sheet.AddPage(dlg5);
sheet.AddPage(dlg6);
sheet.AddPage(dlg8);
sheet.AddPage(dlg4);
sheet.AddPage(dlgAbout);
sheet.SetActivePage(_ttol(pstrCommand));
if (IDOK == sheet.DoModal(hWnd))
{
ReloadConfiguration();
}
return TRUE;
}
private:
void ReloadConfiguration()
{
HWND hWndDest = ::FindWindow(L"FINGER_MENU", NULL);
if (hWndDest != NULL)
{
::PostMessage(hWndDest, UWM_UPDATECONFIGURATION, 0, 0);
/*
::PostMessage(hWndDest, WM_CLOSE, 0, 0);
Sleep(2000);
CString strApp = L"\\Program Files\\FingerMenu\\FingerMenu.exe";
SHELLEXECUTEINFO sei;
memset(&sei, 0, sizeof(sei));
sei.cbSize = sizeof(sei);
sei.fMask = 0;
sei.hwnd = 0;
sei.lpVerb = L"open"; // Operation to perform
sei.lpFile = strApp; // Application name
sei.lpParameters = NULL; // Additional parameters
sei.lpDirectory = 0; // Default directory
sei.nShow = SW_SHOW;
sei.hInstApp = 0;
ShellExecuteEx(&sei);
*/
}
hWndDest = ::FindWindow(L"FINGER_MSGBOX", NULL);
if (hWndDest != NULL)
{
::PostMessage(hWndDest, UWM_UPDATECONFIGURATION, 0, 0);
/*
::PostMessage(hWndDest, WM_CLOSE, 0, 0);
Sleep(2000);
CString strApp = L"\\Program Files\\FingerMsgbox\\FingerMsgbox.exe";
SHELLEXECUTEINFO sei;
memset(&sei, 0, sizeof(sei));
sei.cbSize = sizeof(sei);
sei.fMask = 0;
sei.hwnd = 0;
sei.lpVerb = L"open"; // Operation to perform
sei.lpFile = strApp; // Application name
sei.lpParameters = NULL; // Additional parameters
sei.lpDirectory = 0; // Default directory
sei.nShow = SW_SHOW;
sei.hInstApp = 0;
ShellExecuteEx(&sei);
*/
}
}
};
BEGIN_CPLAPPLET_MAP()
CPLAPPLET_ENTRY(CFingerSuiteApplet, "FingerSuiteApplet", FingerSuiteApplet)
END_CPLAPPLET_MAP()
CAppModule _Module;
CCPlAppletModule _Applets;
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
if( ul_reason_for_call == DLL_PROCESS_ATTACH ) _Module.Init(NULL, (HMODULE)hModule);
if( ul_reason_for_call == DLL_PROCESS_DETACH ) _Module.Term();
return TRUE;
}
extern "C" __declspec(dllexport) LONG APIENTRY CPlApplet(HWND hwndCPl, UINT msg, LPARAM lParam1, LPARAM lParam2)
{
return _Applets.CPlApplet(hwndCPl, msg, lParam1, lParam2);
}
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdDecoder.h
// PpmdDecoder.h
// 2009-05-30 : <NAME> : Public domain
#ifndef __COMPRESS_PPMD_DECODER_H
#define __COMPRESS_PPMD_DECODER_H
#include "../../Common/MyCom.h"
#include "../ICoder.h"
#include "../Common/OutBuffer.h"
#include "PpmdDecode.h"
#include "RangeCoder.h"
namespace NCompress {
namespace NPpmd {
class CDecoder :
public ICompressCoder,
public ICompressSetDecoderProperties2,
#ifndef NO_READ_FROM_CODER
public ICompressSetInStream,
public ICompressSetOutStreamSize,
public ISequentialInStream,
#endif
public CMyUnknownImp
{
CRangeDecoder _rangeDecoder;
COutBuffer _outStream;
CDecodeInfo _info;
Byte _order;
UInt32 _usedMemorySize;
int _remainLen;
UInt64 _outSize;
bool _outSizeDefined;
UInt64 _processedSize;
HRESULT CodeSpec(UInt32 num, Byte *memStream);
public:
#ifndef NO_READ_FROM_CODER
MY_UNKNOWN_IMP4(
ICompressSetDecoderProperties2,
ICompressSetInStream,
ICompressSetOutStreamSize,
ISequentialInStream)
#else
MY_UNKNOWN_IMP1(
ICompressSetDecoderProperties2)
#endif
void ReleaseStreams()
{
ReleaseInStream();
_outStream.ReleaseStream();
}
HRESULT Flush() { return _outStream.Flush(); }
STDMETHOD(CodeReal)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
STDMETHOD(SetDecoderProperties2)(const Byte *data, UInt32 size);
STDMETHOD(SetInStream)(ISequentialInStream *inStream);
STDMETHOD(ReleaseInStream)();
STDMETHOD(SetOutStreamSize)(const UInt64 *outSize);
#ifndef NO_READ_FROM_CODER
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
#endif
CDecoder(): _outSizeDefined(false) {}
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdEncode.h
// PpmdEncode.h
// 2009-05-30 : <NAME> : Public domain
// This code is based on <NAME>'s PPMdH code (public domain)
#ifndef __COMPRESS_PPMD_ENCODE_H
#define __COMPRESS_PPMD_ENCODE_H
#include "PpmdContext.h"
namespace NCompress {
namespace NPpmd {
struct CEncodeInfo: public CInfo
{
void EncodeBinSymbol(int symbol, NRangeCoder::CEncoder *rangeEncoder)
{
PPM_CONTEXT::STATE& rs = MinContext->oneState();
UInt16 &bs = GetBinSumm(rs, GetContextNoCheck(MinContext->Suffix)->NumStats);
if (rs.Symbol == symbol)
{
FoundState = &rs;
rs.Freq = (Byte)(rs.Freq + (rs.Freq < 128 ? 1: 0));
rangeEncoder->EncodeBit(bs, TOT_BITS, 0);
bs = (UInt16)(bs + INTERVAL - GET_MEAN(bs, PERIOD_BITS, 2));
PrevSuccess = 1;
RunLength++;
}
else
{
rangeEncoder->EncodeBit(bs, TOT_BITS, 1);
bs = (UInt16)(bs - GET_MEAN(bs, PERIOD_BITS, 2));
InitEsc = ExpEscape[bs >> 10];
NumMasked = 1;
CharMask[rs.Symbol] = EscCount;
PrevSuccess = 0;
FoundState = NULL;
}
}
void EncodeSymbol1(int symbol, NRangeCoder::CEncoder *rangeEncoder)
{
PPM_CONTEXT::STATE* p = GetStateNoCheck(MinContext->Stats);
if (p->Symbol == symbol)
{
PrevSuccess = (2 * (p->Freq) > MinContext->SummFreq);
RunLength += PrevSuccess;
rangeEncoder->Encode(0, p->Freq, MinContext->SummFreq);
(FoundState = p)->Freq += 4;
MinContext->SummFreq += 4;
if (p->Freq > MAX_FREQ)
rescale();
return;
}
PrevSuccess = 0;
int LoCnt = p->Freq, i = MinContext->NumStats - 1;
while ((++p)->Symbol != symbol)
{
LoCnt += p->Freq;
if (--i == 0)
{
HiBitsFlag = HB2Flag[FoundState->Symbol];
CharMask[p->Symbol] = EscCount;
i=(NumMasked = MinContext->NumStats)-1;
FoundState = NULL;
do { CharMask[(--p)->Symbol] = EscCount; } while ( --i );
rangeEncoder->Encode(LoCnt, MinContext->SummFreq - LoCnt, MinContext->SummFreq);
return;
}
}
rangeEncoder->Encode(LoCnt, p->Freq, MinContext->SummFreq);
update1(p);
}
void EncodeSymbol2(int symbol, NRangeCoder::CEncoder *rangeEncoder)
{
int hiCnt, i = MinContext->NumStats - NumMasked;
UInt32 scale;
SEE2_CONTEXT* psee2c = makeEscFreq2(i, scale);
PPM_CONTEXT::STATE* p = GetStateNoCheck(MinContext->Stats) - 1;
hiCnt = 0;
do
{
do { p++; } while (CharMask[p->Symbol] == EscCount);
hiCnt += p->Freq;
if (p->Symbol == symbol)
goto SYMBOL_FOUND;
CharMask[p->Symbol] = EscCount;
}
while ( --i );
rangeEncoder->Encode(hiCnt, scale, hiCnt + scale);
scale += hiCnt;
psee2c->Summ = (UInt16)(psee2c->Summ + scale);
NumMasked = MinContext->NumStats;
return;
SYMBOL_FOUND:
UInt32 highCount = hiCnt;
UInt32 lowCount = highCount - p->Freq;
if ( --i )
{
PPM_CONTEXT::STATE* p1 = p;
do
{
do { p1++; } while (CharMask[p1->Symbol] == EscCount);
hiCnt += p1->Freq;
}
while ( --i );
}
// SubRange.scale += hiCnt;
scale += hiCnt;
rangeEncoder->Encode(lowCount, highCount - lowCount, scale);
psee2c->update();
update2(p);
}
void EncodeSymbol(int c, NRangeCoder::CEncoder *rangeEncoder)
{
if (MinContext->NumStats != 1)
EncodeSymbol1(c, rangeEncoder);
else
EncodeBinSymbol(c, rangeEncoder);
while ( !FoundState )
{
do
{
OrderFall++;
MinContext = GetContext(MinContext->Suffix);
if (MinContext == 0)
return; // S_OK;
}
while (MinContext->NumStats == NumMasked);
EncodeSymbol2(c, rangeEncoder);
}
NextContext();
}
};
}}
#endif
<file_sep>/FBReaderJ/jni/Makefile
NDK_BUILD= /home/taotao/Dev/Tools/android-ndk-r4b/ndk-build
PROJ_DIR = /media/34D0110AD010D448/Interested/FBReaderJ/jni
START = FBReaderJ
$(START):
cd $(PROJ_DIR);$(NDK_BUILD) V=1
all: $(START)
clean:
cd $(PROJ_DIR);$(NDK_BUILD) clean
<file_sep>/SQLCEHelper/Include/SqlCeHelper.h
// SqlCeHelper class
// based on OLE DB Client class library, <NAME>
// Copyright (C) 2009 by <NAME>
//
//
#pragma once
#include "oledbcli.h"
using namespace OLEDBCLI;
class SqlCeHelper
{
public:
SqlCeHelper(void);
~SqlCeHelper(void);
bool Open(const CString& dbPath);
void Close();
//If database exists, delete it and create new one.
bool CreateDatabase(const CString& dbPath);
bool DeleteDatabase(const CString& dbPath);
int ExecuteReader(const CString& sql);
bool IsEndOfRecordSet();
void MoveNext();
void CloseReader();
int GetRowInt(const long ordinal);
double GetRowDouble(const long ordinal);
CString GetRowStr(const long ordinal);
int ExecuteNonQuery(const CString& sql);
void BeginTransaction();
void CommitTransaction();
void RollbackTransaction();
CString GetErrorsMessage();
private:
bool isOpen;
CDataSource dataSource;
CSession session;
CRowset rowset;
int totalRowCount;
int currentRowCount;
};
<file_sep>/SQLCEHelper/Source/TableSchema.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
typedef CTable* CTablePtr;
CSchema::CSchema(CSession& session)
: m_session (session)
{
}
CSchema::~CSchema()
{
Clear();
}
void CSchema::Clear()
{
size_t i;
for(i = 0; i < m_tables.GetCount(); ++i)
delete m_tables[i];
m_tables.RemoveAll();
}
// CSchema::Load
//
// Loads all tables
//
HRESULT CSchema::Load()
{
CTablesRowset tables(m_session); // http://msdn.microsoft.com/en-us/library/ms716980(VS.85).aspx
HRESULT hr;
CRowset rowset;
Clear();
// Open the tables rowset
hr = tables.Open(NULL, NULL, NULL, NULL, rowset);
if(SUCCEEDED(hr))
{
CString strTable;
for(hr = rowset.MoveFirst(); hr == S_OK; hr = rowset.MoveNext())
{
if(rowset.GetValue(3, strTable))
{
CTableSchema* pTableSchema = new CTableSchema(strTable, this);
if(pTableSchema != NULL)
m_tables.Add(pTableSchema);
else
return E_OUTOFMEMORY;
}
}
hr = S_OK;
}
return hr;
}
//-------------------------------------------------------------------------
//
// CTableSchema - manipulates the table schema
//
//-------------------------------------------------------------------------
CTableSchema::CTableSchema()
: m_pSchema (NULL),
m_bLoaded (false)
{
}
CTableSchema::CTableSchema(LPCTSTR pszTableName, CSchema* pSchema)
: m_pSchema (pSchema),
m_strName (pszTableName),
m_bLoaded (false)
{
}
CTableSchema::CTableSchema(const CTableSchema& tableSchema)
: m_bLoaded (false)
{
Copy(tableSchema);
}
CTableSchema::~CTableSchema()
{
Clear();
}
void CTableSchema::Clear()
{
size_t i;
for(i = 0; i < m_columns.GetCount(); ++i)
delete m_columns[i];
m_columns.RemoveAll();
for(i = 0; i < m_foreignKeys.GetCount(); ++i)
delete m_foreignKeys[i];
m_foreignKeys.RemoveAll();
for(i = 0; i < m_indexes.GetCount(); ++i)
delete m_indexes[i];
m_indexes.RemoveAll();
for(i = 0; i < m_uniques.GetCount(); ++i)
delete m_uniques[i];
m_uniques.RemoveAll();
}
bool CTableSchema::Copy(const OLEDBCLI::CTableSchema &tableSchema)
{
Clear();
m_columns .Copy(tableSchema.m_columns);
m_indexes .Copy(tableSchema.m_indexes);
m_foreignKeys .Copy(tableSchema.m_foreignKeys);
m_uniques .Copy(tableSchema.m_uniques);
m_strName = tableSchema.GetName();
m_pSchema = tableSchema.GetSchema();
m_bLoaded = tableSchema.IsLoaded();
return true;
}
// CTableSchema::FindIndex
//
// Seraches for an index in the list given a name and returns its position or -1 if not found.
//
int CTableSchema::FindIndex(LPCTSTR pszName)
{
int i, n = m_indexes.GetCount();
for(i = 0; i < n; ++i)
{
if(wcsicmp(pszName, m_indexes[i]->GetName()) == 0)
return i;
}
return -1;
}
// CTableSchema::FindUnique
//
// Seraches for an unique constraint in the list given a name and returns its position or -1 if not found.
//
int CTableSchema::FindUnique(LPCTSTR pszName)
{
int i, n = m_uniques.GetCount();
for(i = 0; i < n; ++i)
{
if(wcsicmp(pszName, m_uniques[i]->GetName()) == 0)
return i;
}
return -1;
}
// CTableSchema::GetPrimaryKey
//
// Gets the CIndex object that represents the PRIMARY KEY, if any
//
CIndex* CTableSchema::GetPrimaryKey()
{
int i, n = m_indexes.GetCount();
for(i = 0; i < n; ++i)
{
if(m_indexes[i]->IsPrimaryKey())
return m_indexes[i];
}
return NULL;
}
// CTableSchema::FindForeignKey
//
// Searches for a foreign key in the list given a name and returns its position or -1 if not found.
//
int CTableSchema::FindForeignKey(LPCTSTR pszName)
{
int i, n = m_foreignKeys.GetCount();
for(i = 0; i < n; ++i)
{
if(wcsicmp(pszName, m_foreignKeys[i]->GetName()) == 0)
return i;
}
return -1;
}
// CTableSchema::Load
//
// Loads the table schema
//
HRESULT CTableSchema::Load(OLEDBCLI::CSession &session, LPCTSTR pszTableName)
{
if(m_bLoaded)
return S_OK;
HRESULT hr;
CTableDefinition tableDef;
Clear();
hr = tableDef.GetDefinition(session, m_strName);
if(FAILED(hr))
return hr;
// Populate the column array
tableDef.FillColumnArray(m_columns);
// Populate the foreign key array
tableDef.FillForeignKeyArray(m_foreignKeys);
// Populate the foreign key array
tableDef.FillUniqueArray(m_uniques);
// Load and filter the indexes
hr = LoadIndexes(session);
m_bLoaded = true;
return hr;
}
// CTableSchema::Load
//
// Loads the schema from a table created through a CSchema.
// These have a non-NULL m_pSchema.
//
HRESULT CTableSchema::Load()
{
if(m_pSchema == NULL)
return E_FAIL;
return Load(m_pSchema->GetSession(), m_strName);
}
// CTableSchema::LoadIndexes
//
// Loads the table's indexes
//
HRESULT CTableSchema::LoadIndexes(CSession& session)
{
HRESULT hr;
CRowset rowset;
CIndexesRowset indexes(session);
// List all indexes for the given table
hr = indexes.Open(NULL, NULL, NULL, NULL, m_strName, rowset);
if(SUCCEEDED(hr))
{
CString strName,
strColumn;
for(hr = rowset.MoveFirst(); hr == S_OK; hr = rowset.MoveNext())
{
int iIndex,
iOrdinal;
short nCollation;
CIndex* pIndex = NULL;
if(!rowset.GetValue(6, strName))
return E_FAIL;
// Skip known unique constraints
if(FindUnique(strName) != -1)
continue;
if(!rowset.GetValue(17, iOrdinal))
return E_FAIL;
if(!rowset.GetValue(18, strColumn))
return E_FAIL;
if(!rowset.GetValue(21, nCollation))
return E_FAIL;
iIndex = FindIndex(strName);
if(iIndex == -1)
{
bool bPrimary, bUnique;
rowset.GetValue(7, bPrimary);
rowset.GetValue(8, bUnique);
pIndex = new CIndex(strName, bUnique, bPrimary);
if(pIndex == NULL)
return E_OUTOFMEMORY;
m_indexes.Add(pIndex);
iIndex = 0;
}
if(pIndex == NULL)
pIndex = m_indexes[iIndex];
pIndex->AddColumn(strColumn, nCollation, (ULONG)iOrdinal);
}
hr = S_OK;
}
return hr;
}
<file_sep>/FBReader/zlibrary/ui/src/qt4/dialogs/ZLQtSelectionDialog.cpp
/*
* Copyright (C) 2004-2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <QtGui/QApplication>
#include <QtGui/QLineEdit>
#include <QtGui/QPixmap>
#include <QtGui/QLayout>
#include <QtGui/QPushButton>
#include <QtGui/QButtonGroup>
#include <QtGui/QKeyEvent>
#include <ZLibrary.h>
#include "ZLQtSelectionDialog.h"
#include "ZLQtDialogManager.h"
#include "ZLQtUtil.h"
ZLQListWidget::ZLQListWidget(QWidget *parent) : QListWidget(parent) {
}
void ZLQListWidget::keyPressEvent(QKeyEvent *event) {
if (event->key() == Qt::Key_Return) {
emit returnPressed();
}
QListWidget::keyPressEvent(event);
}
ZLQtSelectionDialogItem::ZLQtSelectionDialogItem(QListWidget *listWidget, const ZLTreeNodePtr node) : QListWidgetItem(listWidget), myNode(node) {
setText(::qtString(node->displayName()));
}
ZLQtSelectionDialog::ZLQtSelectionDialog(const std::string &caption, ZLTreeHandler &handler) : QDialog(qApp->activeWindow()), ZLDesktopSelectionDialog(handler) {
setWindowTitle(::qtString(caption));
QVBoxLayout *mainLayout = new QVBoxLayout(this);
myStateLine = new QLineEdit(this);
myStateLine->setEnabled(!this->handler().isOpenHandler());
mainLayout->addWidget(myStateLine);
myListWidget = new ZLQListWidget(this);
mainLayout->addWidget(myListWidget);
QWidget *group = new QWidget(this);
QGridLayout *buttonLayout = new QGridLayout(group);
buttonLayout->setColumnStretch(0, 3);
mainLayout->addWidget(group);
QPushButton *okButton = new QPushButton(group);
okButton->setText(::qtButtonName(ZLDialogManager::OK_BUTTON));
buttonLayout->addWidget(okButton, 0, 1);
connect(okButton, SIGNAL(clicked()), this, SLOT(accept()));
QPushButton *cancelButton = new QPushButton(group);
cancelButton->setText(::qtButtonName(ZLDialogManager::CANCEL_BUTTON));
buttonLayout->addWidget(cancelButton, 0, 2);
connect(cancelButton, SIGNAL(clicked()), this, SLOT(reject()));
connect(myListWidget, SIGNAL(itemClicked(QListWidgetItem*)), this, SLOT(runNodeSlot()));
connect(myListWidget, SIGNAL(returnPressed()), this, SLOT(runNodeSlot()));
connect(myStateLine, SIGNAL(returnPressed()), this, SLOT(accept()));
ZLSelectionDialog::update();
}
ZLQtSelectionDialog::~ZLQtSelectionDialog() {
for (std::map<std::string,QIcon*>::const_iterator it = myIcons.begin(); it != myIcons.end(); ++it) {
delete it->second;
}
}
QIcon &ZLQtSelectionDialog::getIcon(const ZLTreeNodePtr node) {
const std::string &pixmapName = node->pixmapName();
std::map<std::string,QIcon*>::const_iterator it = myIcons.find(pixmapName);
if (it == myIcons.end()) {
QPixmap pixmap((ZLibrary::ApplicationImageDirectory() + ZLibrary::FileNameDelimiter + pixmapName + ".png").c_str());
QIcon *icon = new QIcon(pixmap);
myIcons[pixmapName] = icon;
myListWidget->setIconSize(pixmap.size());
return *icon;
} else {
return *it->second;
}
}
void ZLQtSelectionDialog::keyPressEvent(QKeyEvent *event) {
if ((event != 0) && (event->key() == Qt::Key_Escape)) {
reject();
}
}
void ZLQtSelectionDialog::updateStateLine() {
myStateLine->setText(::qtString(handler().stateDisplayName()));
}
void ZLQtSelectionDialog::updateList() {
myListWidget->clear();
const std::vector<ZLTreeNodePtr> &subnodes = handler().subnodes();
if (subnodes.size() > 0) {
for (std::vector<ZLTreeNodePtr>::const_iterator it = subnodes.begin(); it != subnodes.end(); ++it) {
QListWidgetItem *item = new ZLQtSelectionDialogItem(myListWidget, *it);
item->setIcon(getIcon(*it));
}
}
}
void ZLQtSelectionDialog::selectItem(int index) {
if ((index >= 0) && (index < myListWidget->count())) {
myListWidget->setCurrentRow(index);
}
}
void ZLQtSelectionDialog::exitDialog() {
QDialog::accept();
}
void ZLQtSelectionDialog::runNodeSlot() {
QListWidgetItem *item = myListWidget->currentItem();
if (item != 0) {
runNode(((ZLQtSelectionDialogItem*)item)->node());
}
}
void ZLQtSelectionDialog::accept() {
if (handler().isOpenHandler()) {
runNodeSlot();
} else {
runState((const char*)myStateLine->text().toUtf8());
}
}
bool ZLQtSelectionDialog::run() {
return QDialog::exec() == Accepted;
}
<file_sep>/7-Zip/CPP/7zip/UI/Explorer/ContextMenuFlags.h
// ContextMenuFlags.h
#ifndef __SEVENZIP_CONTEXTMENUFLAGS_H
#define __SEVENZIP_CONTEXTMENUFLAGS_H
namespace NContextMenuFlags
{
const UINT32 kExtract = 1 << 0;
const UINT32 kExtractHere = 1 << 1;
const UINT32 kExtractTo = 1 << 2;
// const UINT32 kExtractEach = 1 << 3;
const UINT32 kTest = 1 << 4;
const UINT32 kOpen = 1 << 5;
const UINT32 kCompress = 1 << 8;
const UINT32 kCompressTo7z = 1 << 9;
const UINT32 kCompressEmail = 1 << 10;
const UINT32 kCompressTo7zEmail = 1 << 11;
const UINT32 kCompressToZip = 1 << 12;
const UINT32 kCompressToZipEmail = 1 << 13;
inline UINT32 GetDefaultFlags() {
return
kOpen | kTest |
kExtract | kExtractHere | kExtractTo |
kCompress | kCompressEmail |
kCompressTo7z | kCompressTo7zEmail |
kCompressToZip | kCompressToZipEmail; }
}
#endif
<file_sep>/SQLCEHelper/Source/DbValue.cpp
#include "stdafx.h"
#include "Currency.h"
using namespace OLEDBCLI;
//-------------------------------------------------------------------------
//
// CDbValueRef
//
//-------------------------------------------------------------------------
CDbValueRef::CDbValueRef()
: m_pLength (NULL),
m_pStatus (NULL),
m_wType (DBTYPE_EMPTY),
m_nMaxSize (0),
m_pValue (NULL),
m_bIsLong (false)
{
}
CDbValueRef::CDbValueRef(BOUNDCOLUMN *pBoundColumn, BYTE *pData)
{
ATLASSERT(pBoundColumn != NULL);
ATLASSERT(pData != NULL);
m_pLength = (ULONG*) (pData + pBoundColumn->obLength);
m_pStatus = (DBSTATUS*) (pData + pBoundColumn->obStatus);
m_pValue = pData + pBoundColumn->obValue;
m_wType = pBoundColumn->wType;
m_bIsLong = (pBoundColumn->dwFlags & DBCOLUMNFLAGS_ISLONG) != 0;
m_nMaxSize = pBoundColumn->ulColumnSize;
}
CDbValueRef::CDbValueRef(DBTYPE wType, ULONG* pLength, DBSTATUS* pStatus, BYTE* pValue)
: m_pLength (pLength),
m_pStatus (pStatus),
m_wType (wType),
m_nMaxSize (0),
m_pValue (pValue),
m_bIsLong (false)
{
ATLASSERT(pLength != NULL);
ATLASSERT(pStatus != NULL);
ATLASSERT(pValue != NULL);
}
void CDbValueRef::FreeStorage()
{
if(*m_pStatus == DBSTATUS_S_OK)
{
IUnknown* pUnknown = *(IUnknown**)m_pValue;
if(pUnknown != NULL)
{
pUnknown->Release();
*(IUnknown**)m_pValue = NULL;
}
}
}
bool CDbValueRef::GetValue(bool& bVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_BOOL: bVal = *(VARIANT_BOOL*)m_pValue != 0; return true;
case DBTYPE_UI1: bVal = *(BYTE*)m_pValue != 0; return true;
case DBTYPE_UI2: bVal = *(USHORT*)m_pValue != 0; return true;
case DBTYPE_I2: bVal = *(SHORT*)m_pValue != 0; return true;
case DBTYPE_UI4: bVal = *(UINT*)m_pValue != 0; return true;
case DBTYPE_I4: bVal = *(INT*)m_pValue != 0; return true;
}
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as a boolean
//
bool CDbValueRef::SetValue(bool bVal)
{
bool bSet = true;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
switch(m_wType)
{
case DBTYPE_BOOL: *(VARIANT_BOOL*)m_pValue = bVal ? VARIANT_TRUE : VARIANT_FALSE; break;
case DBTYPE_UI1: *(BYTE*)m_pValue = bVal ? 1 : 0; break;
case DBTYPE_UI2: *(USHORT*)m_pValue = bVal ? 1 : 0; break;
case DBTYPE_I2: *(SHORT*)m_pValue = bVal ? 1 : 0; break;
case DBTYPE_UI4: *(UINT*)m_pValue = bVal ? 1 : 0; break;
case DBTYPE_I4: *(int*)m_pValue = bVal ? 1 : 0; break;
case DBTYPE_I8: *(__int64*)m_pValue = bVal ? 1 : 0; break;
case DBTYPE_R4: *(float*)m_pValue = bVal ? 1.0f : 0.0f; break;
case DBTYPE_R8: *(double*)m_pValue = bVal ? 1.0 : 0.0; break;
default:
bSet = false;
}
if(bSet)
*m_pStatus = DBSTATUS_S_OK;
return bSet;
}
// CDbValueRef::GetValue
//
// Gets the column value as a short
//
bool CDbValueRef::GetValue(short& nVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_I8: nVal = (short)(*(__int64*)m_pValue); return true;
case DBTYPE_UI4: nVal = (short)(*(USHORT*)m_pValue); return true;
case DBTYPE_I4: nVal = (short)(*(int*)m_pValue); return true;
case DBTYPE_UI2: nVal = (short)(*(USHORT*)m_pValue); return true;
case DBTYPE_BOOL:
case DBTYPE_I2: nVal = *(short*)m_pValue; return true;
case DBTYPE_UI1: nVal = (short)(*(BYTE*)m_pValue); return true;
case DBTYPE_R4: nVal = (short)(*(float*)m_pValue); return true;
case DBTYPE_R8: nVal = (short)(*(double*)m_pValue); return true;
case DBTYPE_CY:
{
CY cy = *(CY*)m_pValue;
nVal = short(cy.int64 / 10000);
}
return true;
}
}
return false;
}
// CDbValueRef::GetValue
//
// Gets the column value as an integer
//
bool CDbValueRef::GetValue(int &nVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_UI1: nVal = (int)(*(BYTE*)m_pValue); return true;
case DBTYPE_UI2: nVal = (int)(*(USHORT*)m_pValue); return true;
case DBTYPE_I2: nVal = (int)(*(short*)m_pValue); return true;
case DBTYPE_UI4: nVal = (int)(*(UINT*)m_pValue); return true;
case DBTYPE_I4: nVal = *(int*)m_pValue; return true;
case DBTYPE_I8: nVal = (int)(*(__int64*)m_pValue); return true;
case DBTYPE_R4: nVal = (int)(*(float*)m_pValue); return true;
case DBTYPE_R8: nVal = (int)(*(double*)m_pValue); return true;
case DBTYPE_CY:
{
CY cy = *(CY*)m_pValue;
nVal = int(cy.int64 / 10000);
}
return true;
}
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as an integer
//
bool CDbValueRef::SetValue(int nVal)
{
bool bSet = true;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
switch(m_wType)
{
case DBTYPE_UI1: *(BYTE*)m_pValue = (BYTE)nVal; break;
case DBTYPE_UI2: *(USHORT*)m_pValue = (USHORT)nVal; break;
case DBTYPE_I2: *(SHORT*)m_pValue = (SHORT)nVal; break;
case DBTYPE_UI4: *(UINT*)m_pValue = (UINT)nVal; break;
case DBTYPE_I4: *(int*)m_pValue = nVal; break;
case DBTYPE_I8: *(__int64*)m_pValue = nVal; break;
case DBTYPE_R4: *(float*)m_pValue = (float)nVal; break;
case DBTYPE_R8: *(double*)m_pValue = nVal; break;
default:
bSet = false;
}
if(bSet)
*m_pStatus = DBSTATUS_S_OK;
return bSet;
}
// CDbValueRef::GetValue
//
// Gets the column value as an int64
//
bool CDbValueRef::GetValue(__int64& nVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_I8: nVal = *(__int64*)m_pValue; return true;
case DBTYPE_UI4: nVal = *(UINT*)m_pValue; return true;
case DBTYPE_I4: nVal = *(int*)m_pValue; return true;
case DBTYPE_UI2: nVal = *(USHORT*)m_pValue; return true;
case DBTYPE_I2: nVal = *(short*)m_pValue; return true;
case DBTYPE_UI1: nVal = *(BYTE*)m_pValue; return true;
case DBTYPE_R4: nVal = (__int64)(*(float*)m_pValue); return true;
case DBTYPE_R8: nVal = (__int64)(*(double*)m_pValue); return true;
}
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as an int64
//
bool CDbValueRef::SetValue(__int64 nVal)
{
bool bSet = true;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
switch(m_wType)
{
case DBTYPE_UI1: *(BYTE*)m_pValue = (BYTE)nVal; break;
case DBTYPE_UI2: *(USHORT*)m_pValue = (USHORT)nVal; break;
case DBTYPE_I2: *(short*)m_pValue = (short)nVal; break;
case DBTYPE_UI4: *(UINT*)m_pValue = (UINT)nVal; break;
case DBTYPE_I4: *(int*)m_pValue = (int)nVal; break;
case DBTYPE_I8: *(__int64*)m_pValue = nVal; break;
case DBTYPE_R4: *(float*)m_pValue = (float)nVal; break;
case DBTYPE_R8: *(double*)m_pValue = (double)nVal; break;
case DBTYPE_CY:
{
CY cy;
cy.int64 = nVal * 10000;
*(CY*)m_pValue = cy;
}
break;
default:
bSet = false;
}
if(bSet)
*m_pStatus = DBSTATUS_S_OK;
return bSet;
}
// CDbValueRef::GetValue
//
// Gets the column value as a float
//
bool CDbValueRef::GetValue(float& fltVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_I8: fltVal = (float)(*(__int64*)m_pValue); return true;
case DBTYPE_UI4: fltVal = (float)(*(UINT*)m_pValue); return true;
case DBTYPE_I4: fltVal = (float)(*(int*)m_pValue); return true;
case DBTYPE_UI2: fltVal = (float)(*(USHORT*)m_pValue); return true;
case DBTYPE_I2: fltVal = *(short*)m_pValue; return true;
case DBTYPE_UI1: fltVal = *(BYTE*)m_pValue; return true;
case DBTYPE_R4: fltVal = *(float*)m_pValue; return true;
case DBTYPE_R8: fltVal = (float)(*(double*)m_pValue); return true;
case DBTYPE_CY:
{
CY cy = *(CY*)m_pValue;
fltVal = float((double)cy.int64 / 10000.0);
}
return true;
}
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as a float
//
bool CDbValueRef::SetValue(float fltVal)
{
bool bSet = true;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
switch(m_wType)
{
case DBTYPE_UI1: *(BYTE*)m_pValue = (BYTE)fltVal; break;
case DBTYPE_UI2: *(USHORT*)m_pValue = (USHORT)fltVal; break;
case DBTYPE_I2: *(short*)m_pValue = (short)fltVal; break;
case DBTYPE_UI4: *(UINT*)m_pValue = (UINT)fltVal; break;
case DBTYPE_I4: *(int*)m_pValue = (int)fltVal; break;
case DBTYPE_I8: *(__int64*)m_pValue = (__int64)fltVal; break;
case DBTYPE_R4: *(float*)m_pValue = fltVal; break;
case DBTYPE_R8: *(double*)m_pValue = fltVal; break;
case DBTYPE_CY:
{
CY cyVal;
cyVal.int64 = __int64(fltVal * 10000);
*(CY*)m_pValue = cyVal;
}
break;
default:
bSet = false;
}
if(bSet)
*m_pStatus = DBSTATUS_S_OK;
return bSet;
}
// CDbValueRef::GetValue
//
// Gets the column value as a double
//
bool CDbValueRef::GetValue(double& dblVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_I8: dblVal = (double)(*(__int64*)m_pValue); return true;
case DBTYPE_UI4: dblVal = (double)(*(UINT*)m_pValue); return true;
case DBTYPE_I4: dblVal = (double)(*(int*)m_pValue); return true;
case DBTYPE_UI2: dblVal = (double)(*(USHORT*)m_pValue); return true;
case DBTYPE_I2: dblVal = *(short*)m_pValue; return true;
case DBTYPE_UI1: dblVal = *(BYTE*)m_pValue; return true;
case DBTYPE_R4: dblVal = *(float*)m_pValue; return true;
case DBTYPE_R8: dblVal = *(double*)m_pValue; return true;
case DBTYPE_CY:
{
CY cy = *(CY*)m_pValue;
dblVal = double(cy.int64 / 10000.0);
}
return true;
}
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as double
//
bool CDbValueRef::SetValue(double dblVal)
{
bool bSet = true;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
switch(m_wType)
{
case DBTYPE_UI1: *(BYTE*)m_pValue = (BYTE)dblVal; break;
case DBTYPE_I2: *(short*)m_pValue = (short)dblVal; break;
case DBTYPE_I4: *(int*)m_pValue = (int)dblVal; break;
case DBTYPE_I8: *(__int64*)m_pValue = (__int64)dblVal; break;
case DBTYPE_R4: *(float*)m_pValue = (float)dblVal; break;
case DBTYPE_R8: *(double*)m_pValue = dblVal; break;
case DBTYPE_CY:
{
CY cyVal;
cyVal.int64 = __int64(dblVal * 10000);
*(CY*)m_pValue = cyVal;
}
break;
default:
bSet = false;
}
if(bSet)
*m_pStatus = DBSTATUS_S_OK;
return bSet;
}
// CDbValueRef::GetValue
//
// Gets the column value as a CY
//
bool CDbValueRef::GetValue(CY& cyVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_R4:
{
float val = *(float*)m_pValue;
cyVal.int64 = __int64(val * 10000);
}
return true;
case DBTYPE_R8:
{
double val = *(double*)m_pValue;
cyVal.int64 = __int64(val * 10000);
}
return true;
case DBTYPE_CY:
cyVal = *(CY*)m_pValue;
return true;
}
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as a CY
//
bool CDbValueRef::SetValue(CY cyVal)
{
bool bSet = true;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
switch(m_wType)
{
case DBTYPE_I2:
*(short*)m_pValue = int(cyVal.int64 / 10000);
break;
case DBTYPE_I4:
*(int*)m_pValue = int(cyVal.int64 / 10000);
break;
case DBTYPE_I8:
*(__int64*)m_pValue = cyVal.int64 / 10000;
break;
case DBTYPE_R4:
*(float*)m_pValue = float(cyVal.int64) / 10000;
break;
case DBTYPE_R8:
*(double*)m_pValue = double(cyVal.int64) / 10000;
break;
case DBTYPE_CY:
*(CY*)m_pValue = cyVal;
break;
default:
bSet = false;
}
return bSet;
}
// CDbValueRef::GetValue
//
// Gets the column value as a DB_NUMERIC
//
bool CDbValueRef::GetValue(DB_NUMERIC& numVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK && m_wType == DBTYPE_NUMERIC)
{
numVal = *(DB_NUMERIC*)m_pValue;
return true;
}
return false;
}
// CDbValueRef::GetValue
//
// Gets the column value as a DBTIMESTAMP
//
bool CDbValueRef::GetValue(DBTIMESTAMP& dtVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK && m_wType == DBTYPE_DBTIMESTAMP)
{
dtVal = *(DBTIMESTAMP*)m_pValue;
return true;
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as a DBTIMESTAMP
//
bool CDbValueRef::SetValue(DBTIMESTAMP& dtVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(m_wType == DBTYPE_DBTIMESTAMP)
{
*(DBTIMESTAMP*)m_pValue = dtVal;
*m_pStatus = DBSTATUS_S_OK;
return true;
}
return false;
}
// CDbValueRef::GetValue
//
// Gets the column value as a GUID
//
bool CDbValueRef::GetValue(GUID& guid)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK && m_wType == DBTYPE_GUID)
{
guid = *(GUID*)m_pValue;
return true;
}
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as a GUID
//
bool CDbValueRef::SetValue(GUID& guid)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(m_wType == DBTYPE_GUID)
{
*(GUID*)m_pValue = guid;
*m_pStatus = DBSTATUS_S_OK;
return true;
}
return false;
}
// CDbValueRef::GetValue
//
// Gets the column value as a CString
//
bool CDbValueRef::GetValue(CString& strVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_UI1:
strVal.Format(_T("%d"), *(BYTE*)m_pValue);
return true;
case DBTYPE_I2:
strVal.Format(_T("%d"), *(short*)m_pValue);
return true;
case DBTYPE_I4:
strVal.Format(_T("%d"), *(int*)m_pValue);
return true;
case DBTYPE_DBTIMESTAMP:
{
DBTIMESTAMP dt = *(DBTIMESTAMP*)m_pValue;
strVal.Format(_T("%d-%02d-%02d %02d:%02d:%02d"), dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second);
}
return true;
case DBTYPE_CY:
{
CY cy = *(CY*)m_pValue;
CCurrency curr(cy);
strVal = curr.Format(CCurrency::Currency);
}
return true;
case DBTYPE_WSTR:
if(m_bIsLong)
{
ISequentialStream* pStream;
TCHAR buf[2048];
ULONG cb;
pStream = *(ISequentialStream**)m_pValue;
ATLASSERT(pStream != NULL);
//
// Enter a loop to read the string from the stream
//
do
{
pStream->Read(buf, sizeof(buf) - sizeof(TCHAR), &cb);
if(cb > 0)
{
int i = cb / sizeof(TCHAR);
buf[i] = 0;
strVal += buf;
}
} while(cb >= sizeof(buf));
pStream->Release();
}
else
{
TCHAR* pszText = (TCHAR*)m_pValue;
ULONG nLength = *m_pLength / sizeof(wchar_t);
pszText[nLength] = 0;
strVal = pszText;
}
return true;
}
}
else
strVal.Empty();
return false;
}
// CDbValueRef::SetValue
//
// Sets the column value as a string
//
bool CDbValueRef::SetValue(LPCTSTR pszVal)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if(m_wType == DBTYPE_WSTR)
{
if(m_bIsLong)
{
CBlobStream* pBlobStream = new CBlobStream;
if(pBlobStream == NULL)
return false;
ULONG ulWritten;
size_t nStrLen = wcslen(pszVal);
HRESULT hr = pBlobStream->Write(pszVal, (nStrLen + 1) * sizeof(TCHAR), &ulWritten);
if(SUCCEEDED(hr))
{
*(CBlobStream**)m_pValue = pBlobStream;
*m_pStatus = DBSTATUS_S_OK;
*m_pLength = nStrLen;
}
else
{
delete pBlobStream;
*(CBlobStream**)m_pValue = NULL;
*m_pStatus = DBSTATUS_S_ISNULL;
*m_pLength = 0;
return false;
}
}
else
{
size_t nStrLen = wcslen(pszVal);
ULONG nMaxLen = m_nMaxSize / sizeof(wchar_t);
if(nStrLen > nMaxLen)
{
TCHAR* pszBuf = (TCHAR*)m_pValue;
wcsncpy(pszBuf, pszVal, nMaxLen);
pszBuf[nMaxLen] = 0;
nStrLen = nMaxLen;
}
else
{
wcscpy((TCHAR*)m_pValue, pszVal);
}
*m_pLength = nStrLen;
*m_pStatus = DBSTATUS_S_OK;
}
return true;
}
return false;
}
// CDbValueRef::GetValue
//
// Gets the column value into a byte buffer.
// Does not work for BLOB columns.
//
bool CDbValueRef::GetValue(BYTE *pVal)
{
ULONG nLength;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pLength != NULL);
ATLASSERT(m_pValue != NULL);
ATLASSERT(pVal != NULL);
nLength = * m_pLength;
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_I2:
case DBTYPE_I4:
case DBTYPE_I8:
case DBTYPE_R4:
case DBTYPE_R8:
case DBTYPE_CY:
case DBTYPE_NUMERIC:
case DBTYPE_DBTIMESTAMP:
case DBTYPE_GUID:
memcpy(pVal, m_pValue, nLength);
return true;
case DBTYPE_WSTR:
nLength *= sizeof(wchar_t);
case DBTYPE_BYTES:
if(!m_bIsLong)
{
memcpy(pVal, m_pValue, nLength);
return true;
}
}
}
return false;
}
bool CDbValueRef::SetValue(BYTE *pVal, ULONG nLength)
{
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pValue != NULL);
if((m_wType == DBTYPE_BYTES) && m_bIsLong)
{
CBlobStream* pBlobStream = new CBlobStream;
if(pBlobStream == NULL)
return false;
ULONG ulWritten;
HRESULT hr = pBlobStream->Write(pVal, nLength, &ulWritten);
if(SUCCEEDED(hr))
{
*(CBlobStream**)m_pValue = pBlobStream;
*m_pStatus = DBSTATUS_S_OK;
*m_pLength = nLength;
}
else
{
delete pBlobStream;
*(CBlobStream**)m_pValue = NULL;
*m_pStatus = DBSTATUS_S_ISNULL;
*m_pLength = 0;
return false;
}
}
else
{
if(nLength > m_nMaxSize)
nLength = m_nMaxSize;
memcpy(m_pValue, pVal, nLength);
*m_pLength = nLength;
*m_pStatus = DBSTATUS_S_OK;
}
return true;
}
// CDbValueRef::GetValue
//
// Gets the column value as a BLOB
//
bool CDbValueRef::GetValue(CBlobStream& blob)
{
ULONG nLength,
nWritten;
HRESULT hr;
ATLASSERT(m_pStatus != NULL);
ATLASSERT(m_pLength != NULL);
ATLASSERT(m_pValue != NULL);
blob.Clear();
nLength = *m_pLength;
if(*m_pStatus == DBSTATUS_S_OK)
{
switch(m_wType)
{
case DBTYPE_I2:
case DBTYPE_I4:
case DBTYPE_I8:
case DBTYPE_R4:
case DBTYPE_R8:
case DBTYPE_CY:
case DBTYPE_NUMERIC:
case DBTYPE_DBTIMESTAMP:
case DBTYPE_GUID:
hr = blob.Write(m_pValue, nLength, &nWritten);
if(SUCCEEDED(hr) && nWritten == nLength)
return true;
case DBTYPE_WSTR:
nLength *= sizeof(wchar_t);
case DBTYPE_BYTES:
if(!m_bIsLong)
{
hr = blob.Write(m_pValue, nLength, &nWritten);
if(SUCCEEDED(hr) && nWritten == nLength)
return true;
}
else
{
ISequentialStream* pStream = *(ISequentialStream**)m_pValue;
hr = blob.WriteFromStream(pStream, nLength, &nWritten);
pStream->Release();
if(SUCCEEDED(hr) && nWritten == nLength)
return true;
}
}
}
return false;
}
//-------------------------------------------------------------------------
//
// CDbValue
//
//-------------------------------------------------------------------------
CDbValue::CDbValue()
: CDbValueRef (DBTYPE_EMPTY, &m_nLength, &m_status, (BYTE*)&m_val),
m_nLength (0),
m_status (DBSTATUS_S_ISNULL)
{
memset(&m_val, 0, sizeof(m_val));
}
CDbValue::CDbValue(const CDbValue& dbVal)
{
InternalCopy(dbVal);
}
CDbValue::CDbValue(DBTYPE type, ULONG nLength, DBSTATUS status, const void* pData)
: CDbValueRef (DBTYPE_EMPTY, &m_nLength, &m_status, (BYTE*)&m_val),
m_nLength (nLength),
m_status (status)
{
memset(&m_val, 0, sizeof(m_val));
// SetValue(type, nLength, status, pData);
}
CDbValue::~CDbValue()
{
Clear();
}
void CDbValue::Initialize(DBTYPE type, ULONG nLength, ULONG nMaxLength, bool bIsLong)
{
Clear();
m_wType = type;
m_nMaxSize = nMaxLength;
m_nLength = nLength;
m_bIsLong = bIsLong;
}
// CDbValue::InternalCopy
//
// Copies two CDbValues
//
void CDbValue::InternalCopy(const CDbValue& dbVal)
{
Clear();
m_nLength = dbVal.m_nLength;
m_status = dbVal.m_status;
m_wType = dbVal.m_wType;
switch(m_wType)
{
case DBTYPE_WSTR:
m_val.pszVal = new TCHAR[m_nLength + 1];
if(m_val.pszVal != NULL)
wcscpy(m_val.pszVal, dbVal.m_val.pszVal);
else
m_status = DBSTATUS_E_OUTOFSPACE;
break;
case DBTYPE_BYTES:
m_val.pVal = new BYTE[m_nLength];
if(m_val.pVal != NULL)
memcpy(m_val.pVal, dbVal.m_val.pVal, m_nLength);
else
m_status = DBSTATUS_E_OUTOFSPACE;
break;
default:
memcpy(&m_val, &dbVal.m_val, sizeof(m_val));
}
}
// CDbValue::Clear
//
// Clears the value
//
void CDbValue::Clear()
{
if(m_wType == DBTYPE_WSTR)
{
delete [] m_val.pszVal;
m_val.pszVal = NULL;
}
else if(m_wType == DBTYPE_BYTES)
{
delete [] m_val.pVal;
m_val.pVal = NULL;
}
else
{
memset(&m_val, 0, sizeof(m_val));
}
m_nLength = 0;
m_status = DBSTATUS_S_ISNULL;
}
// CDbValue::operator =
//
// Assigns a CDbValue object to another
//
CDbValue& CDbValue::operator =(const OLEDBCLI::CDbValue &dbVal)
{
if(this != &dbVal)
InternalCopy(dbVal);
return *this;
}
// CDbValue::SetValue
//
// Sets a CDbValue from an OLE DB column definition
//
void CDbValue::SetValue(DBTYPE type, ULONG nLength, DBSTATUS status, const void* pData)
{
Clear();
m_wType = type;
m_nLength = nLength;
m_status = status;
if(status != DBSTATUS_S_OK)
return;
ATLASSERT(pData != NULL);
switch(type)
{
case DBTYPE_UI1: m_val.bVal = *(BYTE*)pData; break;
case DBTYPE_I2: m_val.shortVal = *(short*)pData; break;
case DBTYPE_I4: m_val.intVal = *(int*)pData; break;
case DBTYPE_I8: m_val.lngVal = *(__int64*)pData; break;
case DBTYPE_R4: m_val.fltVal = *(float*)pData; break;
case DBTYPE_R8: m_val.dblVal = *(double*)pData; break;
case DBTYPE_CY: m_val.cyVal = *(CY*)pData; break;
case DBTYPE_GUID: m_val.guidVal = *(GUID*)pData; break;
case DBTYPE_BOOL: m_val.boolVal = *(VARIANT_BOOL*)pData; break;
case DBTYPE_DBTIMESTAMP:
memcpy(&m_val.dtVal, pData, sizeof(m_val.dtVal));
break;
case DBTYPE_NUMERIC:
memcpy(&m_val.numVal, pData, sizeof(m_val.numVal));
break;
case DBTYPE_BYTES:
m_val.pVal = new BYTE[nLength];
if(m_val.pVal != NULL)
{
memcpy(m_val.pVal, pData, nLength);
}
else
{
m_status = DBSTATUS_S_ISNULL;
m_nLength = 0;
}
break;
case DBTYPE_WSTR:
m_val.pszVal = new TCHAR[nLength + 1];
if(m_val.pszVal != NULL)
{
memset(m_val.pszVal, 0, sizeof(TCHAR) * (nLength + 1));
memcpy(m_val.pszVal, pData, nLength * sizeof(TCHAR));
}
else
{
m_status = DBSTATUS_S_ISNULL;
m_nLength = 0;
}
break;
}
}
// CDbValue::SetValue
//
// Sets a CDbValue from a BLOB
//
HRESULT CDbValue::SetValue(DBTYPE type, ULONG nLength, DBSTATUS status, ISequentialStream* pStream)
{
HRESULT hr = E_FAIL;
Clear();
m_wType = type;
m_nLength = nLength;
m_status = status;
if(status != DBSTATUS_S_OK)
return S_OK;
ATLASSERT(pStream != NULL);
ULONG nRead;
if(type == DBTYPE_WSTR)
{
m_val.pszVal = new TCHAR[nLength + 1];
if(m_val.pszVal != NULL)
{
memset(m_val.pszVal, 0, sizeof(TCHAR) * (nLength + 1));
hr = pStream->Read(m_val.pszVal, nLength * sizeof(TCHAR), &nRead);
}
else
{
m_nLength = 0;
m_status = DBSTATUS_S_ISNULL;
hr = E_OUTOFMEMORY;
}
}
else if(type == DBTYPE_BYTES)
{
m_val.pVal = new BYTE[nLength];
if(m_val.pVal != NULL)
{
hr = pStream->Read(m_val.pVal, nLength, &nRead);
}
else
{
m_nLength = 0;
m_status = DBSTATUS_S_ISNULL;
hr = E_OUTOFMEMORY;
}
}
return hr;
}
// CDbValue::SetValue
//
// Sets a string value allowing the string buffer to increase its maximum size.
// This is useful for command parameters where values are indirectly set through CDbValues.
//
bool CDbValue::SetValue(LPCTSTR pszVal)
{
if(m_wType == DBTYPE_WSTR)
{
ULONG nLength = wcslen(pszVal) + 1;
if(m_bIsLong)
{
SetValue(DBTYPE_WSTR, nLength, DBSTATUS_S_OK, pszVal);
if(m_nMaxSize < nLength)
m_nMaxSize = nLength;
}
else
{
if(nLength > m_nMaxSize)
nLength = m_nMaxSize;
SetValue(DBTYPE_WSTR, nLength, DBSTATUS_S_OK, pszVal);
}
return true;
}
return false;
}
bool CDbValue::SetValue(BYTE* pValue, ULONG nSize)
{
if(m_wType == DBTYPE_BYTES)
{
if(m_bIsLong)
{
SetValue(DBTYPE_BYTES, nSize, DBSTATUS_S_OK, pValue);
if(m_nMaxSize < nSize)
m_nMaxSize = nSize;
}
else
{
if(nSize > m_nMaxSize)
nSize = m_nMaxSize;
SetValue(DBTYPE_BYTES, nSize, DBSTATUS_S_OK, pValue);
}
return true;
}
return false;
}
// CDbValue::GetDataPtr
//
// Gets the underlying data pointer.
//
void* CDbValue::GetDataPtr()
{
if(m_wType == DBTYPE_WSTR)
return m_val.pszVal;
if(m_wType == DBTYPE_BYTES)
return m_val.pVal;
return &m_val;
}
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/AppState.h
// AppState.h
#ifndef __APP_STATE_H
#define __APP_STATE_H
#include "Windows/Synchronization.h"
#include "ViewSettings.h"
void inline AddUniqueStringToHead(UStringVector &list,
const UString &string)
{
for(int i = 0; i < list.Size();)
if (string.CompareNoCase(list[i]) == 0)
list.Delete(i);
else
i++;
list.Insert(0, string);
}
class CFastFolders
{
NWindows::NSynchronization::CCriticalSection _criticalSection;
public:
UStringVector Strings;
void SetString(int index, const UString &string)
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
while(Strings.Size() <= index)
Strings.Add(UString());
Strings[index] = string;
}
UString GetString(int index)
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
if (index >= Strings.Size())
return UString();
return Strings[index];
}
void Save()
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
SaveFastFolders(Strings);
}
void Read()
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
ReadFastFolders(Strings);
}
};
class CFolderHistory
{
NWindows::NSynchronization::CCriticalSection _criticalSection;
UStringVector Strings;
void Normalize()
{
const int kMaxSize = 100;
if (Strings.Size() > kMaxSize)
Strings.Delete(kMaxSize, Strings.Size() - kMaxSize);
}
public:
void GetList(UStringVector &foldersHistory)
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
foldersHistory = Strings;
}
void AddString(const UString &string)
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
AddUniqueStringToHead(Strings, string);
Normalize();
}
void RemoveAll()
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
Strings.Clear();
}
void Save()
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
SaveFolderHistory(Strings);
}
void Read()
{
NWindows::NSynchronization::CCriticalSectionLock lock(_criticalSection);
ReadFolderHistory(Strings);
Normalize();
}
};
struct CAppState
{
CFastFolders FastFolders;
CFolderHistory FolderHistory;
void Save()
{
FastFolders.Save();
FolderHistory.Save();
}
void Read()
{
FastFolders.Read();
FolderHistory.Read();
}
};
#endif<file_sep>/FingerSuite/FingerMenuDLL/InterceptEngine.cpp
#include "stdafx.h"
#include <windows.h>
#include "hook\SysDecls.h"
#include "hook\undocWM5.h"
#include "InterceptEngine.h"
#include <tlhelp32.h>
#include "..\Common\log\logger.h"
#include "..\Common\utils.h"
// globals
HINSTANCE g_hInst = NULL;
UINT UWM_INTERCEPT_MENU;
UINT UWM_INTERCEPT_MSGBOX;
UINT UWM_INTERCEPT_NOTIF;
UINT UWM_NOTIF_POPUP;
HWND g_hWndHHTaskBar = 0;
#pragma data_seg("SH_DATA")
// for SH_WMGR apiset replacement
CINFO * m_pNewWmgrApiSet = NULL;
CINFO * m_pOldWmgrApiSet = NULL;
// end SH_WMGR
// for SH_SHELL apiset replacement
CINFO * m_pNewShellApiSet = NULL;
CINFO * m_pOldShellApiSet = NULL;
// end SH_SHELL
HWND g_hWndServer = 0;
HWND g_hWndServerMsgBox = 0;
HWND g_hWndServerNotif = 0;
HANDLE m_hDestProcess = NULL;
HINSTANCE m_hDllInst = 0;
BOOL g_bTrackPopupMenuExResult = FALSE;
int g_iMsgBoxResult = 0;
PFNVOID g_pOrigTrackPopupMenuEx = NULL;
PFNVOID g_pOrigMessageBoxW = NULL;
PFNVOID g_pOrigSHNotificationAddII = NULL;
PFNVOID g_pOrigSHNotificationUpdateII = NULL;
PFNVOID g_pOrigSHNotificationRemoveII = NULL;
#pragma data_seg()
#pragma comment( linker, "/SECTION:SH_DATA,SRW" )
__declspec(dllexport)
HANDLE CreateWaitEvent(LPTSTR szEvt)
{
HANDLE hEvt = CreateEvent(NULL, TRUE, FALSE, szEvt);
if ( (hEvt != NULL) && (GetLastError() == ERROR_ALREADY_EXISTS) )
ResetEvent(hEvt);
return hEvt;
}
__declspec(dllexport)
BOOL ResetWaitEvent(LPTSTR szEvt)
{
HANDLE hEvt = OpenEvent(EVENT_ALL_ACCESS, FALSE, szEvt);
if (hEvt != NULL)
{
BOOL bRes = ResetEvent(hEvt);
CloseHandle(hEvt);
return bRes;
}
return FALSE;
}
__declspec(dllexport)
BOOL SignalWaitEvent(LPTSTR szEvt)
{
BOOL bRes = FALSE;
//wprintf(L"SignalWaitEvent...");
HANDLE hEvt = OpenEvent(EVENT_ALL_ACCESS, FALSE, szEvt);
if (hEvt != NULL)
{
bRes = SetEvent(hEvt);
CloseHandle(hEvt);
}
//wprintf(L"...done\n");
return bRes;
}
/*-------------------------------------------------------------
FUNCTION: HookTrackPopupMenuEx
PURPOSE: Interceptor for TrackPopupMenuEx API
Parameters and return value are identical to the documented
HookTrackPopupMenuEx function.
-------------------------------------------------------------*/
BOOL HookTrackPopupMenuEx
(
HMENU p_hmenu,
UINT p_uFlags,
int p_x,
int p_y,
HWND p_hWnd,
LPTPMPARAMS p_lptpm
)
{
BOOL bResult = FALSE;
if (!(IsWindow(g_hWndServer)))
goto normal;
if (p_hWnd == g_hWndHHTaskBar)
goto normal;
UINT msgToBeSent = UWM_INTERCEPT_MENU;
//if (p_uFlags & TPM_RETURNCMD)
TRACKPOPUPMENUINFO info;
info.hMenu = p_hmenu;
info.hWnd = p_hWnd;
info.uFlags = p_uFlags;
BOOL bInterceptRes = (BOOL)SendMessageRemote(g_hWndServer, msgToBeSent, (WPARAM)0, (LPARAM)&info, sizeof(TRACKPOPUPMENUINFO));
if (bInterceptRes)
{
goto normal;
}
HANDLE arr[1];
arr[0] = CreateWaitEvent(EVT_FNGRMENU);
DWORD dwRes;
MSG msg;
do
{
dwRes = MsgWaitForMultipleObjectsEx(1, arr, INFINITE, QS_ALLINPUT, 0);
if (dwRes != WAIT_OBJECT_0 + 0)
{
if (GetMessage( &msg, NULL, 0, 0 ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
}
while (dwRes != WAIT_OBJECT_0 + 0);
CloseHandle(arr[0]);
if (g_bTrackPopupMenuExResult == -1)
{
goto normal;
}
if (p_uFlags & TPM_RETURNCMD)
{
// calling process should call SetTrackPopupMenuExResult
return g_bTrackPopupMenuExResult;
}
else
return bResult;
normal:
if(g_pOrigTrackPopupMenuEx)
{
bResult = ((BOOL (*)(
HMENU, UINT, int, int,
HWND, LPTPMPARAMS))g_pOrigTrackPopupMenuEx)
(
p_hmenu,
p_uFlags,
p_x,
p_y,
p_hWnd,
p_lptpm
);
}//if(g_pOrigTrackPopupMenuEx)
return bResult;
}//HANDLE HookTrackPopupMenuEx
/*-------------------------------------------------------------
BOOL HookTrackPopupMenuEx
(
HMENU p_hmenu,
UINT p_uFlags,
int p_x,
int p_y,
HWND p_hWnd,
LPTPMPARAMS p_lptpm
)
{
BOOL bResult = FALSE;
if (!(IsWindow(g_hWndServer)))
goto normal;
if (p_hWnd == g_hWndHHTaskBar)
goto normal;
UINT msg = 0;
if (p_uFlags & TPM_RETURNCMD)
msg = UWM_INTERCEPT_MENU2;
else
msg = UWM_INTERCEPT_MENU1;
BOOL bInterceptRes = (BOOL)SendMessage(g_hWndServer, msg, (WPARAM)p_hmenu, (LPARAM)p_hWnd);
if (bInterceptRes)
{
goto normal;
}
HANDLE hEvt = CreateWaitEvent(EVT_FNGRMENU);
DWORD dwRes = WaitForSingleObject(hEvt, INFINITE);
if (dwRes == WAIT_OBJECT_0)
{
}
CloseHandle(hEvt);
if (g_bTrackPopupMenuExResult == -1)
{
goto normal;
}
if (p_uFlags & TPM_RETURNCMD)
{
// calling process should call SetTrackPopupMenuExResult
return g_bTrackPopupMenuExResult;
}
else
return bResult;
normal:
if(g_pOrigTrackPopupMenuEx)
{
bResult = ((BOOL (*)(
HMENU, UINT, int, int,
HWND, LPTPMPARAMS))g_pOrigTrackPopupMenuEx)
(
p_hmenu,
p_uFlags,
p_x,
p_y,
p_hWnd,
p_lptpm
);
}//if(g_pOrigTrackPopupMenuEx)
return bResult;
}
int HookMessageBoxW(
HWND hwnd,
const WCHAR* szText,
const WCHAR* szCaption,
UINT uType,
MSG* pMsg
)
{
int iResult = 0;
if (!(IsWindow(g_hWndServerMsgBox)))
goto normal;
LPMSGBOXINFO info = (MSGBOXINFO*)g_sharedMsgBoxMem.GetValue();
ZeroMemory(info, sizeof(MSGBOXINFO));
wsprintf(info->szCaption, L"%s", szCaption);
wsprintf(info->szText, L"%s", szText);
//g_sharedMsgBoxMem.SetValue(&info, sizeof(info));
BOOL bInterceptRes = (BOOL)SendMessage(g_hWndServerMsgBox, UWM_INTERCEPT_MSGBOX, (WPARAM)hwnd, (LPARAM)uType);
if (bInterceptRes)
{
goto normal;
}
HANDLE hEvt = CreateWaitEvent(EVT_FNGRMSGBOX);
DWORD dwRes = WaitForSingleObject(hEvt, INFINITE);
if (dwRes == WAIT_OBJECT_0)
{
if (g_iMsgBoxResult == -1)
{
goto normal;
}
return g_iMsgBoxResult;
}
normal:
if (g_pOrigMessageBoxW)
{
iResult = ((int (*)(HWND,
const WCHAR*,
const WCHAR*,
UINT,
MSG*))g_pOrigMessageBoxW)
(
hwnd,
szText,
szCaption,
uType,
pMsg
);
}//if(g_pOrigMessageBoxW)
return iResult;
}
-------------------------------------------------------------*/
int HookMessageBoxW(
HWND hwnd,
const WCHAR* szText,
const WCHAR* szCaption,
UINT uType,
MSG* pMsg
)
{
int iResult = 0;
if (!(IsWindow(g_hWndServerMsgBox)))
goto normal;
MSGBOXINFO info;
info.hWnd = hwnd;
info.uType = uType;
wsprintf(info.szCaption, L"%s", szCaption);
wsprintf(info.szText, L"%s", szText);
BOOL bInterceptRes = (BOOL)SendMessageRemote(g_hWndServerMsgBox, UWM_INTERCEPT_MSGBOX, (WPARAM)0, (LPARAM)&info, sizeof(MSGBOXINFO));
if (bInterceptRes)
{
goto normal;
}
HANDLE arr[1];
arr[0] = CreateWaitEvent(EVT_FNGRMSGBOX);
DWORD dwRes;
do
{
dwRes = MsgWaitForMultipleObjectsEx(1, arr, INFINITE, QS_ALLINPUT, 0);
if (dwRes != WAIT_OBJECT_0 + 0)
{
MSG msg;
if (GetMessage( &msg, NULL, 0, 0 ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
}
}
while (dwRes != WAIT_OBJECT_0 + 0);
CloseHandle(arr[0]);
if (dwRes == WAIT_OBJECT_0)
{
if (g_iMsgBoxResult == -1)
{
goto normal;
}
return g_iMsgBoxResult;
}
normal:
if (g_pOrigMessageBoxW)
{
iResult = ((int (*)(HWND,
const WCHAR*,
const WCHAR*,
UINT,
MSG*))g_pOrigMessageBoxW)
(
hwnd,
szText,
szCaption,
uType,
pMsg
);
}//if(g_pOrigMessageBoxW)
return iResult;
}
/*-------------------------------------------------------------------
FUNCTION: DllMain
PURPOSE: Regular DLL initialization point. Used to initialize
per-process data structures, such as the tracing engine
-------------------------------------------------------------------*/
BOOL WINAPI DllMain(HANDLE hInstance, DWORD dwReason,
LPVOID /*lpReserved*/)
{
TCHAR l_szPath[_MAX_PATH];
*l_szPath = 0;
GetModuleFileName(NULL, l_szPath, _MAX_PATH);
static long s_lLoadCount = 0;
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
{
g_hInst = (HINSTANCE)hInstance;
UWM_INTERCEPT_MENU = RegisterWindowMessage(UWM_INTERCEPT_MENU_MSG);
UWM_INTERCEPT_MSGBOX = RegisterWindowMessage(UWM_INTERCEPT_MSGBOX_MSG);
UWM_INTERCEPT_NOTIF = RegisterWindowMessage(UWM_INTERCEPT_NOTIF_MSG);
UWM_NOTIF_POPUP = RegisterWindowMessage(UWM_NOTIF_POPUP_MSG);
g_hWndHHTaskBar = FindWindow(L"HHTaskBar", NULL);
if(InterlockedIncrement(&s_lLoadCount) == 1)
{
DWORD l_dwOldProtect;
BOOL bRes = VirtualProtect(&m_pNewWmgrApiSet, sizeof(m_pNewWmgrApiSet),
PAGE_READWRITE | PAGE_NOCACHE, &l_dwOldProtect);
}
}
break;
case DLL_PROCESS_DETACH:
{
if(InterlockedDecrement(&s_lLoadCount) == 0)
{
}
}
break;
}
return TRUE;
}//BOOL WINAPI DllMain
__declspec(dllexport)
BOOL SetHWndServer(HWND hWndServer)
{
g_hWndServer = hWndServer;
return TRUE;
}
__declspec(dllexport)
BOOL SetHWndServerMsgBox(HWND hWndServer)
{
g_hWndServerMsgBox = hWndServer;
return TRUE;
}
__declspec(dllexport)
BOOL SetHWndServerNotif(HWND hWndServer)
{
g_hWndServerNotif = hWndServer;
return TRUE;
}
/*-------------------------------------------------------------------
FUNCTION: ProcessAddress
PURPOSE:
returns an address of memory slot for the given process index.
PARAMETERS:
BYTE p_byProcNum - process number (slot index) between 0 and 31
RETURNS:
Address of the memory slot.
-------------------------------------------------------------------*/
inline DWORD ProcessAddress(BYTE p_byProcNum)
{
return 0x02000000 * (p_byProcNum+1);
}
/*-------------------------------------------------------------------
FUNCTION: ConvertAddr
PURPOSE:
ConvertAddr does the same as MapPtrToProcess - maps an address in
slot 0 to the address in the slot of the given process. Unlike
MapPtrToProcess, which accepts process handle, ConvertAddr uses
undocumented PROCESS structure.
PARAMETERS:
LPVOID p_pAddr - address to convert
PPROCESS p_pProcess - internal kernel Process structure
RETURNS:
Address mapped to the slot of the given process
-------------------------------------------------------------------*/
LPVOID ConvertAddr(LPVOID p_pAddr, PPROCESS p_pProcess)
{
if( ((DWORD)p_pAddr) < 0x2000000 && p_pProcess)
{//Slot 0 and process is not the kernel
LPVOID l_pOld = p_pAddr;
BYTE l_byProcNum =
*(((LPBYTE)p_pProcess) + PROCESS_NUM_OFFSET);
p_pAddr = (LPVOID) (((DWORD)p_pAddr) +
ProcessAddress(l_byProcNum));
}
return p_pAddr;
}
int FilterException(LPEXCEPTION_POINTERS pEx)
{
DWORD exCode = pEx->ExceptionRecord->ExceptionCode;
BOOL bRes = (exCode == EXCEPTION_ACCESS_VIOLATION);
return EXCEPTION_EXECUTE_HANDLER;
}
void * AllocateMemInKernelProc(int p_iSize)
{
LPVOID pAllocated = NULL;
// find process id of nk.exe
HANDLE snapShot = INVALID_HANDLE_VALUE;
DWORD dwNKProcessId = 0;
__try
{
snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPNOHEAPS, 0);
if (snapShot != INVALID_HANDLE_VALUE)
{
// Build new list
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
BOOL ret = Process32First(snapShot, &processEntry);
while (ret == TRUE)
{
if (lstrcmpi(processEntry.szExeFile, L"nk.exe") == 0)
{
dwNKProcessId = processEntry.th32ProcessID;
break;
}
ret = Process32Next(snapShot, &processEntry);
}
CloseToolhelp32Snapshot(snapShot);
}
} __except (EXCEPTION_EXECUTE_HANDLER)
{
if (snapShot != INVALID_HANDLE_VALUE)
{
CloseToolhelp32Snapshot(snapShot);
}
return NULL;
}
HANDLE hNKProcess = OpenProcess(0, FALSE, dwNKProcessId);
if (hNKProcess == NULL)
return NULL;
HINSTANCE hCoreDll = LoadLibrary(_T("COREDLL"));
CALLBACKINFO cbi;
cbi.m_hDestinationProcessHandle = hNKProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(hCoreDll, L"VirtualAlloc"), hNKProcess);
cbi.m_pFirstArgument = (LPVOID)0;
DWORD dwParam2 = p_iSize;
DWORD dwParam3 = MEM_COMMIT;
DWORD dwParam4 = PAGE_EXECUTE_READWRITE;
DWORD dwPtr = PerformCallBack4(&cbi, dwParam2, dwParam3, dwParam4); //returns 1 if correctly executed
pAllocated = MapPtrToProcess( (LPVOID)dwPtr, hNKProcess);
CloseHandle(hNKProcess);
return pAllocated;
}
__declspec(dllexport)
BOOL InstallHook()
{
static long s_lCount = 0;
if (InterlockedIncrement(&s_lCount) > 1)
{
// no need to install again
return TRUE;
}
BOOL bResult = TRUE;
if (m_hDestProcess == NULL)
{
int iAPISetId = SH_WMGR;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
CINFO ** pSystemAPISets = (CINFO**)(UserKInfo[KINX_APISETS]);
m_hDestProcess = pSystemAPISets[iAPISetId]->m_pProcessServer->hProc;
CALLBACKINFO cbi;
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = m_hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(GetModuleHandle(L"COREDLL"), L"LoadLibraryW"), m_hDestProcess);
cbi.m_pFirstArgument = (LPVOID)MapPtrToProcess(L"\\Windows\\FingerSuiteDll.dll", GetCurrentProcess());
m_hDllInst = (HINSTANCE)PerformCallBack4(&cbi, 0,0,0); //returns the HINSTANCE from LoadLibraryW
Sleep(1000);
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = m_hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(m_hDllInst, L"StartHookOnServer"), m_hDestProcess);
cbi.m_pFirstArgument = NULL;
DWORD dw = PerformCallBack4(&cbi, 0,0,0); //returns 1 if correctly executed
Sleep(1000);
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
}
return bResult;
}
__declspec(dllexport)
BOOL RemoveHook()
{
static long s_lCount = 0;
if (InterlockedIncrement(&s_lCount) > 1)
{
// no need to remove now
return TRUE;
}
BOOL bResult = TRUE;
if (m_hDestProcess != NULL)
{
int iAPISetId = SH_WMGR;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
CALLBACKINFO cbi;
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = m_hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(m_hDllInst, L"StopHookOnServer"), m_hDestProcess);
cbi.m_pFirstArgument = NULL;
BOOL bRes = (BOOL)PerformCallBack4(&cbi, 0,0,0); //returns the HINSTANCE from LoadLibraryW
Sleep(1000);
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = m_hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(GetModuleHandle(L"COREDLL"), L"FreeLibraryW"), m_hDestProcess);
cbi.m_pFirstArgument = m_hDllInst;
bRes = (BOOL)PerformCallBack4(&cbi, 0,0,0); //returns the HINSTANCE from LoadLibraryW
Sleep(1000);
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
}
StopHookOnSIP();
return bResult;
}
__declspec(dllexport)
BOOL StartHookOnServer()
{
BOOL bResult = TRUE;
int iAPISetId = SH_WMGR;
int iMethodIndex = WMGR_TrackPopupMenuEx;
int iMethodIndex2 = WMGR_MessageBoxW;
//HANDLE hCurProc = GetCurrentProcess();
CINFO * pOrigApiSet; pOrigApiSet = NULL;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
CINFO ** pSystemAPISets = (CINFO**)(UserKInfo[KINX_APISETS]);
pOrigApiSet = pSystemAPISets[iAPISetId];
PFNVOID * pHookMthds = NULL;
DWORD * pdwHookSignatures = NULL;
PFNVOID * pOrigMethods = (PFNVOID *)ConvertAddr(pOrigApiSet->m_ppMethods, pOrigApiSet->m_pProcessServer);
DWORD * pOrigSignatures = (DWORD *)ConvertAddr(pOrigApiSet->m_pdwMethodSignatures, pOrigApiSet->m_pProcessServer);
m_pNewWmgrApiSet = (CINFO *)AllocateMemInKernelProc(sizeof(CINFO));
int iNewNumMethods = pOrigApiSet->m_wNumMethods;
// duplicate method table
int iSize = (sizeof(PFNVOID) * iNewNumMethods + sizeof(DWORD) * iNewNumMethods);
LPBYTE pRemoteMem = (LPBYTE)AllocateMemInKernelProc(iSize);
pHookMthds = (PFNVOID *)pRemoteMem;
pdwHookSignatures = (DWORD*)(pRemoteMem + sizeof(PFNVOID)*iNewNumMethods);
for (int i = 0; i < iNewNumMethods; i++)
{
pHookMthds[i] = pOrigMethods[i];
pdwHookSignatures[i] = pOrigSignatures? pOrigSignatures[i] : FNSIG0();
}
memcpy(m_pNewWmgrApiSet, pOrigApiSet, sizeof(CINFO));
//But replace the method and signature tables:
m_pNewWmgrApiSet->m_ppMethods = pHookMthds;
m_pNewWmgrApiSet->m_pdwMethodSignatures = pdwHookSignatures;
m_pNewWmgrApiSet->m_wNumMethods = (WORD)iNewNumMethods;
// replace pointer with hooked procedure
g_pOrigTrackPopupMenuEx = ((PFNVOID *)m_pNewWmgrApiSet->m_ppMethods)[iMethodIndex];
((PFNVOID *)m_pNewWmgrApiSet->m_ppMethods)[iMethodIndex] = (PFNVOID)HookTrackPopupMenuEx;
g_pOrigMessageBoxW = ((PFNVOID *)m_pNewWmgrApiSet->m_ppMethods)[iMethodIndex2];
((PFNVOID *)m_pNewWmgrApiSet->m_ppMethods)[iMethodIndex2] = (PFNVOID)HookMessageBoxW;
//And finally, replace the pointer to the original CINFO
//by the pointer to ours.
m_pOldWmgrApiSet = pSystemAPISets[iAPISetId];
pSystemAPISets[iAPISetId] = m_pNewWmgrApiSet;
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
return bResult;
}
__declspec(dllexport)
BOOL StopHookOnServer()
{
BOOL bResult = TRUE;
int iAPISetId = SH_WMGR;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
CINFO ** pSystemAPISets = (CINFO**)(UserKInfo[KINX_APISETS]);
//restore the pointer to the original CINFO
if (m_pOldWmgrApiSet != NULL)
{
pSystemAPISets[iAPISetId] = m_pOldWmgrApiSet;
// TODO
// free mem allocated for m_pNewApiSet
}
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
return bResult;
}
__declspec(dllexport)
void SetMsgBoxResult(int iResult)
{
g_iMsgBoxResult = iResult;
}
__declspec(dllexport)
void SetTrackPopupMenuExResult(BOOL bResult)
{
g_bTrackPopupMenuExResult = bResult;
}
/// SHELL ////////////////
//////////////////////////
LRESULT UpdateBuffer(LPNOTIFICATIONINFO pInfo, const CLSID *pclsid, DWORD dwID, DWORD grfFlagsOriginal)
{
SHNOTIFICATIONDATA shnd;
ZeroMemory(&shnd, sizeof(SHNOTIFICATIONDATA));
shnd.cbStruct = sizeof(SHNOTIFICATIONDATA);
LRESULT lRes = SHNotificationGetData(pclsid, dwID, &shnd);
// notification data
if (lRes == ERROR_SUCCESS)
{
ZeroMemory(pInfo, sizeof(NOTIFICATIONINFO));
memcpy(&pInfo->nd, &shnd, sizeof(SHNOTIFICATIONDATA));
pInfo->grfFlagsOriginal = grfFlagsOriginal;
// strings
wsprintf(pInfo->szTitle, L"%s", shnd.pszTitle);
wsprintf(pInfo->szHTML, L"%s", shnd.pszHTML);
if (shnd.pszHTML)
free((LPVOID)shnd.pszHTML);
shnd.pszHTML = NULL;
if (shnd.pszTitle)
free((LPVOID)shnd.pszTitle);
shnd.pszTitle = NULL;
// adjust pointers
pInfo->nd.pszTitle = pInfo->szTitle;
pInfo->nd.pszHTML = pInfo->szHTML;
// menu
if (shnd.grfFlags & SHNF_HASMENU)
{
memcpy(pInfo->rgskc, shnd.skm.prgskc, sizeof(SOFTKEYMENU) * shnd.skm.cskc);
// adjust pointers
pInfo->nd.skm.prgskc = pInfo->rgskc;
}
else
{
if (shnd.rgskn[0].pszTitle != NULL) wsprintf(pInfo->sk1Title, L"%s", shnd.rgskn[0].pszTitle);
if (shnd.rgskn[1].pszTitle != NULL) wsprintf(pInfo->sk2Title, L"%s", shnd.rgskn[1].pszTitle);
// adjust pointers
pInfo->nd.rgskn[0].pszTitle = pInfo->sk1Title;
pInfo->nd.rgskn[1].pszTitle = pInfo->sk2Title;
}
}
return lRes;
}
LRESULT WINAPI HookSHNotificationAddII( SHNOTIFICATIONDATA *pndAdd, DWORD cbData, LPTSTR pszTitle, LPTSTR pszHTML )
{
LRESULT lResult = ERROR_INVALID_PARAMETER;
NOTIFICATIONINFO info;
DWORD grfFlagsOriginal = pndAdd->grfFlags;
BOOL bIsManaged = IsManagedNotification(pndAdd->clsid);
if ((IsWindow(g_hWndServerNotif)) && (pndAdd->npPriority & SHNP_INFORM) && (bIsManaged))
{
//modifica parametri pndAdd
pndAdd->grfFlags |= SHNF_STRAIGHTTOTRAY;
pndAdd->grfFlags &= (~SHNF_FORCEMESSAGE);
}
if (g_pOrigSHNotificationAddII)
{
lResult = ((LRESULT (*)(
SHNOTIFICATIONDATA *, DWORD, LPTSTR, LPTSTR))g_pOrigSHNotificationAddII)
(
pndAdd,
cbData,
pszTitle,
pszHTML
);
} //if (g_pOrigSHNotificationAddII)
if (lResult != ERROR_SUCCESS)
goto normal;
if (pndAdd->npPriority == SHNP_ICONIC)
goto normal;
if (!(IsWindow(g_hWndServerNotif)))
goto normal;
lResult = UpdateBuffer(&info, &pndAdd->clsid, pndAdd->dwID, grfFlagsOriginal);
info.isManaged = bIsManaged;
BOOL bInterceptRes = (BOOL)SendMessageRemote(g_hWndServerNotif, UWM_INTERCEPT_NOTIF, NOTIF_ADD, (LPARAM)&info, sizeof(NOTIFICATIONINFO));
if (bInterceptRes)
{
goto normal;
}
normal:
return lResult;
}
LRESULT WINAPI HookSHNotificationUpdateII(DWORD grnumUpdateMask, SHNOTIFICATIONDATA *pndNew, DWORD cbData, LPTSTR pszTitle, LPTSTR pszHTML)
{
LRESULT lResult = ERROR_INVALID_PARAMETER;
NOTIFICATIONINFO info;
DWORD grfFlagsOriginal = pndNew->grfFlags;
BOOL bIsManaged = IsManagedNotification(pndNew->clsid);
if (IsWindow(g_hWndServerNotif) && (bIsManaged))
{
pndNew->grfFlags |= SHNF_STRAIGHTTOTRAY;
pndNew->grfFlags &= (~SHNF_FORCEMESSAGE);
}
if (g_pOrigSHNotificationUpdateII)
{
lResult = ((LRESULT (*)(
DWORD, SHNOTIFICATIONDATA *, DWORD, LPTSTR, LPTSTR))g_pOrigSHNotificationUpdateII)
(
grnumUpdateMask,
pndNew,
cbData,
pszTitle,
pszHTML
);
} //if (g_pOrigSHNotificationUpdateII)
if (lResult != ERROR_SUCCESS)
goto normal;
if (!(IsWindow(g_hWndServerNotif)))
goto normal;
lResult = UpdateBuffer(&info, &pndNew->clsid, pndNew->dwID, grfFlagsOriginal);
if (lResult != ERROR_SUCCESS)
goto normal;
info.isManaged = bIsManaged;
BOOL bInterceptRes = (BOOL)SendMessageRemote(g_hWndServerNotif, UWM_INTERCEPT_NOTIF, NOTIF_UPD, (LPARAM)&info, sizeof(NOTIFICATIONINFO));
if (bInterceptRes)
{
goto normal;
}
normal:
return lResult;
}
LRESULT WINAPI HookSHNotificationRemoveII(const CLSID *pclsid, DWORD cbCLSID, DWORD dwID)
{
LRESULT lResult = ERROR_INVALID_PARAMETER;
if (IsWindow(g_hWndServerNotif))
{
}
NOTIFICATIONINFO info;
ZeroMemory(&info, sizeof(NOTIFICATIONINFO));
memcpy(&info.nd.clsid, pclsid, sizeof(CLSID));
info.nd.dwID = dwID;
if (g_pOrigSHNotificationRemoveII)
{
lResult = ((LRESULT (*)(
const CLSID *, DWORD, DWORD))g_pOrigSHNotificationRemoveII)
(
pclsid,
cbCLSID,
dwID
);
} //if (g_pOrigSHNotificationRemoveII)
if (lResult != ERROR_SUCCESS)
goto normal;
if (!(IsWindow(g_hWndServerNotif)))
goto normal;
BOOL bInterceptRes = (BOOL)SendMessageRemote(g_hWndServerNotif, UWM_INTERCEPT_NOTIF, NOTIF_DEL, (LPARAM)&info, sizeof(NOTIFICATIONINFO));
if (bInterceptRes)
{
goto normal;
}
normal:
return lResult;
}
// NON SERVE PIU
/*
BOOL WINAPI HookShell_NotifyIconI(DWORD dwMsg, PNOTIFYICONDATA pNID, DWORD cbNID)
{
LOG(L"Start HookShell_NotifyIconI ...\n");
BOOL bResult = FALSE;
LPNOTIFICATIONINFO info = NULL;
if (IsWindow(g_hWndServerNotif))
{
info = (NOTIFICATIONINFO*)g_sharedNotifMem.GetValue();
ZeroMemory(info, sizeof(NOTIFICATIONINFO));
info->dwType = NTF_TYPE_NOTIFYICONDATA;
info->info2.dwMessage = dwMsg;
memcpy(&info->info2.nid, pNID, sizeof(PNOTIFYICONDATA));
//modifica parametri pndAdd
//pndAdd->npPriority = SHNP_ICONIC;
}
if (g_pOrigShell_NotifyIconI)
{
bResult = ((BOOL (*)(
DWORD, PNOTIFYICONDATA, DWORD))g_pOrigShell_NotifyIconI)
(
dwMsg,
pNID,
cbNID
);
} //if (g_pOrigShell_NotifyIconI)
if (bResult == FALSE)
goto normal;
if (!(IsWindow(g_hWndServerNotif)))
goto normal;
BOOL bInterceptRes = (BOOL)SendMessage(g_hWndServerNotif, UWM_INTERCEPT_SHELLNOTIFICON, 0, 0);
if (bInterceptRes)
{
goto normal;
}
normal:
LOG(L"End HookShell_NotifyIconI .....\n");
return bResult;
}
*/
__declspec(dllexport)
BOOL InstallHookOnShell()
{
static long s_lCount = 0;
if (InterlockedIncrement(&s_lCount) > 1)
{
// no need to install again
return TRUE;
}
BOOL bResult = TRUE;
HANDLE hDestProcess = NULL;
HINSTANCE hDllInst = 0;
int iAPISetId = SH_SHELL;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
CINFO ** pSystemAPISets = (CINFO**)(UserKInfo[KINX_APISETS]);
hDestProcess = pSystemAPISets[iAPISetId]->m_pProcessServer->hProc; // should be shell32.exe
CALLBACKINFO cbi;
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(GetModuleHandle(L"COREDLL"), L"LoadLibraryW"), hDestProcess);
cbi.m_pFirstArgument = (LPVOID)MapPtrToProcess(L"\\Windows\\FingerSuiteDll.dll", GetCurrentProcess());
hDllInst = (HINSTANCE)PerformCallBack4(&cbi, 0,0,0); //returns the HINSTANCE from LoadLibraryW
Sleep(1000);
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(hDllInst, L"StartHookOnShellServer"), hDestProcess);
cbi.m_pFirstArgument = NULL;
DWORD dw = PerformCallBack4(&cbi, 0,0,0); //returns 1 if correctly executed
Sleep(1000);
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
return bResult;
}
__declspec(dllexport)
BOOL StartHookOnShellServer()
{
BOOL bResult = TRUE;
int iAPISetId = SH_SHELL;
int iMethodIndex = SHELL_SHNotificationAddII;
int iMethodIndex2 = SHELL_SHNotificationUpdateII;
int iMethodIndex3 = SHELL_SHNotificationRemoveII;
//HANDLE hCurProc = GetCurrentProcess();
CINFO * pOrigApiSet; pOrigApiSet = NULL;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
CINFO ** pSystemAPISets = (CINFO**)(UserKInfo[KINX_APISETS]);
pOrigApiSet = pSystemAPISets[iAPISetId];
PFNVOID * pHookMthds = NULL;
DWORD * pdwHookSignatures = NULL;
PFNVOID * pOrigMethods = (PFNVOID *)ConvertAddr(pOrigApiSet->m_ppMethods, pOrigApiSet->m_pProcessServer);
DWORD * pOrigSignatures = (DWORD *)ConvertAddr(pOrigApiSet->m_pdwMethodSignatures, pOrigApiSet->m_pProcessServer);
m_pNewShellApiSet = (CINFO *)AllocateMemInKernelProc(sizeof(CINFO));
int iNewNumMethods = pOrigApiSet->m_wNumMethods;
// duplicate method table
int iSize = (sizeof(PFNVOID) * iNewNumMethods + sizeof(DWORD) * iNewNumMethods);
LPBYTE pRemoteMem = (LPBYTE)AllocateMemInKernelProc(iSize);
pHookMthds = (PFNVOID *)pRemoteMem;
pdwHookSignatures = (DWORD*)(pRemoteMem + sizeof(PFNVOID)*iNewNumMethods);
for (int i = 0; i < iNewNumMethods; i++)
{
pHookMthds[i] = pOrigMethods[i];
pdwHookSignatures[i] = pOrigSignatures? pOrigSignatures[i] : FNSIG0();
}
memcpy(m_pNewShellApiSet, pOrigApiSet, sizeof(CINFO));
//But replace the method and signature tables:
m_pNewShellApiSet->m_ppMethods = pHookMthds;
m_pNewShellApiSet->m_pdwMethodSignatures = pdwHookSignatures;
m_pNewShellApiSet->m_wNumMethods = (WORD)iNewNumMethods;
// replace pointer with hooked procedure
g_pOrigSHNotificationAddII = ((PFNVOID *)m_pNewShellApiSet->m_ppMethods)[iMethodIndex];
((PFNVOID *)m_pNewShellApiSet->m_ppMethods)[iMethodIndex] = (PFNVOID)HookSHNotificationAddII;
g_pOrigSHNotificationUpdateII = ((PFNVOID *)m_pNewShellApiSet->m_ppMethods)[iMethodIndex2];
((PFNVOID *)m_pNewShellApiSet->m_ppMethods)[iMethodIndex2] = (PFNVOID)HookSHNotificationUpdateII;
g_pOrigSHNotificationRemoveII = ((PFNVOID *)m_pNewShellApiSet->m_ppMethods)[iMethodIndex3];
((PFNVOID *)m_pNewShellApiSet->m_ppMethods)[iMethodIndex3] = (PFNVOID)HookSHNotificationRemoveII;
//And finally, replace the pointer to the original CINFO
//by the pointer to ours.
m_pOldShellApiSet = pSystemAPISets[iAPISetId];
pSystemAPISets[iAPISetId] = m_pNewShellApiSet;
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
return bResult;
}
/////////////////////////////////// SIP BUTTON HOOK //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
////// SIP Hook
LONG oldSIPBtnWindowProc;
DWORD dwSIPBtnStartTime;
DWORD dwSIPBtnInterval;
LRESULT CALLBACK newSIPBtnWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
//LOG(L"Interceptiong SIP Button message...\n");
BOOL bStartSIPMenu = FALSE;
if (!(IsWindow(g_hWndServer)))
goto normal;
switch (uMsg){
case WM_LBUTTONDOWN:
dwSIPBtnStartTime = ::GetTickCount();
break;
case WM_LBUTTONUP:
if ((::GetTickCount() - dwSIPBtnStartTime) > dwSIPBtnInterval)
bStartSIPMenu = TRUE;
break;
default:
break;
}
normal:
LRESULT lResult = CallWindowProc((WNDPROC)oldSIPBtnWindowProc, hwnd, uMsg, wParam, lParam);
if (bStartSIPMenu)
{
RECT rc; ::GetClientRect(hwnd, &rc);
LPARAM lParam = ((rc.bottom / 2) << 16) + (rc.right - 10);
::PostMessage(hwnd, WM_LBUTTONDOWN, (WPARAM)0x00000001, lParam);
}
return lResult;
}
__declspec(dllexport)
BOOL StartHookOnSIP()
{
BOOL bResult = TRUE;
HWND hWndSIPButton = ::FindWindow(L"MS_SIPBUTTON", NULL);
if (hWndSIPButton != NULL)
{
HWND hWndToolbar = ::GetWindow(hWndSIPButton, GW_CHILD);
if (hWndToolbar != NULL)
{
oldSIPBtnWindowProc = ::GetWindowLong(hWndToolbar, GWL_WNDPROC);
if (::SetWindowLong(hWndToolbar, GWL_WNDPROC, (LONG)newSIPBtnWindowProc) == 0)
{
LOG(L"Errore StartHookOnSIP\n");
return FALSE;
}
}
}
if (RegistryGetDWORD(HKEY_LOCAL_MACHINE, L"Software\\FingerMenu", L"SIPBtnPressInterval", &dwSIPBtnInterval) != S_OK)
dwSIPBtnInterval = 500;
LOG(L"StartHookOnSIP OK\n");
return TRUE;
}
__declspec(dllexport)
BOOL StopHookOnSIP()
{
BOOL bResult = TRUE;
HWND hWndSIPButton = ::FindWindow(L"MS_SIPBUTTON", NULL);
if (hWndSIPButton != NULL)
{
HWND hWndToolbar = ::GetWindow(hWndSIPButton, GW_CHILD);
if (hWndToolbar != NULL)
{
if (oldSIPBtnWindowProc != NULL)
::SetWindowLong(hWndToolbar, GWL_WNDPROC, (LONG)oldSIPBtnWindowProc);
}
}
LOG(L"StopHookOnSIP OK\n");
return TRUE;
}
__declspec(dllexport)
BOOL InstallHookOnSIP()
{
static long s_lCount = 0;
if (InterlockedIncrement(&s_lCount) > 1)
{
// no need to install again
return TRUE;
}
BOOL bResult = TRUE;
HANDLE hDestProcess = NULL;
HINSTANCE hDllInst = 0;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
HWND hWndSIPButton = ::FindWindow(L"MS_SIPBUTTON", NULL);
DWORD dwProcessId; GetWindowThreadProcessId(hWndSIPButton, &dwProcessId);
hDestProcess = (HANDLE)dwProcessId;
CALLBACKINFO cbi;
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(GetModuleHandle(L"COREDLL"), L"LoadLibraryW"), hDestProcess);
cbi.m_pFirstArgument = (LPVOID)MapPtrToProcess(L"\\Windows\\FingerSuiteDll.dll", GetCurrentProcess());
hDllInst = (HINSTANCE)PerformCallBack4(&cbi, 0,0,0); //returns the HINSTANCE from LoadLibraryW
Sleep(1000);
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(hDllInst, L"StartHookOnSIP"), hDestProcess);
cbi.m_pFirstArgument = NULL;
DWORD dw = PerformCallBack4(&cbi, 0,0,0); //returns 1 if correctly executed
Sleep(1000);
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
return bResult;
}
/////////////////////////////////// TITLEBAR HOOK //////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
typedef enum {QVGA = 320, WQVGA = 400, VGA = 640, WVGA = 800} RESOLUTION;
int scaleFactor = 0;
LONG oldHHTaskbarWindowProc;
LRESULT CALLBACK newHHTaskbarWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
switch (uMsg){
case WM_LBUTTONDOWN:
if (!(::IsWindow(g_hWndServerNotif)))
break;
RECT rc; ::GetClientRect(hwnd, &rc);
::InflateRect(&rc, -27 * scaleFactor, 0); // only VGA
POINT pt; pt.x = LOWORD(lParam); pt.y = HIWORD(lParam);
if (::PtInRect(&rc, pt))
{
::PostMessage(g_hWndServerNotif, UWM_NOTIF_POPUP, 0, 0);
return 0;
}
break;
default:
break;
}
LRESULT lResult = CallWindowProc((WNDPROC)oldHHTaskbarWindowProc, hwnd, uMsg, wParam, lParam);
return lResult;
}
__declspec(dllexport)
BOOL StartHookOnHHTaskBar()
{
BOOL bResult = TRUE;
HWND hWndHHTaskbar = ::FindWindow(L"HHTaskBar", NULL);
if (hWndHHTaskbar != NULL)
{
oldHHTaskbarWindowProc = ::GetWindowLong(hWndHHTaskbar, GWL_WNDPROC);
if (::SetWindowLong(hWndHHTaskbar, GWL_WNDPROC, (LONG)newHHTaskbarWindowProc) == 0)
{
LOG(L"Errore StartHookOnHHTaskBar\n");
return FALSE;
}
}
// detect resolution
RESOLUTION resolution = QVGA;
DEVMODE dm;
::ZeroMemory(&dm, sizeof(DEVMODE));
dm.dmSize = sizeof(DEVMODE);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm))
{
resolution = (RESOLUTION)dm.dmPelsHeight;
}
// load icon images
switch (resolution)
{
case QVGA:
case WQVGA:
scaleFactor = 1;
break;
case VGA:
case WVGA:
scaleFactor = 2;
break;
}
LOG(L"Tutto OK StartHookOnHHTaskBar\n");
return TRUE;
}
__declspec(dllexport)
BOOL InstallHookOnHHTaskBar()
{
static long s_lCount = 0;
if (InterlockedIncrement(&s_lCount) > 1)
{
// no need to install again
return TRUE;
}
BOOL bResult = TRUE;
HANDLE hDestProcess = NULL;
HINSTANCE hDllInst = 0;
DWORD dwOldPermissions = 0;
SetKMode(TRUE);
dwOldPermissions = SetProcPermissions(-1);
__try
{
HWND hWndHHTaskbar = ::FindWindow(L"HHTaskBar", NULL);
DWORD dwProcessId; GetWindowThreadProcessId(hWndHHTaskbar, &dwProcessId);
hDestProcess = (HANDLE)dwProcessId;
CALLBACKINFO cbi;
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(GetModuleHandle(L"COREDLL"), L"LoadLibraryW"), hDestProcess);
cbi.m_pFirstArgument = (LPVOID)MapPtrToProcess(L"\\Windows\\FingerSuiteDll.dll", GetCurrentProcess());
hDllInst = (HINSTANCE)PerformCallBack4(&cbi, 0,0,0); //returns the HINSTANCE from LoadLibraryW
Sleep(1000);
ZeroMemory(&cbi, sizeof(CALLBACKINFO));
cbi.m_hDestinationProcessHandle = hDestProcess;
cbi.m_pFunction = (FARPROC)MapPtrToProcess(GetProcAddress(hDllInst, L"StartHookOnHHTaskBar"), hDestProcess);
cbi.m_pFirstArgument = NULL;
DWORD dw = PerformCallBack4(&cbi, 0,0,0); //returns 1 if correctly executed
Sleep(1000);
}
__except(FilterException(GetExceptionInformation()))
{
bResult = FALSE;
}
if(dwOldPermissions)
{
SetProcPermissions(dwOldPermissions);
}
SetKMode(FALSE);
return bResult;
}
__declspec(dllexport)
BOOL IsManagedNotification(REFCLSID clsid)
{
LPOLESTR pOleStr;
StringFromCLSID(clsid, &pOleStr);
LOG(L"IsManagedNotification notif = %s\n", (WCHAR*)pOleStr);
BOOL bResult = FALSE;
for (int i = 0; i < MANAGED_NOTIF_SIZE; i++)
{
if ( lstrcmpi(g_szManagedNotificationCLSID[i], (WCHAR*)pOleStr) == 0 )
{
bResult = TRUE;
break;
}
}
CoTaskMemFree(pOleStr);
return bResult;
}<file_sep>/FingerSuite/FingerNotification/Commons.h
#ifndef COMMONS_H
#define COMMONS_H
#pragma once
template <class T>
class CNotificationInfoEqualHelper
{
public:
static bool IsEqual(const T& t1, const T& t2)
{
return false;
}
};
#endif // COMMONS_H<file_sep>/FBReader/zlibrary/ui/src/win32/dialogs/ZLWin32SelectionDialog.cpp
/*
* Copyright (C) 2007-2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#include <ZLApplication.h>
#include <ZLibrary.h>
#include <ZLFile.h>
#include <ZLDialogManager.h>
#include "ZLWin32SelectionDialog.h"
#include "../w32widgets/W32Container.h"
#include "../w32widgets/W32Control.h"
#include "../application/ZLWin32ApplicationWindow.h"
#include "../../../../core/src/win32/util/W32WCHARUtil.h"
const int ICON_SIZE = 22;
ZLWin32SelectionDialog::ZLWin32SelectionDialog(ZLWin32ApplicationWindow &window, const std::string &caption, ZLTreeHandler &handler) : ZLDesktopSelectionDialog(handler), myWindow(window), myPanel(myWindow.mainWindow(), caption) {
myPanel.setResizeable(true);
myPanel.setExitOnOk(false);
myPanel.addListener(this);
W32VBorderBox *panelBox = new W32VBorderBox();
panelBox->setSpacing(4);
panelBox->setMargins(4, 4, 4, 4);
myPanel.setElement(panelBox);
myLineEditor = new W32LineEditor("");
myLineEditor->setVisible(true);
myLineEditor->setEnabled(!handler.isOpenHandler());
panelBox->setTopElement(myLineEditor);
myTreeView = new W32TreeView(ICON_SIZE);
myTreeView->setVisible(true);
myTreeView->addListener(this);
panelBox->setCenterElement(myTreeView);
W32HBox *buttonBox = new W32HBox();
panelBox->setBottomElement(buttonBox);
buttonBox->setHomogeneous(true);
buttonBox->setAlignment(W32HBox::RIGHT);
buttonBox->setSpacing(4);
buttonBox->setMargins(4, 4, 4, 4);
myOkButton = new W32PushButton(ZLDialogManager::buttonName(ZLDialogManager::OK_BUTTON));
myOkButton->addListener(this);
buttonBox->addElement(myOkButton);
buttonBox->addElement(new W32PushButton(ZLDialogManager::buttonName(ZLDialogManager::CANCEL_BUTTON), W32PushButton::CANCEL_BUTTON));
buttonBox->setVisible(true);
update();
}
ZLWin32SelectionDialog::~ZLWin32SelectionDialog() {
for(std::map<std::string,HICON>::iterator it = myIcons.begin(); it != myIcons.end(); ++it) {
DestroyIcon(it->second);
}
}
HICON ZLWin32SelectionDialog::getIcon(const ZLTreeNodePtr node) {
const std::string &pixmapName = node->pixmapName();
std::map<std::string,HICON>::const_iterator it = myIcons.find(pixmapName);
if (it == myIcons.end()) {
std::string imageFileName = ZLibrary::ApplicationImageDirectory() + ZLibrary::FileNameDelimiter + pixmapName + ".ico";
ZLFile file(imageFileName);
ZLUnicodeUtil::Ucs2String wPath;
HICON icon = (HICON)LoadImageW(0, ::wchar(::createNTWCHARString(wPath, file.path())), IMAGE_ICON, ICON_SIZE, ICON_SIZE, LR_LOADFROMFILE);
myIcons[pixmapName] = icon;
return icon;
} else {
return it->second;
}
}
void ZLWin32SelectionDialog::updateStateLine() {
myLineEditor->setText(handler().stateDisplayName());
}
void ZLWin32SelectionDialog::updateList() {
myTreeView->clear();
const std::vector<ZLTreeNodePtr> &nodes = handler().subnodes();
if (nodes.empty()) {
return;
}
for (std::vector<ZLTreeNodePtr>::const_iterator it = nodes.begin(); it != nodes.end(); ++it) {
myTreeView->insert((*it)->displayName(), getIcon(*it));
}
}
void ZLWin32SelectionDialog::selectItem(int index) {
myTreeView->select(index);
}
bool ZLWin32SelectionDialog::run() {
myWindow.blockMouseEvents(true);
bool result = myPanel.runDialog(myWidth, myHeight);
W32Widget::Size size = myPanel.size();
myWidth = size.Width;
myHeight = size.Height;
myWindow.blockMouseEvents(false);
return result;
}
void ZLWin32SelectionDialog::exitDialog() {
myPanel.endDialog(true);
}
void ZLWin32SelectionDialog::setSize(int width, int height) {
myWidth = width;
myHeight = height;
}
int ZLWin32SelectionDialog::width() const {
return myWidth;
}
int ZLWin32SelectionDialog::height() const {
return myHeight;
}
void ZLWin32SelectionDialog::onEvent(const std::string &event, W32EventSender&) {
if ((event == W32StandaloneDialogPanel::OK_EVENT) ||
(event == W32TreeView::ITEM_DOUBLE_CLICKED_EVENT) ||
(event == W32PushButton::RELEASED_EVENT)) {
if (handler().isOpenHandler()) {
int index = myTreeView->selectedIndex();
const std::vector<ZLTreeNodePtr> &nodes = handler().subnodes();
if ((index >= 0) && (index < (int)nodes.size())) {
runNode(nodes[index]);
}
} else {
//runState(gtk_entry_get_text(myStateLine));
}
} else if (event == W32TreeView::ITEM_SELECTED_EVENT) {
int index = myTreeView->selectedIndex();
const std::vector<ZLTreeNodePtr> &nodes = handler().subnodes();
if ((index >= 0) && (index < (int)nodes.size())) {
myOkButton->setEnabled(!nodes[index]->isFolder());
}
}
}
<file_sep>/FBReader/makefiles/arch/iliad.mk
include $(ROOTDIR)/makefiles/arch/unix.mk
BASEPATH = /opt/iLiad/usr/local/arm/oe
TOOLSPATH = $(BASEPATH)/bin
INCPATH = $(BASEPATH)/arm-linux/include
LIBPATH = $(BASEPATH)/arm-linux/lib
RM = rm -rvf
RM_QUIET = rm -rf
GTKINCLUDE = -I$(LIBPATH)/glib-2.0/include -I$(LIBPATH)/gtk-2.0/include -I$(INCPATH)/glib-2.0 -I$(INCPATH)/gtk-2.0 -I$(INCPATH)/pango-1.0 -I$(INCPATH)/atk-1.0
MOC = $(TOOLSPATH)/moc
CC = $(TOOLSPATH)/arm-linux-gcc
AR = $(TOOLSPATH)/arm-linux-ar rsu
LD = $(TOOLSPATH)/arm-linux-g++
UILIBS = -lgtk-x11-2.0 -lgdk-x11-2.0 -lgdk_pixbuf-2.0
CFLAGS = -pipe -DOPIE_NO_DEBUG -DQT_NO_DEBUG -DQWS -fno-exceptions -fno-rtti -march=armv4 -mtune=xscale --param inline-unit-growth=200 --param large-function-growth=2000 -Wall -Wno-ctor-dtor-privacy -W -Winline
LDFLAGS = -Wl,-rpath,$(LIBDIR)
<file_sep>/SQLCEHelper/Include/sqlce_ex.h
#ifndef __sqlce_ex_h__
#define __sqlce_ex_h__
#ifdef __cplusplus
extern "C"{
#endif
/***************************************************************************
****************************************************************************
SQL CE specific GUIDS
***************************************************************************
***************************************************************************/
// Microsoft SQL Server for Windows CE 1.0 Provider (Microsoft.SQLSERVER.OLEDB.CE.1.0)
//
extern const OLEDBDECLSPEC GUID CLSID_SQLSERVERCE_1_0 = {0x7D0703CB,0x4C23,0x11d2,{0x88,0x82,0x00,0xC0,0x4F,0xD9,0x37,0xF0}};
// Microsoft SQL Server for Windows CE 2.0 Provider (Microsoft.SQLSERVER.OLEDB.CE.2.0)
//
extern const OLEDBDECLSPEC GUID CLSID_SQLSERVERCE_2_0 = {0x76A85B2E,0x9DE0,0x4ded,{0x8E,0x69,0x4D,0xEF,0xDB,0x9C,0x09,0x17}};
// Microsoft SQL Server Lite for Windows 3.0 Provider (Microsoft.SQLSERVER.OLEDB.CE.3.0)
//
// {32CE2952-2585-49a6-AEFF-1732076C2945}
//
extern const OLEDBDECLSPEC GUID CLSID_SQLSERVERCE_3_0 = {0x32ce2952, 0x2585, 0x49a6, {0xae, 0xff, 0x17, 0x32, 0x7, 0x6c, 0x29, 0x45}};
/*
// Microsoft SQL Server Lite for Windows 3.5 Provider (Microsoft.SQLSERVER.CE.OLEDB.3.5)
//
// {F49C559D-E9E5-467C-8C18-3326AAE4EBCC}
//
extern const OLEDBDECLSPEC GUID CLSID_SQLSERVERCE_3_5 = {0xf49c559d, 0xe9e5, 0x467c, {0x8c, 0x18, 0x33, 0x26, 0xaa, 0xe4, 0xeb, 0xcc}};
// PUBLISHED: Provider Specific Property Sets
//
// Provider-Specific DBInit Property Set
// {2B9AB5BA-4F6C-4ddd-BF18-24DD4BD41848}
//
//extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_DBINIT = {0x2b9ab5ba, 0x4f6c, 0x4ddd, {0xbf, 0x18, 0x24, 0xdd, 0x4b, 0xd4, 0x18, 0x48}};
// Provider-Specific Column Property Set
// {352CC8D5-9181-11d3-B27B-00C04F68DBFF}
//
//extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_COLUMN = {0x352cc8d5, 0x9181, 0x11d3, {0xb2, 0x7b, 0x0, 0xc0, 0x4f, 0x68, 0xdb, 0xff}};
// Provider-Specific Rowset Property Set
// {5C17C602-A107-11d3-B27B-00C04F68DBFF}
//
//extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_ROWSET = {0x5c17c602, 0xa107, 0x11d3, {0xb2, 0x7b, 0x0, 0xc0, 0x4f, 0x68, 0xdb, 0xff}};
// Provider-Specific Session Property Set
// {22FE7D33-5E5C-4a45-B723-8BED2374A06B}
//
//extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_SESSION = {0x22fe7d33, 0x5e5c, 0x4a45, {0xb7, 0x23, 0x8b, 0xed, 0x23, 0x74, 0xa0, 0x6b}};
*/
#ifndef GUIDS_ONLY
#undef DBPROP_SSCE_COL_ROWGUID
#undef DBPROP_SSCE_MAXBUFFERSIZE
#undef DBPROP_SSCE_DBPASSWORD
#undef DBPROP_SSCE_ENCRYPTDATABASE
#undef DBPROP_SSCE_TEMPFILE_DIRECTORY
// PUBLISHED Provider specific properties
//
#define DBPROP_SSCE3_COL_ROWGUID 0x1F9L // SSCE_COLUMN
#define DBPROP_SSCE3_MAXBUFFERSIZE 0x1FAL // SSCE_DBINIT
#define DBPROP_SSCE3_DBPASSWORD 0x1FBL // SSCE_DBINIT
#define DBPROP_SSCE3_ENCRYPTDATABASE 0x1FCL // SSCE_DBINIT
#define DBPROP_SSCE3_TEMPFILE_DIRECTORY 0x1FEL // SSCE_DBINIT
// FOR SQL CE 2.0 ONLY
//
#define DBPROP_SSCE_TBL_DISTINCT 0x64
#define DBPROP_SSCE_COL_TTKEYASCENDING 0x65
#define DBPROP_SSCE_COL_TTKEYORDINAL 0x66
#define DBPROP_SSCE_TBL_TTTYPE 0x67
#define DBPROP_SSCE_PARTIALSETDATA 0x68
#define DBPROP_SSCE2_COL_ROWGUID 0x69
#define DBPROP_SSCE2_MAXBUFFERSIZE 0x70
#define DBPROP_SSCE2_DBPASSWORD 0x71
#define DBPROP_SSCE2_ENCRYPTDATABASE 0x72
#define DBPROP_SSCE2_TEMPFILE_DIRECTORY 0x73
#endif
/*********************************************************************/
#ifdef __cplusplus
}
#endif
#endif // __sqlce_ex_h__
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/PropertyNameRes.h
#define IDS_PROP_PATH 3
#define IDS_PROP_NAME 4
#define IDS_PROP_EXTENSION 5
#define IDS_PROP_IS_FOLDER 6
#define IDS_PROP_SIZE 7
#define IDS_PROP_PACKED_SIZE 8
#define IDS_PROP_ATTRIBUTES 9
#define IDS_PROP_CTIME 10
#define IDS_PROP_ATIME 11
#define IDS_PROP_MTIME 12
#define IDS_PROP_SOLID 13
#define IDS_PROP_C0MMENTED 14
#define IDS_PROP_ENCRYPTED 15
#define IDS_PROP_DICTIONARY_SIZE 16
#define IDS_PROP_SPLIT_BEFORE 17
#define IDS_PROP_SPLIT_AFTER 18
#define IDS_PROP_CRC 19
#define IDS_PROP_FILE_TYPE 20
#define IDS_PROP_ANTI 21
#define IDS_PROP_METHOD 22
#define IDS_PROP_HOST_OS 23
#define IDS_PROP_FILE_SYSTEM 24
#define IDS_PROP_USER 25
#define IDS_PROP_GROUP 26
#define IDS_PROP_BLOCK 27
#define IDS_PROP_COMMENT 28
#define IDS_PROP_POSITION 29
#define IDS_PROP_PREFIX 30
#define IDS_PROP_FOLDERS 31
#define IDS_PROP_FILES 32
#define IDS_PROP_VERSION 33
#define IDS_PROP_VOLUME 34
#define IDS_PROP_IS_VOLUME 35
#define IDS_PROP_OFFSET 36
#define IDS_PROP_LINKS 37
#define IDS_PROP_NUM_BLOCKS 38
#define IDS_PROP_NUM_VOLUMES 39
#define IDS_PROP_BIT64 41
#define IDS_PROP_BIG_ENDIAN 42
#define IDS_PROP_CPU 43
#define IDS_PROP_PHY_SIZE 44
#define IDS_PROP_HEADERS_SIZE 45
#define IDS_PROP_CHECKSUM 46
#define IDS_PROP_CHARACTS 47
#define IDS_PROP_VA 48
#define IDS_PROP_ID 49
#define IDS_PROP_SHORT_NAME 50
#define IDS_PROP_CREATOR_APP 51
#define IDS_PROP_SECTOR_SIZE 52
#define IDS_PROP_POSIX_ATTRIB 53
#define IDS_PROP_LINK 54
<file_sep>/7-Zip/CPP/7zip/Archive/Wim/WimHandler.h
// WimHandler.h
#ifndef __ARCHIVE_WIM_HANDLER_H
#define __ARCHIVE_WIM_HANDLER_H
#include "Common/MyCom.h"
#include "Common/MyXml.h"
#include "../IArchive.h"
#include "WimIn.h"
namespace NArchive {
namespace NWim {
struct CVolume
{
CHeader Header;
CMyComPtr<IInStream> Stream;
};
struct CImageInfo
{
bool CTimeDefined;
bool MTimeDefined;
bool NameDefined;
// bool IndexDefined;
FILETIME CTime;
FILETIME MTime;
UString Name;
// UInt32 Index;
CImageInfo(): CTimeDefined(false), MTimeDefined(false), NameDefined(false)
// , IndexDefined(false)
{}
void Parse(const CXmlItem &item);
};
struct CXml
{
CByteBuffer Data;
UInt16 VolIndex;
CObjectVector<CImageInfo> Images;
void Parse();
};
class CHandler:
public IInArchive,
public CMyUnknownImp
{
public:
MY_UNKNOWN_IMP1(IInArchive)
INTERFACE_IInArchive(;)
private:
CDatabase m_Database;
CObjectVector<CVolume> m_Volumes;
CObjectVector<CXml> m_Xmls;
int m_NameLenForStreams;
};
}}
#endif
<file_sep>/FingerSuite/Common/AboutView.h
// Test99View.h : interface of the CTest99View class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLMISC_H__
#error AboutView.h requires atlmisc.h to be included first
#endif
// Extracted from MFC 7.0 source code by <NAME>
BOOL AfxExtractSubString(CString& rString, LPCTSTR lpszFullString,
int iSubString, TCHAR chSep)
{
if (lpszFullString == NULL)
return FALSE;
while (iSubString--)
{
lpszFullString = _tcschr(lpszFullString, chSep);
if (lpszFullString == NULL)
{
rString.Empty(); // return empty string as well
return FALSE;
}
lpszFullString++; // point past the separator
}
LPCTSTR lpchEnd = _tcschr(lpszFullString, chSep);
int nLen = (lpchEnd == NULL) ?
lstrlen(lpszFullString) : (int)(lpchEnd - lpszFullString);
ATLASSERT(nLen >= 0);
memcpy(rString.GetBufferSetLength(nLen), lpszFullString, nLen*sizeof(TCHAR));
return TRUE;
}
class CAboutView : public CWindowImpl<CAboutView>
{
public:
DECLARE_WND_CLASS(NULL)
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
void SetCredits(LPCTSTR lpszCredits)
{
m_strCredits = lpszCredits;
}
void SetBitmap(HBITMAP hBmp, int x, int y)
{
m_hBitmap = hBmp;
m_ptPos.x = x;
m_ptPos.y = y;
}
BEGIN_MSG_MAP(CAboutView)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CPaintDC dc(m_hWnd);
RECT rc; GetClientRect(&rc);
//TODO: Add your drawing code here
CFont cOldFont;
CFont cFontNormal = dc.GetCurrentFont();
LOGFONT lf; cFontNormal.GetLogFont(lf);
lf.lfWeight = FW_BOLD;
CFont cFontBold; cFontBold.CreateFontIndirect(&lf);
lf.lfHeight -= 2;
CFont cFontTitle; cFontTitle.CreateFontIndirect(&lf);
dc.SetBkMode(TRANSPARENT);
CString strSub;
int nCount=0;
// draw each line, based on specified type
while(AfxExtractSubString(strSub, m_strCredits, nCount++, '\n'))
{
TCHAR nType = 0;
if (!strSub.IsEmpty())
nType = strSub.GetAt(0);
switch(nType)
{
case '\t': // title
dc.SetTextColor(RGB(16,140,231));
cOldFont = dc.SelectFont(cFontTitle);
strSub.TrimLeft('\t');
dc.DrawText(strSub, strSub.GetLength(), &rc, DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE);
dc.SelectFont(cOldFont);
break;
case '\r': // bold
dc.SetTextColor(RGB(0,0,0));
cOldFont = dc.SelectFont(cFontBold);
strSub.TrimLeft('\r');
dc.DrawText(strSub, strSub.GetLength(), &rc, DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE);
dc.SelectFont(cOldFont);
break;
default: // normal
dc.SetTextColor(RGB(0,0,0));
cOldFont = dc.SelectFont(cFontNormal);
dc.DrawText(strSub, strSub.GetLength(), &rc, DT_TOP|DT_CENTER|DT_NOPREFIX | DT_SINGLELINE);
dc.SelectFont(cOldFont);
break;
}
// next line
TEXTMETRIC tm;
dc.GetTextMetricsW(&tm);
rc.top += tm.tmHeight;
}
return 0;
}
private:
CString m_strCredits;
HBITMAP m_hBitmap;
POINT m_ptPos;
};
<file_sep>/FBReaderJ/jni/HanvonUtil.h
#ifndef HANVONUTIL_H_
#define HANVONUTIL_H_
#ifdef DEBUG_LOG
#include <android/log.h>
#define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, "=== HAN.WANG ===", __VA_ARGS__)
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, "=== HAN.WANG ===", __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, "=== HAN.WANG ===", __VA_ARGS__)
#define LOGV(...) __android_log_print(ANDROID_LOG_VERBOSE, "=== HAN.WANG ===", __VA_ARGS__)
#define LOGW(...) __android_log_print(ANDROID_LOG_WARN, "=== HAN.WANG ===", __VA_ARGS__)
#else
#define LOGD(...)
#define LOGE(...)
#define LOGI(...)
#define LOGV(...)
#define LOGW(...)
#endif
#endif /* HANVONUTIL_H_ */
<file_sep>/FingerSuite/FingerNotification/MainFrm.h
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "..\Common\AboutView.h"
typedef enum {QVGA = 320, WQVGA = 400, VGA = 640, WVGA = 800} RESOLUTION;
static UINT UWM_INTERCEPT_NOTIF = ::RegisterWindowMessage(UWM_INTERCEPT_NOTIF_MSG);
static UINT UWM_NOTIF_POPUP = ::RegisterWindowMessage(UWM_NOTIF_POPUP_MSG);
typedef struct tagNMSHN_LINK
{
NMSHN inner;
WCHAR szLink[1024];
} NMSHN_LINK, *LPNMSHN_LINK;
class CMainFrame : public CFrameWindowImpl<CMainFrame>, public CUpdateUI<CMainFrame>,
public CFullScreenFrame<CMainFrame, false>, public CMessageFilter, public CIdleHandler
{
public:
DECLARE_FRAME_WND_CLASS(NULL, IDR_MAINFRAME)
CHTMLNotifWindow m_notif;
CNotifListWindow m_list;
CAboutView m_aboutView;
virtual BOOL PreTranslateMessage(MSG* pMsg)
{
if(CFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg))
return TRUE;
return m_list.PreTranslateMessage(pMsg);
}
virtual BOOL OnIdle()
{
return FALSE;
}
BEGIN_UPDATE_UI_MAP(CMainFrame)
END_UPDATE_UI_MAP()
BEGIN_MSG_MAP(CMainFrame)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
MESSAGE_HANDLER(UWM_INTERCEPT_NOTIF, OnInterceptNotif)
MESSAGE_HANDLER(UWM_NOTIF_POPUP, OnNotifPopup)
MESSAGE_HANDLER(WM_NOTIFY, OnNotify)
MESSAGE_HANDLER(UM_SELECTNOTIF, OnSelectNotif)
MESSAGE_HANDLER(UM_MINIMIZE, OnMinimize)
COMMAND_ID_HANDLER(ID_MENU_EXIT, OnMenuExit)
COMMAND_ID_HANDLER(ID_MENU_ABOUT, OnMenuAbout)
COMMAND_ID_HANDLER(ID_MENU_SHOWORIGINAL, OnMenuShowOriginal)
MESSAGE_HANDLER(WM_COMMAND, OnCommand)
CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
CHAIN_MSG_MAP(CFrameWindowImpl<CMainFrame>)
END_MSG_MAP()
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CreateSimpleCEMenuBar();
LoadConfiguration();
m_hWndClient = m_list.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_notif.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
CString strCredits = "\n\n"
"\tFingerNotification v1.00\n\n"
"\rDeveloped by:\n"
"<NAME>\n"
"<<EMAIL>>\n"
"\n\n"
"http://forum.xda-developers.com/\n"
" showthread.php?t=459125\n";
m_aboutView.SetCredits(strCredits);
m_aboutView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE |WS_CLIPSIBLINGS | WS_CLIPCHILDREN); //
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
SetHWndServerNotif(m_hWnd);
InstallHookOnShell();
Sleep(1000);
//ParseStandardNotification();
ModifyStyle(0, WS_NONAVDONEBUTTON, SWP_NOSIZE);
InstallHookOnHHTaskBar();
LOG(L"FingerNotification started.\n");
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
}
return 0;
}
LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
int fActive = LOWORD(wParam);
if ((fActive == WA_ACTIVE) || (fActive == WA_CLICKACTIVE))
{
}
else if (fActive == WA_INACTIVE)
{
if (IsWindowVisible())
{
Minimize();
}
}
return 0;
}
LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CDCHandle dc( (HDC) wParam );
RECT rc; GetClientRect(&rc);
if (m_bDisabledTransp)
{
dc.FillSolidRect(&rc, m_clNoTranspBackground);
}
else
{
if (!(m_imgBkg.IsValid()))
CaptureScreen(dc);
m_imgBkg.Draw(dc, rc);
}
return 1;
}
LRESULT OnInterceptNotif(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
int idx;
LPNOTIFICATIONINFO pInfo = (LPNOTIFICATIONINFO)malloc(sizeof(NOTIFICATIONINFO));
memcpy(pInfo, (LPNOTIFICATIONINFO)lParam, sizeof(NOTIFICATIONINFO));
// adjust pointers
pInfo->nd.pszTitle = pInfo->szTitle;
pInfo->nd.pszHTML = pInfo->szHTML;
// menu
if (pInfo->nd.grfFlags & SHNF_HASMENU)
{
pInfo->nd.skm.prgskc = pInfo->rgskc;
}
else
{
pInfo->nd.rgskn[0].pszTitle = pInfo->sk1Title;
pInfo->nd.rgskn[1].pszTitle = pInfo->sk2Title;
}
DUMP_SHN(&pInfo->nd);
switch (wParam)
{
case NOTIF_ADD:
LOG(L"\nNOTIF_ADD\n");
g_pNotifications.Add(pInfo);
if (pInfo->isManaged)
{
// tempor disabled
//ShowNotification(g_pNotifications.GetSize() - 1); // show last notification added
}
break;
case NOTIF_UPD:
LOG(L"\nNOTIF_UPD\n");
idx = -1;
for (int i = 0; i < g_pNotifications.GetSize(); i++)
{
LPNOTIFICATIONINFO pFind = g_pNotifications[i];
if (
//(pFind->nd.dwID == pData->nd.dwID) &&
(IsEqualCLSID(pFind->nd.clsid, pInfo->nd.clsid)))
{
idx = i;
break;
}
}
if (idx > -1)
{
free(g_pNotifications[idx]);
g_pNotifications.RemoveAt(idx);
g_pNotifications.Add(pInfo);
// tempor disabled
if (pInfo->isManaged)
ShowNotification(g_pNotifications.GetSize() - 1); // show last notification added
}
break;
case NOTIF_DEL:
LOG(L"\nNOTIF_DEL\n");
idx = -1;
for (int i = 0; i < g_pNotifications.GetSize(); i++)
{
LPNOTIFICATIONINFO pFind = g_pNotifications[i];
if (
//(pFind->nd.dwID == pData->nd.dwID) &&
(IsEqualCLSID(pFind->nd.clsid, pInfo->nd.clsid)))
{
idx = i;
break;
}
}
if (idx > -1)
{
free(g_pNotifications[idx]);
g_pNotifications.RemoveAt(idx);
}
break;
} // end switch
return 0;
}
LRESULT OnNotifPopup(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
ShowNotificationList();
return 0;
}
LRESULT OnCommand(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
WORD wID = LOWORD(wParam);
// ricerca
LPNOTIFICATIONINFO pInfo = g_pNotifications[m_idx];
BOOL bSendCommand = TRUE;
DWORD dwSoftkeyType = 0;
HWND hwndSink = pInfo->nd.hwndSink;
if (pInfo->nd.grfFlags & SHNF_HASMENU)
{
for (UINT i = 0; i < pInfo->nd.skm.cskc; i++)
{
if (wID == pInfo->nd.skm.prgskc[i].wpCmd)
{
dwSoftkeyType = pInfo->nd.skm.prgskc[i].grfFlags;
break; // exit for
}
}
}
else
{
if (pInfo->nd.rgskn[0].skc.wpCmd == wID)
dwSoftkeyType = pInfo->nd.rgskn[0].skc.grfFlags;
if (pInfo->nd.rgskn[1].skc.wpCmd == wID)
dwSoftkeyType = pInfo->nd.rgskn[1].skc.grfFlags;
}
if (dwSoftkeyType == NOTIF_SOFTKEY_FLAGS_DISMISS)
{
SendNotifyDismiss(pInfo, FALSE);
SHNotificationRemove(&pInfo->nd.clsid, pInfo->nd.dwID);
Minimize();
}
if (dwSoftkeyType & NOTIF_SOFTKEY_FLAGS_HIDE)
{
Minimize();
}
if (dwSoftkeyType & NOTIF_SOFTKEY_FLAGS_STAYOPEN)
{
}
if (dwSoftkeyType & NOTIF_SOFTKEY_FLAGS_SUBMIT_FORM)
{
bSendCommand = FALSE;
m_notif.SubmitForm();
Minimize();
}
if (bSendCommand)
::PostMessage(hwndSink, WM_COMMAND, (WPARAM)wID, (LPARAM)0);
return 0;
}
LRESULT OnNotify(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
LOG(L"\n");
LPNOTIFICATIONINFO pInfo = g_pNotifications[m_idx];
DWORD dwCmd = 0;
int idCtrl = (int) wParam;
NM_HTMLVIEW * pnmHTML = (NM_HTMLVIEW *) lParam;
LPNMHDR pnmh = (LPNMHDR) &(pnmHTML->hdr);
switch (pnmh->code)
{
case NM_INLINE_IMAGE:
LOG(L"NM_INLINE_IMAGE\n\n");
if (lstrcmpi(pnmHTML->szTarget, L"fngrnotif_btn_bkg.gif") == 0)
{
INLINEIMAGEINFO imageInfo;
imageInfo.dwCookie = pnmHTML->dwCookie;
imageInfo.bOwnBitmap = FALSE;
imageInfo.hbm = m_bmpHtmlButton;
imageInfo.iOrigWidth = 1;
imageInfo.iOrigHeight = 70;
m_notif.m_html.SetImage(&imageInfo);
}
break;
case NM_HOTSPOT:
LOG(L"NM_HOTSPOT\n\n");
SendNotifyDismiss(pInfo, FALSE);
Minimize();
// command in format of cmd:XXX
// sent to hwndSink
swscanf(pnmHTML->szTarget, L"cmd:%d", &dwCmd);
if (dwCmd != 0)
{
::PostMessage(pInfo->nd.hwndSink, WM_COMMAND, (WPARAM)dwCmd, (LPARAM)0);
}
else
{
// send SHNM_LINKSEL
SendNotifyLink(pInfo, pnmHTML->szTarget);
}
break;
case NM_BEFORENAVIGATE:
LOG(L"NM_BEFORENAVIGATE\n");
LOG(L"\n");
break;
case NM_DOCUMENTCOMPLETE:
LOG(L"NM_DOCUMENTCOMPLETE\n");
LOG(L"\n");
m_notif.UpdateWindow();
break;
default:
LOG(L"NOT MANAGED: %X\n", pnmh->code);
LOG(L"\n");
}
LOG(L"pnmHTML->szTarget: %s\n", pnmHTML->szTarget);
LOG(L"pnmHTML->szData: %s\n", pnmHTML->szData);
LOG(L"pnmHTML->szExInfo: %s\n", pnmHTML->szExInfo);
return 0;
}
LRESULT OnSelectNotif(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
int idx = (int)wParam;
LPNOTIFICATIONINFO pInfo = g_pNotifications[idx];
if (pInfo->nd.npPriority != SHNP_ICONIC)
ShowNotification(idx);
return 0;
}
LRESULT OnMinimize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
Minimize();
return 0;
}
LRESULT OnMenuExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled)
{
Minimize();
PostMessage(WM_CLOSE);
bHandled = TRUE;
return 0;
}
LRESULT OnMenuAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled)
{
SwitchToAboutView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
bHandled = TRUE;
return 0;
}
LRESULT OnMenuShowOriginal(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& bHandled)
{
Minimize();
// TODO
bHandled = TRUE;
return 0;
}
public:
static HRESULT ActivatePreviousInstance(HINSTANCE hInstance)
{
const TCHAR* pszMutex = L"FINGERNOTIFMUTEX";
const TCHAR* pszClass = L"FINGER_NOTIFICATION";
const DWORD dRetryInterval = 100;
const int iMaxRetries = 25;
for(int i = 0; i < iMaxRetries; ++i)
{
HANDLE hMutex = CreateMutex(NULL, FALSE, pszMutex);
DWORD dw = GetLastError();
if(hMutex == NULL)
{
HRESULT hr = (dw == ERROR_INVALID_HANDLE) ? E_INVALIDARG : E_FAIL;
return hr;
}
if(dw == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
HWND hwnd = FindWindow(pszClass, NULL);
if(hwnd == NULL)
{
Sleep(dRetryInterval);
continue;
}
else
{
if(SetForegroundWindow(reinterpret_cast<HWND>(reinterpret_cast<ULONG>(hwnd) | 0x1)) != 0)
{
return S_FALSE;
}
}
}
else
{
return S_OK;
}
}
return S_OK;
}
void Show()
{
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
}
void Minimize()
{
ShowWindow(SW_HIDE);
}
private:
int m_idx;
CxImage m_imgBkg;
DWORD m_iTransp;
BOOL m_bDisabledTransp;
COLORREF m_clNoTranspBackground;
HBITMAP m_bmpHtmlButton;
void SendNotifyDismiss(LPNOTIFICATIONINFO pData, BOOL bTimeout)
{
NMSHN nm;
ZeroMemory(&nm, sizeof(NMSHN));
nm.hdr.code = SHNN_DISMISS;
nm.hdr.idFrom = pData->nd.dwID;
nm.lParam = pData->nd.lParam;
nm.fTimeout = bTimeout;
SendMessageRemote(pData->nd.hwndSink, WM_NOTIFY, 0, (LPARAM)&nm, sizeof(NMSHN));
}
void SendNotifyShow(LPNOTIFICATIONINFO pData)
{
NMSHN nm;
ZeroMemory(&nm, sizeof(NMSHN));
nm.hdr.code = SHNN_SHOW;
nm.hdr.idFrom = pData->nd.dwID;
nm.lParam = pData->nd.lParam;
nm.pt.x = 1;
nm.pt.y = 1;
SendMessageRemote(pData->nd.hwndSink, WM_NOTIFY, 0, (LPARAM)&nm, sizeof(NMSHN));
}
void SendNotifyLink(LPNOTIFICATIONINFO pData, LPCTSTR pszLink)
{
HANDLE hFile = NULL;
LPVOID pView = PrepareRemoteMessage(&hFile, sizeof(NMSHN_LINK));
if (pView != NULL)
{
LPNMSHN_LINK lpnm = (LPNMSHN_LINK)pView;
ZeroMemory(lpnm, sizeof(NMSHN_LINK));
lpnm->inner.hdr.code = SHNN_LINKSEL;
lpnm->inner.hdr.idFrom = pData->nd.dwID;
lpnm->inner.lParam = pData->nd.lParam;
lpnm->inner.dwReturn = 1;
wsprintf(lpnm->szLink, L"%s", pszLink);
lpnm->inner.pszLink = lpnm->szLink;
SendMessage(pData->nd.hwndSink, WM_NOTIFY, 0, (LPARAM)lpnm);
CloseRemoteMessage(hFile, pView);
}
}
void LoadConfiguration()
{
WCHAR keyName[] = L"Software\\FingerNotification";
// load transparency level
m_iTransp = 128;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"TransparencyLevel", m_iTransp)))
wprintf(L"Unable to read TransparencyLevel from registry: %s\n", ErrorString(GetLastError()));
m_iTransp = m_iTransp;
m_bDisabledTransp = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"DisableTransparency", m_bDisabledTransp)))
wprintf(L"Unable to read DisableTransparency from registry: %s\n", ErrorString(GetLastError()));
m_clNoTranspBackground = RGB(0,0,0);
RegReadColor(HKEY_LOCAL_MACHINE, keyName, L"NoTranspBkgColor", m_clNoTranspBackground);
m_notif.m_bEnableAnimation = TRUE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"EnableAnimation", m_notif.m_bEnableAnimation)))
LOG(L"Unable to read EnableAnimation from registry: %s\n", ErrorString(GetLastError()));
if ( RegistryGetDWORD ( HKEY_LOCAL_MACHINE, keyName, L"AutoMinimizeInterval", &m_list.m_tmrMinimize) != S_OK )
m_list.m_tmrMinimize = 3000;
WCHAR szSkin[60] = L"default";
RegReadString(HKEY_LOCAL_MACHINE, keyName, L"Skin", szSkin);
WCHAR szAppPath[MAX_PATH] = L"";
CString strAppDirectory;
GetModuleFileName(NULL, szAppPath, MAX_PATH);
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind('\\'));
CString skinBasePath; skinBasePath.Format(L"%s\\skins\\%s", strAppDirectory, szSkin);
// detect resolution
RESOLUTION resolution = QVGA;
DEVMODE dm;
::ZeroMemory(&dm, sizeof(DEVMODE));
dm.dmSize = sizeof(DEVMODE);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm))
{
resolution = (RESOLUTION)dm.dmPelsHeight;
}
// load icon images
switch (resolution)
{
case QVGA:
case WQVGA:
m_notif.SetScaleFactor(1);
m_list.SetScaleFactor(1);
break;
case VGA:
case WVGA:
m_notif.SetScaleFactor(2);
m_list.SetScaleFactor(2);
break;
}
if ( (resolution == VGA) || (resolution == WVGA))
{
m_notif.m_imgHeader.Load(skinBasePath + L"\\notif_header_vga.png", CXIMAGE_FORMAT_PNG);
m_notif.m_imgCalendar.Load(skinBasePath + L"\\icon_calendar_vga.png", CXIMAGE_FORMAT_PNG);
m_list.m_notiflist.m_imgSelection.Load(skinBasePath + L"\\list_selection_vga.png", CXIMAGE_FORMAT_PNG);
//m_list.m_imgIconBkg.Load(skinBasePath + L"\\icon_bkg_vga.png", CXIMAGE_FORMAT_PNG);
// normal
AddStaticSet(m_list.m_arrStaticImages, NORMAL, skinBasePath + L"\\notif_button_normal_vga.png");
// pressed
AddStaticSet(m_list.m_arrStaticImages, PUSHED, skinBasePath + L"\\notif_button_pressed_vga.png");
// icons
m_list.m_notiflist.AddIcon(L"missedcall", skinBasePath + L"\\icons\\notifications_icon_MissedCall_vga.png");
m_list.m_notiflist.AddIcon(L"reminder", skinBasePath + L"\\icons\\notifications_icon_Reminder_vga.png");
m_list.m_notiflist.AddIcon(L"message", skinBasePath + L"\\icons\\notifications_icon_Messages_vga.png");
m_list.m_notiflist.AddIcon(L"warning", skinBasePath + L"\\icons\\notifications_icon_Warning_vga.png");
m_list.m_notiflist.AddIcon(L"email", skinBasePath + L"\\icons\\notifications_icon_Email_vga.png");
m_list.m_notiflist.AddIcon(L"wifi", skinBasePath + L"\\icons\\notifications_icon_Wifi_vga.png");
m_list.m_notiflist.AddIcon(L"bluetooth", skinBasePath + L"\\icons\\notifications_icon_Bluetooth_vga.png");
}
else
{
m_notif.m_imgHeader.Load(skinBasePath + L"\\notif_header_qvga.png", CXIMAGE_FORMAT_PNG);
m_notif.m_imgCalendar.Load(skinBasePath + L"\\icon_calendar_qvga.png", CXIMAGE_FORMAT_PNG);
m_list.m_notiflist.m_imgSelection.Load(skinBasePath + L"\\list_selection_qvga.png", CXIMAGE_FORMAT_PNG);
//m_list.m_imgIconBkg.Load(skinBasePath + L"\\icon_bkg_qvga.png", CXIMAGE_FORMAT_PNG);
// normal
AddStaticSet(m_list.m_arrStaticImages, NORMAL, skinBasePath + L"\\notif_button_normal_qvga.png");
// pressed
AddStaticSet(m_list.m_arrStaticImages, PUSHED, skinBasePath + L"\\notif_button_pressed_qvga.png");
// icons
m_list.m_notiflist.AddIcon(L"missedcall", skinBasePath + L"\\icons\\notifications_icon_MissedCall_qvga.png");
m_list.m_notiflist.AddIcon(L"reminder", skinBasePath + L"\\icons\\notifications_icon_Reminder_qvga.png");
m_list.m_notiflist.AddIcon(L"message", skinBasePath + L"\\icons\\notifications_icon_Messages_qvga.png");
m_list.m_notiflist.AddIcon(L"warning", skinBasePath + L"\\icons\\notifications_icon_Warning_qvga.png");
m_list.m_notiflist.AddIcon(L"email", skinBasePath + L"\\icons\\notifications_icon_Email_qvga.png");
m_list.m_notiflist.AddIcon(L"wifi", skinBasePath + L"\\icons\\notifications_icon_Wifi_qvga.png");
m_list.m_notiflist.AddIcon(L"bluetooth", skinBasePath + L"\\icons\\notifications_icon_Bluetooth_qvga.png");
}
m_bmpHtmlButton = SHLoadImageFile(skinBasePath + L"\\fngrnotif_btn_bkg.gif");
// load skin settings
CSimpleIniW ini(TRUE, TRUE, TRUE);
SI_Error rc = ini.LoadFile(skinBasePath + L"\\settings_fingernotif.ini");
// load background and selected color
COLORREF clValue = 0;
m_notif.m_clCaptionText = (StringRGBToColor(ini.GetValue(L"colors", L"CaptionTextColor"), clValue)) ? clValue : RGB(255,255,255);
m_list.m_clText = (StringRGBToColor(ini.GetValue(L"colors", L"TextColor"), clValue)) ? clValue : RGB(255,255,255);
m_list.m_notiflist.m_clText = m_list.m_clText;
m_list.m_clLine = (StringRGBToColor(ini.GetValue(L"colors", L"LineColor"), clValue)) ? clValue : RGB(97,97,97);
m_list.m_notiflist.m_clLine = m_list.m_clLine;
m_list.m_notiflist.m_clBkg = (StringRGBToColor(ini.GetValue(L"colors", L"ListBkgColor"), clValue)) ? clValue : RGB(60,60,60);
m_list.m_clBkgHeader = (StringRGBToColor(ini.GetValue(L"colors", L"ListBkgHeaderColor"), clValue)) ? clValue : RGB(40,40,40);
LOGFONT lf;
if (StringToLogFont(ini.GetValue(L"fonts", L"NotifCaptionFont"), lf))
{
m_notif.m_fCaption.CreateFontIndirect(&lf);
}
if (StringToLogFont(ini.GetValue(L"fonts", L"ListHeaderTextFont"), lf))
{
m_list.m_fHeaderText.CreateFontIndirect(&lf);
}
if (StringToLogFont(ini.GetValue(L"fonts", L"ListTextFont"), lf))
{
m_list.m_notiflist.m_fText.CreateFontIndirect(&lf);
}
if (StringToLogFont(ini.GetValue(L"fonts", L"ListTitleFont"), lf))
{
m_list.m_fTitleText.CreateFontIndirect(&lf);
}
}
void ShowNotification(int idx)
{
m_idx = idx;
LPNOTIFICATIONINFO pInfo = g_pNotifications[m_idx];
if (pInfo->nd.npPriority != SHNP_ICONIC)
{
if ( (!(pInfo->grfFlagsOriginal & SHNF_STRAIGHTTOTRAY))
|| (!(pInfo->grfFlagsOriginal & SHNF_SILENT))
|| (pInfo->grfFlagsOriginal & SHNF_FORCEMESSAGE)
|| (pInfo->grfFlagsOriginal & SHNF_CRITICAL)
)
{
CreateMenuBar(pInfo);
SendNotifyShow(pInfo);
m_list.StopMinimizeTimer();
m_notif.SetNotification(pInfo);
SetFullScreen(false);
Show();
SwitchToNotifView();
m_notif.Show();
}
}
}
void ShowNotificationList()
{
SwitchToListView();
SetFullScreen(true);
Show();
m_list.Show();
}
void CreateMenuBar(LPNOTIFICATIONINFO pData)
{
if (::IsWindow(m_hWndCECommandBar))
{
::DestroyWindow(m_hWndCECommandBar);
}
if (pData->nd.grfFlags & SHNF_HASMENU)
{
SHMENUBARINFO mbi;
ZeroMemory(&mbi, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = m_hWnd;
mbi.nToolBarId = (UINT)(pData->nd.skm.hMenu);
mbi.hInstRes = ModuleHelper::GetModuleInstance();
mbi.dwFlags = SHCMBF_HMENU;
if(SHCreateMenuBar(&mbi))
{
m_hWndCECommandBar = mbi.hwndMB;
SizeToMenuBar();
}
else
{
LOG(L"Error: %s\n", ErrorString(GetLastError()));
}
}
else
{
// menu from soft key
CMenuHandle m; m.CreatePopupMenu();
if (pData->nd.rgskn[0].skc.wpCmd != 0)
m.AppendMenu(MF_STRING, pData->nd.rgskn[0].skc.wpCmd, pData->nd.rgskn[0].pszTitle);
if (pData->nd.rgskn[1].skc.wpCmd != 0)
m.AppendMenu(MF_STRING, pData->nd.rgskn[1].skc.wpCmd, pData->nd.rgskn[1].pszTitle);
SHMENUBARINFO mbi;
ZeroMemory(&mbi, sizeof(SHMENUBARINFO));
mbi.cbSize = sizeof(SHMENUBARINFO);
mbi.hwndParent = m_hWnd;
mbi.nToolBarId = (UINT)m.m_hMenu;
mbi.hInstRes = ModuleHelper::GetModuleInstance();
mbi.dwFlags = SHCMBF_HMENU;
if(SHCreateMenuBar(&mbi))
{
m_hWndCECommandBar = mbi.hwndMB;
SizeToMenuBar();
}
else
{
LOG(L"Error: %s\n", ErrorString(GetLastError()));
}
}
}
void ParseStandardNotification()
{
CSimpleArray<CString> clsids;
SHNOTIFICATIONDATA shnd;
CLSID clsid;
LRESULT result;
DWORD dwID = 0;
clsids.Add("{A877D661-239C-47a7-9304-0D347F580408}");
clsids.Add("{A877D660-239C-47a7-9304-0D347F580408}");
clsids.Add("{A877D65A-239C-47a7-9304-0D347F580408}");
clsids.Add("{A877D65D-239C-47a7-9304-0D347F580408}");
clsids.Add("{A877D659-239C-47a7-9304-0D347F580408}");
clsids.Add("{A877D658-239C-47a7-9304-0D347F580408}");
clsids.Add("{15F11F90-8A5F-454c-89FC-BA9B7AAB0CAD}");
clsids.Add("{B67B425B-365E-42c0-95F7-B75503D775B8}");
clsids.Add("{DDBD3B44-80B0-4b24-9DC4-839FEA6E559E}");
clsids.Add("{8ddf46e8-56ed-4750-9e58-afc6ce486d03}");
clsids.Add("{8ddf46e7-56ed-4750-9e58-afc6ce486d03}");
clsids.Add("{0D3132C4-1298-469c-B2B8-F28CE2D649D0}");
clsids.Add("{A877D663-239C-47a7-9304-0D347F580408}");
clsids.Add("{E0F2B9DD-EDC6-45d4-B440-2C5B5A04A3E3}");
clsids.Add("{A877D65B-239C-47a7-9304-0D347F580408}");
clsids.Add("{F55615D6-D29E-4db8-8C75-98125D1A7253}");
LOG(L"BEGIN parse\n");
for (int i = 0; i < clsids.GetSize(); i++)
{
LOG(L"\nFinding %s\n", clsids[i]);
LPOLESTR c = (LPOLESTR)((LPCTSTR)clsids[i]);
if (0 == CLSIDFromString(c, &clsid))
{
dwID = 0;
memset(&shnd, 0, sizeof(shnd));
shnd.cbStruct = sizeof(SHNOTIFICATIONDATA);
do {
LOG(L".");
result = SHNotificationGetData(&clsid, dwID, &shnd);
if (ERROR_SUCCESS == result) {
LOG(L"\nNotification found\n");
DUMP_SHN(&shnd);
LOG(L"\n\n");
if (shnd.pszHTML) free((void *) shnd.pszHTML);
shnd.pszHTML = NULL;
if (shnd.pszTitle) free((void *) shnd.pszTitle);
shnd.pszTitle = NULL;
} else dwID++;
} while ((ERROR_SUCCESS != result) && (dwID < 70000));
}
}
LOG(L"END parse\n");
}
void SwitchToNotifView()
{
m_hWndClient = m_notif;
m_list.ShowWindow(SW_HIDE);
m_list.SetWindowLongPtr(GWL_ID, 0);
m_notif.ShowWindow(SW_SHOW);
m_notif.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_notif.SetFocus();
}
void SwitchToListView()
{
m_hWndClient = m_list;
m_notif.ShowWindow(SW_HIDE);
m_notif.SetWindowLongPtr(GWL_ID, 0);
m_list.ShowWindow(SW_SHOW);
m_list.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_list.SetFocus();
m_list.Invalidate();
m_list.UpdateWindow();
}
void SwitchToAboutView()
{
SetFullScreen(FALSE);
m_hWndClient = m_aboutView;
m_list.ShowWindow(SW_HIDE);
m_list.SetWindowLongPtr(GWL_ID, 0);
m_notif.ShowWindow(SW_HIDE);
m_notif.SetWindowLongPtr(GWL_ID, 0);
m_aboutView.ShowWindow(SW_SHOW);
m_aboutView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_aboutView.SetFocus();
UpdateLayout();
}
void CaptureScreen(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
CDC dcTemp; dcTemp.CreateCompatibleDC(dc);
CBitmap bmpBkg; bmpBkg.CreateCompatibleBitmap(dc, rc.right, rc.bottom);
CBitmap bmpOld = dcTemp.SelectBitmap(bmpBkg);
dcTemp.FillSolidRect(&rc, RGB(0,0,0));
dcTemp.SelectBitmap(bmpOld);
m_imgBkg.CreateFromHBITMAP(bmpBkg);
m_imgBkg.AlphaCreate();
m_imgBkg.AlphaSet((BYTE)m_iTransp);
}
};
<file_sep>/SQLCEHelper/Include/sqlce_oledb.h
//=============================================================================
// Microsoft SQL Server Compact Edition (Version 3.5)
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// Component: Programmability (Native)
//
// File: sqlce_oledb.h
//
// File Comments: OLE DB Native Programming Interfaces
//=============================================================================
#include "rpc.h"
#include "rpcndr.h"
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __SQLCE_OLEDB_H__
#define __SQLCE_OLEDB_H__
#ifndef GUIDS_ONLY
#ifdef __cplusplus
extern "C"{
#endif
/* Forward Declarations */
#ifndef __IAccessor_FWD_DEFINED__
#define __IAccessor_FWD_DEFINED__
typedef interface IAccessor IAccessor;
#endif /* __IAccessor_FWD_DEFINED__ */
#ifndef __IRowset_FWD_DEFINED__
#define __IRowset_FWD_DEFINED__
typedef interface IRowset IRowset;
#endif /* __IRowset_FWD_DEFINED__ */
#ifndef __IRowsetInfo_FWD_DEFINED__
#define __IRowsetInfo_FWD_DEFINED__
typedef interface IRowsetInfo IRowsetInfo;
#endif /* __IRowsetInfo_FWD_DEFINED__ */
#ifndef __IRowsetLocate_FWD_DEFINED__
#define __IRowsetLocate_FWD_DEFINED__
typedef interface IRowsetLocate IRowsetLocate;
#endif /* __IRowsetLocate_FWD_DEFINED__ */
#ifndef __IRowsetResynch_FWD_DEFINED__
#define __IRowsetResynch_FWD_DEFINED__
typedef interface IRowsetResynch IRowsetResynch;
#endif /* __IRowsetResynch_FWD_DEFINED__ */
#ifndef __IRowsetScroll_FWD_DEFINED__
#define __IRowsetScroll_FWD_DEFINED__
typedef interface IRowsetScroll IRowsetScroll;
#endif /* __IRowsetScroll_FWD_DEFINED__ */
#ifndef __IChapteredRowset_FWD_DEFINED__
#define __IChapteredRowset_FWD_DEFINED__
typedef interface IChapteredRowset IChapteredRowset;
#endif /* __IChapteredRowset_FWD_DEFINED__ */
#ifndef __IRowsetFind_FWD_DEFINED__
#define __IRowsetFind_FWD_DEFINED__
typedef interface IRowsetFind IRowsetFind;
#endif /* __IRowsetFind_FWD_DEFINED__ */
#ifndef __IRowPosition_FWD_DEFINED__
#define __IRowPosition_FWD_DEFINED__
typedef interface IRowPosition IRowPosition;
#endif /* __IRowPosition_FWD_DEFINED__ */
#ifndef __IRowPositionChange_FWD_DEFINED__
#define __IRowPositionChange_FWD_DEFINED__
typedef interface IRowPositionChange IRowPositionChange;
#endif /* __IRowPositionChange_FWD_DEFINED__ */
#ifndef __IViewRowset_FWD_DEFINED__
#define __IViewRowset_FWD_DEFINED__
typedef interface IViewRowset IViewRowset;
#endif /* __IViewRowset_FWD_DEFINED__ */
#ifndef __IViewChapter_FWD_DEFINED__
#define __IViewChapter_FWD_DEFINED__
typedef interface IViewChapter IViewChapter;
#endif /* __IViewChapter_FWD_DEFINED__ */
#ifndef __IViewSort_FWD_DEFINED__
#define __IViewSort_FWD_DEFINED__
typedef interface IViewSort IViewSort;
#endif /* __IViewSort_FWD_DEFINED__ */
#ifndef __IViewFilter_FWD_DEFINED__
#define __IViewFilter_FWD_DEFINED__
typedef interface IViewFilter IViewFilter;
#endif /* __IViewFilter_FWD_DEFINED__ */
#ifndef __IRowsetView_FWD_DEFINED__
#define __IRowsetView_FWD_DEFINED__
typedef interface IRowsetView IRowsetView;
#endif /* __IRowsetView_FWD_DEFINED__ */
#ifndef __IRowsetExactScroll_FWD_DEFINED__
#define __IRowsetExactScroll_FWD_DEFINED__
typedef interface IRowsetExactScroll IRowsetExactScroll;
#endif /* __IRowsetExactScroll_FWD_DEFINED__ */
#ifndef __IRowsetChange_FWD_DEFINED__
#define __IRowsetChange_FWD_DEFINED__
typedef interface IRowsetChange IRowsetChange;
#endif /* __IRowsetChange_FWD_DEFINED__ */
#ifndef __IRowsetUpdate_FWD_DEFINED__
#define __IRowsetUpdate_FWD_DEFINED__
typedef interface IRowsetUpdate IRowsetUpdate;
#endif /* __IRowsetUpdate_FWD_DEFINED__ */
#ifndef __IRowsetIdentity_FWD_DEFINED__
#define __IRowsetIdentity_FWD_DEFINED__
typedef interface IRowsetIdentity IRowsetIdentity;
#endif /* __IRowsetIdentity_FWD_DEFINED__ */
#ifndef __IRowsetNotify_FWD_DEFINED__
#define __IRowsetNotify_FWD_DEFINED__
typedef interface IRowsetNotify IRowsetNotify;
#endif /* __IRowsetNotify_FWD_DEFINED__ */
#ifndef __IRowsetIndex_FWD_DEFINED__
#define __IRowsetIndex_FWD_DEFINED__
typedef interface IRowsetIndex IRowsetIndex;
#endif /* __IRowsetIndex_FWD_DEFINED__ */
#ifndef __ICommand_FWD_DEFINED__
#define __ICommand_FWD_DEFINED__
typedef interface ICommand ICommand;
#endif /* __ICommand_FWD_DEFINED__ */
#ifndef __IMultipleResults_FWD_DEFINED__
#define __IMultipleResults_FWD_DEFINED__
typedef interface IMultipleResults IMultipleResults;
#endif /* __IMultipleResults_FWD_DEFINED__ */
#ifndef __IConvertType_FWD_DEFINED__
#define __IConvertType_FWD_DEFINED__
typedef interface IConvertType IConvertType;
#endif /* __IConvertType_FWD_DEFINED__ */
#ifndef __ICommandPrepare_FWD_DEFINED__
#define __ICommandPrepare_FWD_DEFINED__
typedef interface ICommandPrepare ICommandPrepare;
#endif /* __ICommandPrepare_FWD_DEFINED__ */
#ifndef __ICommandProperties_FWD_DEFINED__
#define __ICommandProperties_FWD_DEFINED__
typedef interface ICommandProperties ICommandProperties;
#endif /* __ICommandProperties_FWD_DEFINED__ */
#ifndef __ICommandText_FWD_DEFINED__
#define __ICommandText_FWD_DEFINED__
typedef interface ICommandText ICommandText;
#endif /* __ICommandText_FWD_DEFINED__ */
#ifndef __ICommandWithParameters_FWD_DEFINED__
#define __ICommandWithParameters_FWD_DEFINED__
typedef interface ICommandWithParameters ICommandWithParameters;
#endif /* __ICommandWithParameters_FWD_DEFINED__ */
#ifndef __IColumnsRowset_FWD_DEFINED__
#define __IColumnsRowset_FWD_DEFINED__
typedef interface IColumnsRowset IColumnsRowset;
#endif /* __IColumnsRowset_FWD_DEFINED__ */
#ifndef __IColumnsInfo_FWD_DEFINED__
#define __IColumnsInfo_FWD_DEFINED__
typedef interface IColumnsInfo IColumnsInfo;
#endif /* __IColumnsInfo_FWD_DEFINED__ */
#ifndef __IDBCreateCommand_FWD_DEFINED__
#define __IDBCreateCommand_FWD_DEFINED__
typedef interface IDBCreateCommand IDBCreateCommand;
#endif /* __IDBCreateCommand_FWD_DEFINED__ */
#ifndef __IDBCreateSession_FWD_DEFINED__
#define __IDBCreateSession_FWD_DEFINED__
typedef interface IDBCreateSession IDBCreateSession;
#endif /* __IDBCreateSession_FWD_DEFINED__ */
#ifndef __ISourcesRowset_FWD_DEFINED__
#define __ISourcesRowset_FWD_DEFINED__
typedef interface ISourcesRowset ISourcesRowset;
#endif /* __ISourcesRowset_FWD_DEFINED__ */
#ifndef __IDBProperties_FWD_DEFINED__
#define __IDBProperties_FWD_DEFINED__
typedef interface IDBProperties IDBProperties;
#endif /* __IDBProperties_FWD_DEFINED__ */
#ifndef __IDBInitialize_FWD_DEFINED__
#define __IDBInitialize_FWD_DEFINED__
typedef interface IDBInitialize IDBInitialize;
#endif /* __IDBInitialize_FWD_DEFINED__ */
#ifndef __IDBInfo_FWD_DEFINED__
#define __IDBInfo_FWD_DEFINED__
typedef interface IDBInfo IDBInfo;
#endif /* __IDBInfo_FWD_DEFINED__ */
#ifndef __IDBDataSourceAdmin_FWD_DEFINED__
#define __IDBDataSourceAdmin_FWD_DEFINED__
typedef interface IDBDataSourceAdmin IDBDataSourceAdmin;
#endif /* __IDBDataSourceAdmin_FWD_DEFINED__ */
#ifndef __IDBAsynchNotify_FWD_DEFINED__
#define __IDBAsynchNotify_FWD_DEFINED__
typedef interface IDBAsynchNotify IDBAsynchNotify;
#endif /* __IDBAsynchNotify_FWD_DEFINED__ */
#ifndef __IDBAsynchStatus_FWD_DEFINED__
#define __IDBAsynchStatus_FWD_DEFINED__
typedef interface IDBAsynchStatus IDBAsynchStatus;
#endif /* __IDBAsynchStatus_FWD_DEFINED__ */
#ifndef __ISessionProperties_FWD_DEFINED__
#define __ISessionProperties_FWD_DEFINED__
typedef interface ISessionProperties ISessionProperties;
#endif /* __ISessionProperties_FWD_DEFINED__ */
#ifndef __IIndexDefinition_FWD_DEFINED__
#define __IIndexDefinition_FWD_DEFINED__
typedef interface IIndexDefinition IIndexDefinition;
#endif /* __IIndexDefinition_FWD_DEFINED__ */
#ifndef __ITableDefinition_FWD_DEFINED__
#define __ITableDefinition_FWD_DEFINED__
typedef interface ITableDefinition ITableDefinition;
#endif /* __ITableDefinition_FWD_DEFINED__ */
#ifndef __IOpenRowset_FWD_DEFINED__
#define __IOpenRowset_FWD_DEFINED__
typedef interface IOpenRowset IOpenRowset;
#endif /* __IOpenRowset_FWD_DEFINED__ */
#ifndef __IDBSchemaRowset_FWD_DEFINED__
#define __IDBSchemaRowset_FWD_DEFINED__
typedef interface IDBSchemaRowset IDBSchemaRowset;
#endif /* __IDBSchemaRowset_FWD_DEFINED__ */
#ifndef __IMDDataset_FWD_DEFINED__
#define __IMDDataset_FWD_DEFINED__
typedef interface IMDDataset IMDDataset;
#endif /* __IMDDataset_FWD_DEFINED__ */
#ifndef __IMDFind_FWD_DEFINED__
#define __IMDFind_FWD_DEFINED__
typedef interface IMDFind IMDFind;
#endif /* __IMDFind_FWD_DEFINED__ */
#ifndef __IMDRangeRowset_FWD_DEFINED__
#define __IMDRangeRowset_FWD_DEFINED__
typedef interface IMDRangeRowset IMDRangeRowset;
#endif /* __IMDRangeRowset_FWD_DEFINED__ */
#ifndef __IAlterTable_FWD_DEFINED__
#define __IAlterTable_FWD_DEFINED__
typedef interface IAlterTable IAlterTable;
#endif /* __IAlterTable_FWD_DEFINED__ */
#ifndef __IAlterIndex_FWD_DEFINED__
#define __IAlterIndex_FWD_DEFINED__
typedef interface IAlterIndex IAlterIndex;
#endif /* __IAlterIndex_FWD_DEFINED__ */
#ifndef __IRowsetChapterMember_FWD_DEFINED__
#define __IRowsetChapterMember_FWD_DEFINED__
typedef interface IRowsetChapterMember IRowsetChapterMember;
#endif /* __IRowsetChapterMember_FWD_DEFINED__ */
#ifndef __ICommandPersist_FWD_DEFINED__
#define __ICommandPersist_FWD_DEFINED__
typedef interface ICommandPersist ICommandPersist;
#endif /* __ICommandPersist_FWD_DEFINED__ */
#ifndef __IRowsetRefresh_FWD_DEFINED__
#define __IRowsetRefresh_FWD_DEFINED__
typedef interface IRowsetRefresh IRowsetRefresh;
#endif /* __IRowsetRefresh_FWD_DEFINED__ */
#ifndef __IParentRowset_FWD_DEFINED__
#define __IParentRowset_FWD_DEFINED__
typedef interface IParentRowset IParentRowset;
#endif /* __IParentRowset_FWD_DEFINED__ */
#ifndef __IErrorRecords_FWD_DEFINED__
#define __IErrorRecords_FWD_DEFINED__
typedef interface IErrorRecords IErrorRecords;
#endif /* __IErrorRecords_FWD_DEFINED__ */
#ifndef __IErrorLookup_FWD_DEFINED__
#define __IErrorLookup_FWD_DEFINED__
typedef interface IErrorLookup IErrorLookup;
#endif /* __IErrorLookup_FWD_DEFINED__ */
#ifndef __ISQLErrorInfo_FWD_DEFINED__
#define __ISQLErrorInfo_FWD_DEFINED__
typedef interface ISQLErrorInfo ISQLErrorInfo;
#endif /* __ISQLErrorInfo_FWD_DEFINED__ */
#ifndef __IGetDataSource_FWD_DEFINED__
#define __IGetDataSource_FWD_DEFINED__
typedef interface IGetDataSource IGetDataSource;
#endif /* __IGetDataSource_FWD_DEFINED__ */
#ifndef __ITransactionLocal_FWD_DEFINED__
#define __ITransactionLocal_FWD_DEFINED__
typedef interface ITransactionLocal ITransactionLocal;
#endif /* __ITransactionLocal_FWD_DEFINED__ */
#ifndef __ITransactionJoin_FWD_DEFINED__
#define __ITransactionJoin_FWD_DEFINED__
typedef interface ITransactionJoin ITransactionJoin;
#endif /* __ITransactionJoin_FWD_DEFINED__ */
#ifndef __ITransactionObject_FWD_DEFINED__
#define __ITransactionObject_FWD_DEFINED__
typedef interface ITransactionObject ITransactionObject;
#endif /* __ITransactionObject_FWD_DEFINED__ */
#ifndef __ITrusteeAdmin_FWD_DEFINED__
#define __ITrusteeAdmin_FWD_DEFINED__
typedef interface ITrusteeAdmin ITrusteeAdmin;
#endif /* __ITrusteeAdmin_FWD_DEFINED__ */
#ifndef __ITrusteeGroupAdmin_FWD_DEFINED__
#define __ITrusteeGroupAdmin_FWD_DEFINED__
typedef interface ITrusteeGroupAdmin ITrusteeGroupAdmin;
#endif /* __ITrusteeGroupAdmin_FWD_DEFINED__ */
#ifndef __IObjectAccessControl_FWD_DEFINED__
#define __IObjectAccessControl_FWD_DEFINED__
typedef interface IObjectAccessControl IObjectAccessControl;
#endif /* __IObjectAccessControl_FWD_DEFINED__ */
#ifndef __ISecurityInfo_FWD_DEFINED__
#define __ISecurityInfo_FWD_DEFINED__
typedef interface ISecurityInfo ISecurityInfo;
#endif /* __ISecurityInfo_FWD_DEFINED__ */
#ifndef __ITableCreation_FWD_DEFINED__
#define __ITableCreation_FWD_DEFINED__
typedef interface ITableCreation ITableCreation;
#endif /* __ITableCreation_FWD_DEFINED__ */
#ifndef __ITableDefinitionWithConstraints_FWD_DEFINED__
#define __ITableDefinitionWithConstraints_FWD_DEFINED__
typedef interface ITableDefinitionWithConstraints ITableDefinitionWithConstraints;
#endif /* __ITableDefinitionWithConstraints_FWD_DEFINED__ */
#ifndef __IRow_FWD_DEFINED__
#define __IRow_FWD_DEFINED__
typedef interface IRow IRow;
#endif /* __IRow_FWD_DEFINED__ */
#ifndef __IRowChange_FWD_DEFINED__
#define __IRowChange_FWD_DEFINED__
typedef interface IRowChange IRowChange;
#endif /* __IRowChange_FWD_DEFINED__ */
#ifndef __IRowSchemaChange_FWD_DEFINED__
#define __IRowSchemaChange_FWD_DEFINED__
typedef interface IRowSchemaChange IRowSchemaChange;
#endif /* __IRowSchemaChange_FWD_DEFINED__ */
#ifndef __IGetRow_FWD_DEFINED__
#define __IGetRow_FWD_DEFINED__
typedef interface IGetRow IGetRow;
#endif /* __IGetRow_FWD_DEFINED__ */
#ifndef __IBindResource_FWD_DEFINED__
#define __IBindResource_FWD_DEFINED__
typedef interface IBindResource IBindResource;
#endif /* __IBindResource_FWD_DEFINED__ */
#ifndef __IScopedOperations_FWD_DEFINED__
#define __IScopedOperations_FWD_DEFINED__
typedef interface IScopedOperations IScopedOperations;
#endif /* __IScopedOperations_FWD_DEFINED__ */
#ifndef __ICreateRow_FWD_DEFINED__
#define __ICreateRow_FWD_DEFINED__
typedef interface ICreateRow ICreateRow;
#endif /* __ICreateRow_FWD_DEFINED__ */
#ifndef __IDBBinderProperties_FWD_DEFINED__
#define __IDBBinderProperties_FWD_DEFINED__
typedef interface IDBBinderProperties IDBBinderProperties;
#endif /* __IDBBinderProperties_FWD_DEFINED__ */
#ifndef __IColumnsInfo2_FWD_DEFINED__
#define __IColumnsInfo2_FWD_DEFINED__
typedef interface IColumnsInfo2 IColumnsInfo2;
#endif /* __IColumnsInfo2_FWD_DEFINED__ */
#ifndef __IRegisterProvider_FWD_DEFINED__
#define __IRegisterProvider_FWD_DEFINED__
typedef interface IRegisterProvider IRegisterProvider;
#endif /* __IRegisterProvider_FWD_DEFINED__ */
#ifndef __IGetSession_FWD_DEFINED__
#define __IGetSession_FWD_DEFINED__
typedef interface IGetSession IGetSession;
#endif /* __IGetSession_FWD_DEFINED__ */
#ifndef __IGetSourceRow_FWD_DEFINED__
#define __IGetSourceRow_FWD_DEFINED__
typedef interface IGetSourceRow IGetSourceRow;
#endif /* __IGetSourceRow_FWD_DEFINED__ */
#ifndef __IRowsetCurrentIndex_FWD_DEFINED__
#define __IRowsetCurrentIndex_FWD_DEFINED__
typedef interface IRowsetCurrentIndex IRowsetCurrentIndex;
#endif /* __IRowsetCurrentIndex_FWD_DEFINED__ */
/* header files for imported files */
#include "wtypes.h"
#include "oaidl.h"
#include "ocidl.h"
#ifndef UNDER_CE
#include "urlmon.h"
#endif
#include "transact.h"
void __RPC_FAR * __RPC_USER MIDL_user_allocate(size_t);
void __RPC_USER MIDL_user_free( void __RPC_FAR * );
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0000
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
//+---------------------------------------------------------------------------
//
// Microsoft OLE DB
// Copyright (C) Microsoft Corporation, 1994 - 1998.
//
//----------------------------------------------------------------------------
#include <pshpack2.h> // 2-byte structure packing
extern RPC_IF_HANDLE __MIDL_itf_oledb_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0000_v0_0_s_ifspec;
#ifndef __DBStructureDefinitions_INTERFACE_DEFINED__
#define __DBStructureDefinitions_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: DBStructureDefinitions
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [auto_handle][unique][uuid] */
#ifndef UNALIGNED
#if defined(_MIPS_) || defined(_ALPHA_) || defined(_PPC_)
#define UNALIGNED __unaligned
#else
#define UNALIGNED
#endif
#endif //UNALIGNED
#undef OLEDBDECLSPEC
#if _MSC_VER >= 1100 && (!defined(SHx) || (defined(SHx) && _MSC_VER >= 1200))
#define OLEDBDECLSPEC __declspec(selectany)
#else
#define OLEDBDECLSPEC
#endif //_MSC_VER
typedef DWORD DBKIND;
enum DBKINDENUM
{ DBKIND_GUID_NAME = 0,
DBKIND_GUID_PROPID = DBKIND_GUID_NAME + 1,
DBKIND_NAME = DBKIND_GUID_PROPID + 1,
DBKIND_PGUID_NAME = DBKIND_NAME + 1,
DBKIND_PGUID_PROPID = DBKIND_PGUID_NAME + 1,
DBKIND_PROPID = DBKIND_PGUID_PROPID + 1,
DBKIND_GUID = DBKIND_PROPID + 1
};
#if defined(MIPSII_FP) || defined(MIPSIV) || defined(MIPSIV_FP)
#pragma pack(push,8)
#endif
typedef struct tagDBID
{
/* [switch_is][switch_type] */ union
{
/* [case()] */ GUID guid;
/* [case()] */ GUID __RPC_FAR *pguid;
/* [default] */ /* Empty union arm */
} uGuid;
DBKIND eKind;
/* [switch_is][switch_type] */ union
{
/* [case()] */ LPOLESTR pwszName;
/* [case()] */ ULONG ulPropid;
/* [default] */ /* Empty union arm */
} uName;
} DBID;
#if defined(MIPSII_FP) || defined(MIPSIV) || defined(MIPSIV_FP)
#pragma pack(pop)
#endif
typedef struct tagDB_NUMERIC
{
BYTE precision;
BYTE scale;
BYTE sign;
BYTE val[ 16 ];
} DB_NUMERIC;
#ifndef _ULONGLONG_
typedef hyper LONGLONG;
typedef MIDL_uhyper ULONGLONG;
typedef LONGLONG __RPC_FAR *PLONGLONG;
typedef ULONGLONG __RPC_FAR *PULONGLONG;
#endif // _ULONGLONG_
#ifndef DECIMAL_NEG
#ifndef DECIMAL_SETZERO
typedef struct tagDEC {
USHORT wReserved;
union {
struct {
BYTE scale;
BYTE sign;
};
USHORT signscale;
};
ULONG Hi32;
union {
struct {
#ifdef _MAC
ULONG Mid32;
ULONG Lo32;
#else
ULONG Lo32;
ULONG Mid32;
#endif
};
ULONGLONG Lo64;
};
} DECIMAL;
#define DECIMAL_NEG ((BYTE)0x80)
#define DECIMAL_SETZERO(dec) {(dec).Lo64 = 0; (dec).Hi32 = 0; (dec).signscale = 0;}
#endif // DECIMAL_SETZERO
#endif // DECIMAL_NEG
typedef struct tagDBVECTOR
{
ULONG size;
/* [size_is] */ void __RPC_FAR *ptr;
} DBVECTOR;
typedef struct tagDBDATE
{
SHORT year;
USHORT month;
USHORT day;
} DBDATE;
typedef struct tagDBTIME
{
USHORT hour;
USHORT minute;
USHORT second;
} DBTIME;
typedef struct tagDBTIMESTAMP
{
SHORT year;
USHORT month;
USHORT day;
USHORT hour;
USHORT minute;
USHORT second;
ULONG fraction;
} DBTIMESTAMP;
#if !defined(_WINBASE_) && !defined(_FILETIME_)
#define _FILETIME_
typedef struct _FILETIME {
DWORD dwLowDateTime;
DWORD dwHighDateTime;
} FILETIME;
#endif // !_FILETIME
typedef signed char SBYTE;
typedef struct tagDB_VARNUMERIC
{
BYTE precision;
SBYTE scale;
BYTE sign;
BYTE val[ 1 ];
} DB_VARNUMERIC;
typedef struct _SEC_OBJECT_ELEMENT
{
GUID guidObjectType;
DBID ObjectID;
} SEC_OBJECT_ELEMENT;
typedef struct _SEC_OBJECT
{
DWORD cObjects;
/* [size_is] */ SEC_OBJECT_ELEMENT __RPC_FAR *prgObjects;
} SEC_OBJECT;
typedef struct tagDBIMPLICITSESSION
{
IUnknown __RPC_FAR *pUnkOuter;
IID __RPC_FAR *piid;
IUnknown __RPC_FAR *pSession;
} DBIMPLICITSESSION;
typedef WORD DBTYPE;
enum DBTYPEENUM
{ DBTYPE_EMPTY = 0,
DBTYPE_NULL = 1,
DBTYPE_I2 = 2,
DBTYPE_I4 = 3,
DBTYPE_R4 = 4,
DBTYPE_R8 = 5,
DBTYPE_CY = 6,
DBTYPE_DATE = 7,
DBTYPE_BSTR = 8,
DBTYPE_IDISPATCH = 9,
DBTYPE_ERROR = 10,
DBTYPE_BOOL = 11,
DBTYPE_VARIANT = 12,
DBTYPE_IUNKNOWN = 13,
DBTYPE_DECIMAL = 14,
DBTYPE_UI1 = 17,
DBTYPE_ARRAY = 0x2000,
DBTYPE_BYREF = 0x4000,
DBTYPE_I1 = 16,
DBTYPE_UI2 = 18,
DBTYPE_UI4 = 19,
DBTYPE_I8 = 20,
DBTYPE_UI8 = 21,
DBTYPE_GUID = 72,
DBTYPE_VECTOR = 0x1000,
DBTYPE_RESERVED = 0x8000,
DBTYPE_BYTES = 128,
DBTYPE_STR = 129,
DBTYPE_WSTR = 130,
DBTYPE_NUMERIC = 131,
DBTYPE_UDT = 132,
DBTYPE_DBDATE = 133,
DBTYPE_DBTIME = 134,
DBTYPE_DBTIMESTAMP = 135
};
enum DBTYPEENUM15
{ DBTYPE_HCHAPTER = 136
};
enum DBTYPEENUM20
{ DBTYPE_FILETIME = 64,
DBTYPE_PROPVARIANT = 138,
DBTYPE_VARNUMERIC = 139
};
typedef DWORD DBPART;
enum DBPARTENUM
{ DBPART_INVALID = 0,
DBPART_VALUE = 0x1,
DBPART_LENGTH = 0x2,
DBPART_STATUS = 0x4
};
typedef DWORD DBPARAMIO;
enum DBPARAMIOENUM
{ DBPARAMIO_NOTPARAM = 0,
DBPARAMIO_INPUT = 0x1,
DBPARAMIO_OUTPUT = 0x2
};
typedef DWORD DBBINDFLAG;
enum DBBINDFLAGENUM
{ DBBINDFLAG_HTML = 0x1
};
typedef DWORD DBMEMOWNER;
enum DBMEMOWNERENUM
{ DBMEMOWNER_CLIENTOWNED = 0,
DBMEMOWNER_PROVIDEROWNED = 0x1
};
typedef struct tagDBOBJECT
{
DWORD dwFlags;
IID iid;
} DBOBJECT;
typedef DWORD DBSTATUS;
enum DBSTATUSENUM
{ DBSTATUS_S_OK = 0,
DBSTATUS_E_BADACCESSOR = 1,
DBSTATUS_E_CANTCONVERTVALUE = 2,
DBSTATUS_S_ISNULL = 3,
DBSTATUS_S_TRUNCATED = 4,
DBSTATUS_E_SIGNMISMATCH = 5,
DBSTATUS_E_DATAOVERFLOW = 6,
DBSTATUS_E_CANTCREATE = 7,
DBSTATUS_E_UNAVAILABLE = 8,
DBSTATUS_E_PERMISSIONDENIED = 9,
DBSTATUS_E_INTEGRITYVIOLATION = 10,
DBSTATUS_E_SCHEMAVIOLATION = 11,
DBSTATUS_E_BADSTATUS = 12,
DBSTATUS_S_DEFAULT = 13
};
enum DBSTATUSENUM20
{ MDSTATUS_S_CELLEMPTY = 14,
DBSTATUS_S_IGNORE = 15
};
enum DBSTATUSENUM21
{ DBSTATUS_E_DOESNOTEXIST = 16,
DBSTATUS_E_INVALIDURL = 17,
DBSTATUS_E_RESOURCELOCKED = 18,
DBSTATUS_E_RESOURCEEXISTS = 19,
DBSTATUS_E_CANNOTCOMPLETE = 20,
DBSTATUS_E_VOLUMENOTFOUND = 21,
DBSTATUS_E_OUTOFSPACE = 22,
DBSTATUS_S_CANNOTDELETESOURCE = 23,
DBSTATUS_E_READONLY = 24,
DBSTATUS_E_RESOURCEOUTOFSCOPE = 25,
DBSTATUS_S_ALREADYEXISTS = 26
};
typedef DWORD DBBINDURLFLAG;
enum DBBINDURLFLAGENUM
{ DBBINDURLFLAG_READ = 0x1L,
DBBINDURLFLAG_WRITE = 0x2L,
DBBINDURLFLAG_READWRITE = 0x3L,
DBBINDURLFLAG_SHARE_DENY_READ = 0x4L,
DBBINDURLFLAG_SHARE_DENY_WRITE = 0x8L,
DBBINDURLFLAG_SHARE_EXCLUSIVE = 0xcL,
DBBINDURLFLAG_SHARE_DENY_NONE = 0x10L,
DBBINDURLFLAG_ASYNCHRONOUS = 0x1000L,
DBBINDURLFLAG_COLLECTION = 0x2000L,
DBBINDURLFLAG_DELAYFETCHSTREAM = 0x4000L,
DBBINDURLFLAG_DELAYFETCHCOLUMNS = 0x8000L,
DBBINDURLFLAG_RECURSIVE = 0x400000L,
DBBINDURLFLAG_OUTPUT = 0x800000L,
DBBINDURLFLAG_WAITFORINIT = 0x1000000L,
DBBINDURLFLAG_OPENIFEXISTS = 0x2000000L,
DBBINDURLFLAG_OVERWRITE = 0x4000000L,
DBBINDURLFLAG_ISSTRUCTUREDDOCUMENT = 0x8000000L
};
typedef DWORD DBBINDURLSTATUS;
enum DBBINDURLSTATUSENUM
{ DBBINDURLSTATUS_S_DENYNOTSUPPORTED = 0x1L,
DBBINDURLSTATUS_S_DENYTYPENOTSUPPORTED = 0x4L,
DBBINDURLSTATUS_S_REDIRECTED = 0x8L
};
typedef struct tagDBBINDEXT
{
/* [size_is] */ BYTE __RPC_FAR *pExtension;
ULONG ulExtension;
} DBBINDEXT;
typedef struct tagDBBINDING
{
ULONG iOrdinal;
ULONG obValue;
ULONG obLength;
ULONG obStatus;
ITypeInfo __RPC_FAR *pTypeInfo;
DBOBJECT __RPC_FAR *pObject;
DBBINDEXT __RPC_FAR *pBindExt;
DBPART dwPart;
DBMEMOWNER dwMemOwner;
DBPARAMIO eParamIO;
ULONG cbMaxLen;
DWORD dwFlags;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
} DBBINDING;
typedef DWORD DBROWSTATUS;
enum DBROWSTATUSENUM
{ DBROWSTATUS_S_OK = 0,
DBROWSTATUS_S_MULTIPLECHANGES = 2,
DBROWSTATUS_S_PENDINGCHANGES = 3,
DBROWSTATUS_E_CANCELED = 4,
DBROWSTATUS_E_CANTRELEASE = 6,
DBROWSTATUS_E_CONCURRENCYVIOLATION = 7,
DBROWSTATUS_E_DELETED = 8,
DBROWSTATUS_E_PENDINGINSERT = 9,
DBROWSTATUS_E_NEWLYINSERTED = 10,
DBROWSTATUS_E_INTEGRITYVIOLATION = 11,
DBROWSTATUS_E_INVALID = 12,
DBROWSTATUS_E_MAXPENDCHANGESEXCEEDED = 13,
DBROWSTATUS_E_OBJECTOPEN = 14,
DBROWSTATUS_E_OUTOFMEMORY = 15,
DBROWSTATUS_E_PERMISSIONDENIED = 16,
DBROWSTATUS_E_LIMITREACHED = 17,
DBROWSTATUS_E_SCHEMAVIOLATION = 18,
DBROWSTATUS_E_FAIL = 19
};
enum DBROWSTATUSENUM20
{ DBROWSTATUS_S_NOCHANGE = 20
};
typedef ULONG HACCESSOR;
#define DB_NULL_HACCESSOR 0x00 // deprecated; use DB_INVALID_HACCESSOR instead
#define DB_INVALID_HACCESSOR 0x00
typedef ULONG HROW;
#define DB_NULL_HROW 0x00
typedef ULONG HWATCHREGION;
#define DBWATCHREGION_NULL NULL
typedef ULONG HCHAPTER;
#define DB_NULL_HCHAPTER 0x00
#define DB_INVALID_HCHAPTER 0x00 // deprecated; use DB_NULL_HCHAPTER instead
typedef struct tagDBFAILUREINFO
{
HROW hRow;
ULONG iColumn;
HRESULT failure;
} DBFAILUREINFO;
typedef DWORD DBCOLUMNFLAGS;
enum DBCOLUMNFLAGSENUM
{ DBCOLUMNFLAGS_ISBOOKMARK = 0x1,
DBCOLUMNFLAGS_MAYDEFER = 0x2,
DBCOLUMNFLAGS_WRITE = 0x4,
DBCOLUMNFLAGS_WRITEUNKNOWN = 0x8,
DBCOLUMNFLAGS_ISFIXEDLENGTH = 0x10,
DBCOLUMNFLAGS_ISNULLABLE = 0x20,
DBCOLUMNFLAGS_MAYBENULL = 0x40,
DBCOLUMNFLAGS_ISLONG = 0x80,
DBCOLUMNFLAGS_ISROWID = 0x100,
DBCOLUMNFLAGS_ISROWVER = 0x200,
DBCOLUMNFLAGS_CACHEDEFERRED = 0x1000
};
enum DBCOLUMNFLAGSENUM20
{ DBCOLUMNFLAGS_SCALEISNEGATIVE = 0x4000,
DBCOLUMNFLAGS_KEYCOLUMN = 0x8000
};
enum DBCOLUMNFLAGS15ENUM
{ DBCOLUMNFLAGS_ISCHAPTER = 0x2000
};
enum DBCOLUMNFLAGSENUM21
{ DBCOLUMNFLAGS_ISROWURL = 0x10000,
DBCOLUMNFLAGS_ISDEFAULTSTREAM = 0x20000,
DBCOLUMNFLAGS_ISCOLLECTION = 0x40000
};
typedef struct tagDBCOLUMNINFO
{
LPOLESTR pwszName;
ITypeInfo __RPC_FAR *pTypeInfo;
ULONG iOrdinal;
DBCOLUMNFLAGS dwFlags;
ULONG ulColumnSize;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
DBID columnid;
} DBCOLUMNINFO;
typedef
enum tagDBBOOKMARK
{ DBBMK_INVALID = 0,
DBBMK_FIRST = DBBMK_INVALID + 1,
DBBMK_LAST = DBBMK_FIRST + 1
} DBBOOKMARK;
#define STD_BOOKMARKLENGTH 1
#ifdef __cplusplus
inline BOOL IsEqualGUIDBase(const GUID &rguid1, const GUID &rguid2)
{ return !memcmp(&(rguid1.Data2), &(rguid2.Data2), sizeof(GUID) - sizeof(rguid1.Data1)); }
#else // !__cplusplus
#define IsEqualGuidBase(rguid1, rguid2) (!memcmp(&((rguid1).Data2), &((rguid2).Data2), sizeof(GUID) - sizeof((rguid1).Data1)))
#endif // __cplusplus
#define DB_INVALIDCOLUMN ULONG_MAX
#define DBCIDGUID {0x0C733A81L,0x2A1C,0x11CE,{0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D}}
#define DB_NULLGUID {0x00000000L,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}}
extern const OLEDBDECLSPEC DBID DB_NULLID = {DB_NULLGUID, 0, (LPOLESTR)0};
extern const OLEDBDECLSPEC DBID DBCOLUMN_IDNAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)2};
extern const OLEDBDECLSPEC DBID DBCOLUMN_NAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)3};
extern const OLEDBDECLSPEC DBID DBCOLUMN_NUMBER = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)4};
extern const OLEDBDECLSPEC DBID DBCOLUMN_TYPE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)5};
extern const OLEDBDECLSPEC DBID DBCOLUMN_PRECISION = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)7};
extern const OLEDBDECLSPEC DBID DBCOLUMN_SCALE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)8};
extern const OLEDBDECLSPEC DBID DBCOLUMN_FLAGS = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)9};
extern const OLEDBDECLSPEC DBID DBCOLUMN_BASECOLUMNNAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)10};
extern const OLEDBDECLSPEC DBID DBCOLUMN_BASETABLENAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)11};
extern const OLEDBDECLSPEC DBID DBCOLUMN_COLLATINGSEQUENCE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)12};
extern const OLEDBDECLSPEC DBID DBCOLUMN_COMPUTEMODE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)13};
extern const OLEDBDECLSPEC DBID DBCOLUMN_DEFAULTVALUE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)14};
extern const OLEDBDECLSPEC DBID DBCOLUMN_DOMAINNAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)15};
extern const OLEDBDECLSPEC DBID DBCOLUMN_HASDEFAULT = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)16};
extern const OLEDBDECLSPEC DBID DBCOLUMN_ISAUTOINCREMENT = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)17};
extern const OLEDBDECLSPEC DBID DBCOLUMN_ISCASESENSITIVE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)18};
extern const OLEDBDECLSPEC DBID DBCOLUMN_ISSEARCHABLE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)20};
extern const OLEDBDECLSPEC DBID DBCOLUMN_ISUNIQUE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)21};
extern const OLEDBDECLSPEC DBID DBCOLUMN_BASECATALOGNAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)23};
extern const OLEDBDECLSPEC DBID DBCOLUMN_BASESCHEMANAME = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)24};
extern const OLEDBDECLSPEC DBID DBCOLUMN_GUID = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)29};
extern const OLEDBDECLSPEC DBID DBCOLUMN_PROPID = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)30};
extern const OLEDBDECLSPEC DBID DBCOLUMN_TYPEINFO = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)31};
extern const OLEDBDECLSPEC DBID DBCOLUMN_DOMAINCATALOG = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)32};
extern const OLEDBDECLSPEC DBID DBCOLUMN_DOMAINSCHEMA = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)33};
extern const OLEDBDECLSPEC DBID DBCOLUMN_DATETIMEPRECISION = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)34};
extern const OLEDBDECLSPEC DBID DBCOLUMN_NUMERICPRECISIONRADIX = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)35};
extern const OLEDBDECLSPEC DBID DBCOLUMN_OCTETLENGTH = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)36};
extern const OLEDBDECLSPEC DBID DBCOLUMN_COLUMNSIZE = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)37};
extern const OLEDBDECLSPEC DBID DBCOLUMN_CLSID = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)38};
extern const OLEDBDECLSPEC DBID DBCOLUMN_MAYSORT = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)39};
extern const OLEDBDECLSPEC GUID DBSCHEMA_TABLES_INFO = {0xc8b522e0,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDGUID_MDX = {0xa07cccd0,0x8148,0x11d0,{0x87,0xbb,0x00,0xc0,0x4f,0xc3,0x39,0x42}};
extern const OLEDBDECLSPEC GUID DBGUID_MDX = {0xa07cccd0,0x8148,0x11d0,{0x87,0xbb,0x00,0xc0,0x4f,0xc3,0x39,0x42}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_CUBES = {0xc8b522d8,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_DIMENSIONS = {0xc8b522d9,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_HIERARCHIES = {0xc8b522da,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_LEVELS = {0xc8b522db,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_MEASURES = {0xc8b522dc,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_PROPERTIES = {0xc8b522dd,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID MDSCHEMA_MEMBERS = {0xc8b522de,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC DBID DBCOLUMN_BASETABLEVERSION = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)40};
extern const OLEDBDECLSPEC DBID DBCOLUMN_KEYCOLUMN = {DBCIDGUID, DBKIND_GUID_PROPID, (LPOLESTR)41};
#define DBGUID_ROWURL {0x0C733AB6L,0x2A1C,0x11CE,{0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D}}
#define DBGUID_ROWDEFAULTSTREAM {0x0C733AB7L,0x2A1C,0x11CE,{0xAD,0xE5,0x00,0xAA,0x00,0x44,0x77,0x3D}}
extern const OLEDBDECLSPEC GUID DBPROPSET_TRUSTEE = {0xc8b522e1,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_TABLE = {0xc8b522e2,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_COLUMN = {0xc8b522e4,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_DATABASE = {0xc8b522e5,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_PROCEDURE = {0xc8b522e6,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_VIEW = {0xc8b522e7,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_SCHEMA = {0xc8b522e8,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_DOMAIN = {0xc8b522e9,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_COLLATION = {0xc8b522ea,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_TRUSTEE = {0xc8b522eb,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_SCHEMAROWSET = {0xc8b522ec,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_CHARACTERSET = {0xc8b522ed,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBOBJECT_TRANSLATION = {0xc8b522ee,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_TRUSTEE = {0xc8b522ef,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_COLUMNALL = {0xc8b522f0,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_INDEXALL = {0xc8b522f1,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_TABLEALL = {0xc8b522f2,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_TRUSTEEALL = {0xc8b522f3,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_CONSTRAINTALL = {0xc8b522fa,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_DSO = {0xc8b522f4,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_SESSION = {0xc8b522f5,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_ROWSET = {0xc8b522f6,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_ROW = {0xc8b522f7,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_COMMAND = {0xc8b522f8,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_STREAM = {0xc8b522f9,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC DBID DBROWCOL_ROWURL = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)0};
extern const OLEDBDECLSPEC DBID DBROWCOL_PARSENAME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)2};
extern const OLEDBDECLSPEC DBID DBROWCOL_PARENTNAME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)3};
extern const OLEDBDECLSPEC DBID DBROWCOL_ABSOLUTEPARSENAME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)4};
extern const OLEDBDECLSPEC DBID DBROWCOL_ISHIDDEN = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)5};
extern const OLEDBDECLSPEC DBID DBROWCOL_ISREADONLY = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)6};
extern const OLEDBDECLSPEC DBID DBROWCOL_CONTENTTYPE = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)7};
extern const OLEDBDECLSPEC DBID DBROWCOL_CONTENTCLASS = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)8};
extern const OLEDBDECLSPEC DBID DBROWCOL_CONTENTLANGUAGE = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)9};
extern const OLEDBDECLSPEC DBID DBROWCOL_CREATIONTIME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)10};
extern const OLEDBDECLSPEC DBID DBROWCOL_LASTACCESSTIME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)11};
extern const OLEDBDECLSPEC DBID DBROWCOL_LASTWRITETIME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)12};
extern const OLEDBDECLSPEC DBID DBROWCOL_STREAMSIZE = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)13};
extern const OLEDBDECLSPEC DBID DBROWCOL_ISCOLLECTION = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)14};
extern const OLEDBDECLSPEC DBID DBROWCOL_ISSTRUCTUREDDOCUMENT = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)15};
extern const OLEDBDECLSPEC DBID DBROWCOL_DEFAULTDOCUMENT = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)16};
extern const OLEDBDECLSPEC DBID DBROWCOL_DISPLAYNAME = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)17};
extern const OLEDBDECLSPEC DBID DBROWCOL_ISROOT = {DBGUID_ROWURL, DBKIND_GUID_PROPID, (LPOLESTR)18};
extern const OLEDBDECLSPEC DBID DBROWCOL_DEFAULTSTREAM = {DBGUID_ROWDEFAULTSTREAM, DBKIND_GUID_PROPID, (LPOLESTR)0};
extern const OLEDBDECLSPEC GUID DBGUID_CONTAINEROBJECT = {0xc8b522fb,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_ASSERTIONS = {0xc8b52210,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_CATALOGS = {0xc8b52211,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_CHARACTER_SETS = {0xc8b52212,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_COLLATIONS = {0xc8b52213,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_COLUMNS = {0xc8b52214,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_CHECK_CONSTRAINTS = {0xc8b52215,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_CONSTRAINT_COLUMN_USAGE = {0xc8b52216,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_CONSTRAINT_TABLE_USAGE = {0xc8b52217,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_KEY_COLUMN_USAGE = {0xc8b52218,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_REFERENTIAL_CONSTRAINTS = {0xc8b52219,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_TABLE_CONSTRAINTS = {0xc8b5221a,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_COLUMN_DOMAIN_USAGE = {0xc8b5221b,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_INDEXES = {0xc8b5221e,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_COLUMN_PRIVILEGES = {0xc8b52221,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_TABLE_PRIVILEGES = {0xc8b52222,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_USAGE_PRIVILEGES = {0xc8b52223,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_PROCEDURES = {0xc8b52224,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_SCHEMATA = {0xc8b52225,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_SQL_LANGUAGES = {0xc8b52226,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_STATISTICS = {0xc8b52227,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_TABLES = {0xc8b52229,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_TRANSLATIONS = {0xc8b5222a,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_PROVIDER_TYPES = {0xc8b5222c,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_VIEWS = {0xc8b5222d,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_VIEW_COLUMN_USAGE = {0xc8b5222e,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_VIEW_TABLE_USAGE = {0xc8b5222f,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_PROCEDURE_PARAMETERS = {0xc8b522b8,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_FOREIGN_KEYS = {0xc8b522c4,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_PRIMARY_KEYS = {0xc8b522c5,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBSCHEMA_PROCEDURE_COLUMNS = {0xc8b522c9,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBCOL_SELFCOLUMNS = {0xc8b52231,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBCOL_SPECIALCOL = {0xc8b52232,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID PSGUID_QUERY = {0x49691c90,0x7e17,0x101a,{0xa9,0x1c,0x08,0x00,0x2b,0x2e,0xcd,0xa9}};
extern const OLEDBDECLSPEC GUID DBPROPSET_COLUMN = {0xc8b522b9,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_DATASOURCE = {0xc8b522ba,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_DATASOURCEINFO = {0xc8b522bb,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_DBINIT = {0xc8b522bc,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_INDEX = {0xc8b522bd,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_ROWSET = {0xc8b522be,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_TABLE = {0xc8b522bf,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_DATASOURCEALL = {0xc8b522c0,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_DATASOURCEINFOALL = {0xc8b522c1,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_ROWSETALL = {0xc8b522c2,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_SESSION = {0xc8b522c6,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_SESSIONALL = {0xc8b522c7,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_DBINITALL = {0xc8b522ca,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_PROPERTIESINERROR = {0xc8b522d4,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBPROPSET_VIEW = {0xc8b522df,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
// DBGUID_DBSQL is deprecated; use DBGUID_DEFAULT instead
extern const OLEDBDECLSPEC GUID DBGUID_DBSQL = {0xc8b521fb,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_DEFAULT = {0xc8b521fb,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC GUID DBGUID_SQL = {0xc8b522d7,0x5cf3,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
enum DBPROPENUM
{ DBPROP_ABORTPRESERVE = 0x2L,
DBPROP_ACTIVESESSIONS = 0x3L,
DBPROP_APPENDONLY = 0xbbL,
DBPROP_ASYNCTXNABORT = 0xa8L,
DBPROP_ASYNCTXNCOMMIT = 0x4L,
DBPROP_AUTH_CACHE_AUTHINFO = 0x5L,
DBPROP_AUTH_ENCRYPT_PASSWORD = <PASSWORD>,
DBPROP_AUTH_INTEGRATED = 0x7L,
DBPROP_AUTH_MASK_PASSWORD = <PASSWORD>,
DBPROP_AUTH_PASSWORD = <PASSWORD>,
DBPROP_AUTH_PERSIST_ENCRYPTED = 0xaL,
DBPROP_AUTH_PERSIST_SENSITIVE_AUTHINFO = 0xbL,
DBPROP_AUTH_USERID = 0xcL,
DBPROP_BLOCKINGSTORAGEOBJECTS = 0xdL,
DBPROP_BOOKMARKS = 0xeL,
DBPROP_BOOKMARKSKIPPED = 0xfL,
DBPROP_BOOKMARKTYPE = 0x10L,
DBPROP_BYREFACCESSORS = 0x78L,
DBPROP_CACHEDEFERRED = 0x11L,
DBPROP_CANFETCHBACKWARDS = 0x12L,
DBPROP_CANHOLDROWS = 0x13L,
DBPROP_CANSCROLLBACKWARDS = 0x15L,
DBPROP_CATALOGLOCATION = 0x16L,
DBPROP_CATALOGTERM = 0x17L,
DBPROP_CATALOGUSAGE = 0x18L,
DBPROP_CHANGEINSERTEDROWS = 0xbcL,
DBPROP_COL_AUTOINCREMENT = 0x1aL,
DBPROP_COL_DEFAULT = 0x1bL,
DBPROP_COL_DESCRIPTION = 0x1cL,
DBPROP_COL_FIXEDLENGTH = 0xa7L,
DBPROP_COL_NULLABLE = 0x1dL,
DBPROP_COL_PRIMARYKEY = 0x1eL,
DBPROP_COL_UNIQUE = 0x1fL,
DBPROP_COLUMNDEFINITION = 0x20L,
DBPROP_COLUMNRESTRICT = 0x21L,
DBPROP_COMMANDTIMEOUT = 0x22L,
DBPROP_COMMITPRESERVE = 0x23L,
DBPROP_CONCATNULLBEHAVIOR = 0x24L,
DBPROP_CURRENTCATALOG = 0x25L,
DBPROP_DATASOURCENAME = 0x26L,
DBPROP_DATASOURCEREADONLY = 0x27L,
DBPROP_DBMSNAME = 0x28L,
DBPROP_DBMSVER = 0x29L,
DBPROP_DEFERRED = 0x2aL,
DBPROP_DELAYSTORAGEOBJECTS = 0x2bL,
DBPROP_DSOTHREADMODEL = 0xa9L,
DBPROP_GROUPBY = 0x2cL,
DBPROP_HETEROGENEOUSTABLES = 0x2dL,
DBPROP_IAccessor = 0x79L,
DBPROP_IColumnsInfo = 0x7aL,
DBPROP_IColumnsRowset = 0x7bL,
DBPROP_IConnectionPointContainer = 0x7cL,
DBPROP_IConvertType = 0xc2L,
DBPROP_IRowset = 0x7eL,
DBPROP_IRowsetChange = 0x7fL,
DBPROP_IRowsetIdentity = 0x80L,
DBPROP_IRowsetIndex = 0x9fL,
DBPROP_IRowsetInfo = 0x81L,
DBPROP_IRowsetLocate = 0x82L,
DBPROP_IRowsetResynch = 0x84L,
DBPROP_IRowsetScroll = 0x85L,
DBPROP_IRowsetUpdate = 0x86L,
DBPROP_ISupportErrorInfo = 0x87L,
DBPROP_ILockBytes = 0x88L,
DBPROP_ISequentialStream = 0x89L,
DBPROP_IStorage = 0x8aL,
DBPROP_IStream = 0x8bL,
DBPROP_IDENTIFIERCASE = 0x2eL,
DBPROP_IMMOBILEROWS = 0x2fL,
DBPROP_INDEX_AUTOUPDATE = 0x30L,
DBPROP_INDEX_CLUSTERED = 0x31L,
DBPROP_INDEX_FILLFACTOR = 0x32L,
DBPROP_INDEX_INITIALSIZE = 0x33L,
DBPROP_INDEX_NULLCOLLATION = 0x34L,
DBPROP_INDEX_NULLS = 0x35L,
DBPROP_INDEX_PRIMARYKEY = 0x36L,
DBPROP_INDEX_SORTBOOKMARKS = 0x37L,
DBPROP_INDEX_TEMPINDEX = 0xa3L,
DBPROP_INDEX_TYPE = 0x38L,
DBPROP_INDEX_UNIQUE = 0x39L,
DBPROP_INIT_DATASOURCE = 0x3bL,
DBPROP_INIT_HWND = 0x3cL,
DBPROP_INIT_IMPERSONATION_LEVEL = 0x3dL,
DBPROP_INIT_LCID = 0xbaL,
DBPROP_INIT_LOCATION = 0x3eL,
DBPROP_INIT_MODE = 0x3fL,
DBPROP_INIT_PROMPT = 0x40L,
DBPROP_INIT_PROTECTION_LEVEL = 0x41L,
DBPROP_INIT_PROVIDERSTRING = 0xa0L,
DBPROP_INIT_TIMEOUT = 0x42L,
DBPROP_LITERALBOOKMARKS = 0x43L,
DBPROP_LITERALIDENTITY = 0x44L,
DBPROP_MARSHALLABLE = 0xc5L,
DBPROP_MAXINDEXSIZE = 0x46L,
DBPROP_MAXOPENROWS = 0x47L,
DBPROP_MAXPENDINGROWS = 0x48L,
DBPROP_MAXROWS = 0x49L,
DBPROP_MAXROWSIZE = 0x4aL,
DBPROP_MAXROWSIZEINCLUDESBLOB = 0x4bL,
DBPROP_MAXTABLESINSELECT = 0x4cL,
DBPROP_MAYWRITECOLUMN = 0x4dL,
DBPROP_MEMORYUSAGE = 0x4eL,
DBPROP_MULTIPLEPARAMSETS = 0xbfL,
DBPROP_MULTIPLERESULTS = 0xc4L,
DBPROP_MULTIPLESTORAGEOBJECTS = 0x50L,
DBPROP_MULTITABLEUPDATE = 0x51L,
DBPROP_NOTIFICATIONGRANULARITY = 0xc6L,
DBPROP_NOTIFICATIONPHASES = 0x52L,
DBPROP_NOTIFYCOLUMNSET = 0xabL,
DBPROP_NOTIFYROWDELETE = 0xadL,
DBPROP_NOTIFYROWFIRSTCHANGE = 0xaeL,
DBPROP_NOTIFYROWINSERT = 0xafL,
DBPROP_NOTIFYROWRESYNCH = 0xb1L,
DBPROP_NOTIFYROWSETCHANGED = 0xd3L,
DBPROP_NOTIFYROWSETRELEASE = 0xb2L,
DBPROP_NOTIFYROWSETFETCHPOSITIONCHANGE = 0xb3L,
DBPROP_NOTIFYROWUNDOCHANGE = 0xb4L,
DBPROP_NOTIFYROWUNDODELETE = 0xb5L,
DBPROP_NOTIFYROWUNDOINSERT = 0xb6L,
DBPROP_NOTIFYROWUPDATE = 0xb7L,
DBPROP_NULLCOLLATION = 0x53L,
DBPROP_OLEOBJECTS = 0x54L,
DBPROP_ORDERBYCOLUMNSINSELECT = 0x55L,
DBPROP_ORDEREDBOOKMARKS = 0x56L,
DBPROP_OTHERINSERT = 0x57L,
DBPROP_OTHERUPDATEDELETE = 0x58L,
DBPROP_OUTPUTPARAMETERAVAILABILITY = 0xb8L,
DBPROP_OWNINSERT = 0x59L,
DBPROP_OWNUPDATEDELETE = 0x5aL,
DBPROP_PERSISTENTIDTYPE = 0xb9L,
DBPROP_PREPAREABORTBEHAVIOR = 0x5bL,
DBPROP_PREPARECOMMITBEHAVIOR = 0x5cL,
DBPROP_PROCEDURETERM = 0x5dL,
DBPROP_PROVIDERNAME = 0x60L,
DBPROP_PROVIDEROLEDBVER = 0x61L,
DBPROP_PROVIDERVER = 0x62L,
DBPROP_QUICKRESTART = 0x63L,
DBPROP_QUOTEDIDENTIFIERCASE = 0x64L,
DBPROP_REENTRANTEVENTS = 0x65L,
DBPROP_REMOVEDELETED = 0x66L,
DBPROP_REPORTMULTIPLECHANGES = 0x67L,
DBPROP_RETURNPENDINGINSERTS = 0xbdL,
DBPROP_ROWRESTRICT = 0x68L,
DBPROP_ROWSETCONVERSIONSONCOMMAND = 0xc0L,
DBPROP_ROWTHREADMODEL = 0x69L,
DBPROP_SCHEMATERM = 0x6aL,
DBPROP_SCHEMAUSAGE = 0x6bL,
DBPROP_SERVERCURSOR = 0x6cL,
DBPROP_SESS_AUTOCOMMITISOLEVELS = 0xbeL,
DBPROP_SQLSUPPORT = 0x6dL,
DBPROP_STRONGIDENTITY = 0x77L,
DBPROP_STRUCTUREDSTORAGE = 0x6fL,
DBPROP_SUBQUERIES = 0x70L,
DBPROP_SUPPORTEDTXNDDL = 0xa1L,
DBPROP_SUPPORTEDTXNISOLEVELS = 0x71L,
DBPROP_SUPPORTEDTXNISORETAIN = 0x72L,
DBPROP_TABLETERM = 0x73L,
DBPROP_TBL_TEMPTABLE = 0x8cL,
DBPROP_TRANSACTEDOBJECT = 0x74L,
DBPROP_UPDATABILITY = 0x75L,
DBPROP_USERNAME = 0x76L
};
enum DBPROPENUM15
{ DBPROP_FILTEROPS = 0xd0L,
DBPROP_FILTERCOMPAREOPS = 0xd1L,
DBPROP_FINDCOMPAREOPS = 0xd2L,
DBPROP_IChapteredRowset = 0xcaL,
DBPROP_IDBAsynchStatus = 0xcbL,
DBPROP_IRowsetFind = 0xccL,
DBPROP_IRowsetView = 0xd4L,
DBPROP_IViewChapter = 0xd5L,
DBPROP_IViewFilter = 0xd6L,
DBPROP_IViewRowset = 0xd7L,
DBPROP_IViewSort = 0xd8L,
DBPROP_INIT_ASYNCH = 0xc8L,
DBPROP_MAXOPENCHAPTERS = 0xc7L,
DBPROP_MAXORSINFILTER = 0xcdL,
DBPROP_MAXSORTCOLUMNS = 0xceL,
DBPROP_ROWSET_ASYNCH = 0xc9L,
DBPROP_SORTONINDEX = 0xcfL
};
#define DBPROP_PROVIDERFILENAME DBPROP_PROVIDERNAME
#define DBPROP_SERVER_NAME DBPROP_SERVERNAME
enum DBPROPENUM20
{ DBPROP_IMultipleResults = 0xd9L,
DBPROP_DATASOURCE_TYPE = 0xfbL,
MDPROP_AXES = 0xfcL,
MDPROP_FLATTENING_SUPPORT = 0xfdL,
MDPROP_MDX_JOINCUBES = 0xfeL,
MDPROP_NAMED_LEVELS = 0xffL,
MDPROP_RANGEROWSET = 0x100L,
MDPROP_MDX_SLICER = 0xdaL,
MDPROP_MDX_CUBEQUALIFICATION = 0xdbL,
MDPROP_MDX_OUTERREFERENCE = 0xdcL,
MDPROP_MDX_QUERYBYPROPERTY = 0xddL,
MDPROP_MDX_CASESUPPORT = 0xdeL,
MDPROP_MDX_STRING_COMPOP = 0xe0L,
MDPROP_MDX_DESCFLAGS = 0xe1L,
MDPROP_MDX_SET_FUNCTIONS = 0xe2L,
MDPROP_MDX_MEMBER_FUNCTIONS = 0xe3L,
MDPROP_MDX_NUMERIC_FUNCTIONS = 0xe4L,
MDPROP_MDX_FORMULAS = 0xe5L,
MDPROP_MDX_AGGREGATECELL_UPDATE = 0xe6L,
MDPROP_MDX_OBJQUALIFICATION = 0x105L,
MDPROP_MDX_NONMEASURE_EXPRESSONS = 0x106L,
DBPROP_ACCESSORDER = 0xe7L,
DBPROP_BOOKMARKINFO = 0xe8L,
DBPROP_INIT_CATALOG = 0xe9L,
DBPROP_ROW_BULKOPS = 0xeaL,
DBPROP_PROVIDERFRIENDLYNAME = 0xebL,
DBPROP_LOCKMODE = 0xecL,
DBPROP_MULTIPLECONNECTIONS = 0xedL,
DBPROP_UNIQUEROWS = 0xeeL,
DBPROP_SERVERDATAONINSERT = 0xefL,
DBPROP_STORAGEFLAGS = 0xf0L,
DBPROP_CONNECTIONSTATUS = 0xf4L,
DBPROP_ALTERCOLUMN = 0xf5L,
DBPROP_COLUMNLCID = 0xf6L,
DBPROP_RESETDATASOURCE = 0xf7L,
DBPROP_INIT_OLEDBSERVICES = 0xf8L,
DBPROP_IRowsetRefresh = 0xf9L,
DBPROP_SERVERNAME = 0xfaL,
DBPROP_IParentRowset = 0x101L,
DBPROP_HIDDENCOLUMNS = 0x102L,
DBPROP_PROVIDERMEMORY = 0x103L,
DBPROP_CLIENTCURSOR = 0x104L
};
enum DBPROPENUM21
{ DBPROP_TRUSTEE_USERNAME = 0xf1L,
DBPROP_TRUSTEE_AUTHENTICATION = 0xf2L,
DBPROP_TRUSTEE_NEWAUTHENTICATION = 0xf3L,
DBPROP_IRow = 0x107L,
DBPROP_IRowChange = 0x108L,
DBPROP_IRowSchemaChange = 0x109L,
DBPROP_IGetRow = 0x10aL,
DBPROP_IScopedOperations = 0x10bL,
DBPROP_IBindResource = 0x10cL,
DBPROP_ICreateRow = 0x10dL,
DBPROP_INIT_BINDFLAGS = 0x10eL,
DBPROP_INIT_LOCKOWNER = 0x10fL,
DBPROP_GENERATEURL = 0x111L,
DBPROP_IDBBinderProperties = 0x112L,
DBPROP_IColumnsInfo2 = 0x113L,
DBPROP_IRegisterProvider = 0x114L,
DBPROP_IGetSession = 0x115L,
DBPROP_IGetSourceRow = 0x116L,
DBPROP_IRowsetCurrentIndex = 0x117L,
DBPROP_OPENROWSETSUPPORT = 0x118L,
DBPROP_COL_ISLONG = 0x119L
};
//@@@+ deprecated
#ifdef deprecated
enum DBPROPENUMDEPRECATED
{ DBPROP_IRowsetExactScroll = 0x9aL
};
#endif // deprecated
//@@@- deprecated
#define DBPROPVAL_BMK_NUMERIC 0x00000001L
#define DBPROPVAL_BMK_KEY 0x00000002L
#define DBPROPVAL_CL_START 0x00000001L
#define DBPROPVAL_CL_END 0x00000002L
#define DBPROPVAL_CU_DML_STATEMENTS 0x00000001L
#define DBPROPVAL_CU_TABLE_DEFINITION 0x00000002L
#define DBPROPVAL_CU_INDEX_DEFINITION 0x00000004L
#define DBPROPVAL_CU_PRIVILEGE_DEFINITION 0x00000008L
#define DBPROPVAL_CD_NOTNULL 0x00000001L
#define DBPROPVAL_CB_NULL 0x00000001L
#define DBPROPVAL_CB_NON_NULL 0x00000002L
#define DBPROPVAL_FU_NOT_SUPPORTED 0x00000001L
#define DBPROPVAL_FU_COLUMN 0x00000002L
#define DBPROPVAL_FU_TABLE 0x00000004L
#define DBPROPVAL_FU_CATALOG 0x00000008L
#define DBPROPVAL_GB_NOT_SUPPORTED 0x00000001L
#define DBPROPVAL_GB_EQUALS_SELECT 0x00000002L
#define DBPROPVAL_GB_CONTAINS_SELECT 0x00000004L
#define DBPROPVAL_GB_NO_RELATION 0x00000008L
#define DBPROPVAL_HT_DIFFERENT_CATALOGS 0x00000001L
#define DBPROPVAL_HT_DIFFERENT_PROVIDERS 0x00000002L
#define DBPROPVAL_IC_UPPER 0x00000001L
#define DBPROPVAL_IC_LOWER 0x00000002L
#define DBPROPVAL_IC_SENSITIVE 0x00000004L
#define DBPROPVAL_IC_MIXED 0x00000008L
//@@@+ deprecated
#ifdef deprecated
#define DBPROPVAL_LM_NONE 0x00000001L
#define DBPROPVAL_LM_READ 0x00000002L
#define DBPROPVAL_LM_INTENT 0x00000004L
#define DBPROPVAL_LM_RITE 0x00000008L
#endif // deprecated
//@@@- deprecated
#define DBPROPVAL_NP_OKTODO 0x00000001L
#define DBPROPVAL_NP_ABOUTTODO 0x00000002L
#define DBPROPVAL_NP_SYNCHAFTER 0x00000004L
#define DBPROPVAL_NP_FAILEDTODO 0x00000008L
#define DBPROPVAL_NP_DIDEVENT 0x00000010L
#define DBPROPVAL_NC_END 0x00000001L
#define DBPROPVAL_NC_HIGH 0x00000002L
#define DBPROPVAL_NC_LOW 0x00000004L
#define DBPROPVAL_NC_START 0x00000008L
#define DBPROPVAL_OO_BLOB 0x00000001L
#define DBPROPVAL_OO_IPERSIST 0x00000002L
#define DBPROPVAL_CB_DELETE 0x00000001L
#define DBPROPVAL_CB_PRESERVE 0x00000002L
#define DBPROPVAL_SU_DML_STATEMENTS 0x00000001L
#define DBPROPVAL_SU_TABLE_DEFINITION 0x00000002L
#define DBPROPVAL_SU_INDEX_DEFINITION 0x00000004L
#define DBPROPVAL_SU_PRIVILEGE_DEFINITION 0x00000008L
#define DBPROPVAL_SQ_CORRELATEDSUBQUERIES 0x00000001L
#define DBPROPVAL_SQ_COMPARISON 0x00000002L
#define DBPROPVAL_SQ_EXISTS 0x00000004L
#define DBPROPVAL_SQ_IN 0x00000008L
#define DBPROPVAL_SQ_QUANTIFIED 0x00000010L
#define DBPROPVAL_SQ_TABLE 0x00000020L
#define DBPROPVAL_SS_ISEQUENTIALSTREAM 0x00000001L
#define DBPROPVAL_SS_ISTREAM 0x00000002L
#define DBPROPVAL_SS_ISTORAGE 0x00000004L
#define DBPROPVAL_SS_ILOCKBYTES 0x00000008L
#define DBPROPVAL_TI_CHAOS 0x00000010L
#define DBPROPVAL_TI_READUNCOMMITTED 0x00000100L
#define DBPROPVAL_TI_BROWSE 0x00000100L
#define DBPROPVAL_TI_CURSORSTABILITY 0x00001000L
#define DBPROPVAL_TI_READCOMMITTED 0x00001000L
#define DBPROPVAL_TI_REPEATABLEREAD 0x00010000L
#define DBPROPVAL_TI_SERIALIZABLE 0x00100000L
#define DBPROPVAL_TI_ISOLATED 0x00100000L
#define DBPROPVAL_TR_COMMIT_DC 0x00000001L
#define DBPROPVAL_TR_COMMIT 0x00000002L
#define DBPROPVAL_TR_COMMIT_NO 0x00000004L
#define DBPROPVAL_TR_ABORT_DC 0x00000008L
#define DBPROPVAL_TR_ABORT 0x00000010L
#define DBPROPVAL_TR_ABORT_NO 0x00000020L
#define DBPROPVAL_TR_DONTCARE 0x00000040L
#define DBPROPVAL_TR_BOTH 0x00000080L
#define DBPROPVAL_TR_NONE 0x00000100L
#define DBPROPVAL_TR_OPTIMISTIC 0x00000200L
#define DBPROPVAL_RT_FREETHREAD 0x00000001L
#define DBPROPVAL_RT_APTMTTHREAD 0x00000002L
#define DBPROPVAL_RT_SINGLETHREAD 0x00000004L
#define DBPROPVAL_UP_CHANGE 0x00000001L
#define DBPROPVAL_UP_DELETE 0x00000002L
#define DBPROPVAL_UP_INSERT 0x00000004L
#define DBPROPVAL_SQL_NONE 0x00000000L
#define DBPROPVAL_SQL_ODBC_MINIMUM 0x00000001L
#define DBPROPVAL_SQL_ODBC_CORE 0x00000002L
#define DBPROPVAL_SQL_ODBC_EXTENDED 0x00000004L
#define DBPROPVAL_SQL_ANSI89_IEF 0x00000008L
#define DBPROPVAL_SQL_ANSI92_ENTRY 0x00000010L
#define DBPROPVAL_SQL_FIPS_TRANSITIONAL 0x00000020L
#define DBPROPVAL_SQL_ANSI92_INTERMEDIATE 0x00000040L
#define DBPROPVAL_SQL_ANSI92_FULL 0x00000080L
#define DBPROPVAL_SQL_ESCAPECLAUSES 0x00000100L
#define DBPROPVAL_IT_BTREE 0x00000001L
#define DBPROPVAL_IT_HASH 0x00000002L
#define DBPROPVAL_IT_CONTENT 0x00000003L
#define DBPROPVAL_IT_OTHER 0x00000004L
#define DBPROPVAL_IN_DISALLOWNULL 0x00000001L
#define DBPROPVAL_IN_IGNORENULL 0x00000002L
#define DBPROPVAL_IN_IGNOREANYNULL 0x00000004L
#define DBPROPVAL_TC_NONE 0x00000000L
#define DBPROPVAL_TC_DML 0x00000001L
#define DBPROPVAL_TC_DDL_COMMIT 0x00000002L
#define DBPROPVAL_TC_DDL_IGNORE 0x00000004L
#define DBPROPVAL_TC_ALL 0x00000008L
#define DBPROPVAL_NP_OKTODO 0x00000001L
#define DBPROPVAL_NP_ABOUTTODO 0x00000002L
#define DBPROPVAL_NP_SYNCHAFTER 0x00000004L
#define DBPROPVAL_OA_NOTSUPPORTED 0x00000001L
#define DBPROPVAL_OA_ATEXECUTE 0x00000002L
#define DBPROPVAL_OA_ATROWRELEASE 0x00000004L
#define DBPROPVAL_MR_NOTSUPPORTED 0x00000000L
#define DBPROPVAL_MR_SUPPORTED 0x00000001L
#define DBPROPVAL_MR_CONCURRENT 0x00000002L
#define DBPROPVAL_PT_GUID_NAME 0x00000001L
#define DBPROPVAL_PT_GUID_PROPID 0x00000002L
#define DBPROPVAL_PT_NAME 0x00000004L
#define DBPROPVAL_PT_GUID 0x00000008L
#define DBPROPVAL_PT_PROPID 0x00000010L
#define DBPROPVAL_PT_PGUID_NAME 0x00000020L
#define DBPROPVAL_PT_PGUID_PROPID 0x00000040L
#define DBPROPVAL_NT_SINGLEROW 0x00000001L
#define DBPROPVAL_NT_MULTIPLEROWS 0x00000002L
#define DBPROPVAL_ASYNCH_INITIALIZE 0x00000001L
#define DBPROPVAL_ASYNCH_SEQUENTIALPOPULATION 0x00000002L
#define DBPROPVAL_ASYNCH_RANDOMPOPULATION 0x00000004L
#define DBPROPVAL_OP_EQUAL 0x00000001L
#define DBPROPVAL_OP_RELATIVE 0x00000002L
#define DBPROPVAL_OP_STRING 0x00000004L
#define DBPROPVAL_CO_EQUALITY 0x00000001L
#define DBPROPVAL_CO_STRING 0x00000002L
#define DBPROPVAL_CO_CASESENSITIVE 0x00000004L
#define DBPROPVAL_CO_CASEINSENSITIVE 0x00000008L
#define DBPROPVAL_CO_CONTAINS 0x00000010L
#define DBPROPVAL_CO_BEGINSWITH 0x00000020L
#define DBPROPVAL_ASYNCH_BACKGROUNDPOPULATION 0x00000008L
#define DBPROPVAL_ASYNCH_PREPOPULATE 0x00000010L
#define DBPROPVAL_ASYNCH_POPULATEONDEMAND 0x00000020L
#define DBPROPVAL_LM_NONE 0x00000001L
#define DBPROPVAL_LM_SINGLEROW 0x00000002L
#define DBPROPVAL_SQL_SUBMINIMUM 0x00000200L
#define DBPROPVAL_DST_TDP 0x00000001L
#define DBPROPVAL_DST_MDP 0x00000002L
#define DBPROPVAL_DST_TDPANDMDP 0x00000003L
#define MDPROPVAL_AU_UNSUPPORTED 0x00000000L
#define MDPROPVAL_AU_UNCHANGED 0x00000001L
#define MDPROPVAL_AU_UNKNOWN 0x00000002L
#define MDPROPVAL_MF_WITH_CALCMEMBERS 0x00000001L
#define MDPROPVAL_MF_WITH_NAMEDSETS 0x00000002L
#define MDPROPVAL_MF_CREATE_CALCMEMBERS 0x00000004L
#define MDPROPVAL_MF_CREATE_NAMEDSETS 0x00000008L
#define MDPROPVAL_MF_SCOPE_SESSION 0x00000010L
#define MDPROPVAL_MF_SCOPE_GLOBAL 0x00000020L
#define MDPROPVAL_MMF_COUSIN 0x00000001L
#define MDPROPVAL_MMF_PARALLELPERIOD 0x00000002L
#define MDPROPVAL_MMF_OPENINGPERIOD 0x00000004L
#define MDPROPVAL_MMF_CLOSINGPERIOD 0x00000008L
#define MDPROPVAL_MNF_MEDIAN 0x00000001L
#define MDPROPVAL_MNF_VAR 0x00000002L
#define MDPROPVAL_MNF_STDDEV 0x00000004L
#define MDPROPVAL_MNF_RANK 0x00000008L
#define MDPROPVAL_MNF_AGGREGATE 0x00000010L
#define MDPROPVAL_MNF_COVARIANCE 0x00000020L
#define MDPROPVAL_MNF_CORRELATION 0x00000040L
#define MDPROPVAL_MNF_LINREGSLOPE 0x00000080L
#define MDPROPVAL_MNF_LINREGVARIANCE 0x00000100L
#define MDPROPVAL_MNF_LINREG2 0x00000200L
#define MDPROPVAL_MNF_LINREGPOINT 0x00000400L
#define MDPROPVAL_MNF_DRILLDOWNLEVEL 0x00000800L
#define MDPROPVAL_MNF_DRILLDOWNMEMBERTOP 0x00001000L
#define MDPROPVAL_MNF_DRILLDOWNMEMBERBOTTOM 0x00002000L
#define MDPROPVAL_MNF_DRILLDOWNLEVELTOP 0x00004000L
#define MDPROPVAL_MNF_DRILLDOWNLEVELBOTTOM 0x00008000L
#define MDPROPVAL_MNF_DRILLUPMEMBER 0x00010000L
#define MDPROPVAL_MNF_DRILLUPLEVEL 0x00020000L
#define MDPROPVAL_MMF_COUSIN 0x00000001L
#define MDPROPVAL_MMF_PARALLELPERIOD 0x00000002L
#define MDPROPVAL_MMF_OPENINGPERIOD 0x00000004L
#define MDPROPVAL_MMF_CLOSINGPERIOD 0x00000008L
#define MDPROPVAL_MSF_TOPPERCENT 0x00000001L
#define MDPROPVAL_MSF_BOTTOMPERCENT 0x00000002L
#define MDPROPVAL_MSF_TOPSUM 0x00000004L
#define MDPROPVAL_MSF_BOTTOMSUM 0x00000008L
#define MDPROPVAL_MSF_PERIODSTODATE 0x00000010L
#define MDPROPVAL_MSF_LASTPERIODS 0x00000020L
#define MDPROPVAL_MSF_YTD 0x00000040L
#define MDPROPVAL_MSF_QTD 0x00000080L
#define MDPROPVAL_MSF_MTD 0x00000100L
#define MDPROPVAL_MSF_WTD 0x00000200L
#define MDPROPVAL_MSF_DRILLDOWNMEMBBER 0x00000400L
#define MDPROPVAL_MSF_DRILLDOWNLEVEL 0x00000800L
#define MDPROPVAL_MSF_DRILLDOWNMEMBERTOP 0x00001000L
#define MDPROPVAL_MSF_DRILLDOWNMEMBERBOTTOM 0x00002000L
#define MDPROPVAL_MSF_DRILLDOWNLEVELTOP 0x00004000L
#define MDPROPVAL_MSF_DRILLDOWNLEVELBOTTOM 0x00008000L
#define MDPROPVAL_MSF_DRILLUPMEMBER 0x00010000L
#define MDPROPVAL_MSF_DRILLUPLEVEL 0x00020000L
#define MDPROPVAL_MSF_TOGGLEDRILLSTATE 0x00040000L
// values for MDPROP_MDX_DESCFLAGS
#define MDPROPVAL_MD_SELF 0x00000001L
#define MDPROPVAL_MD_BEFORE 0x00000002L
#define MDPROPVAL_MD_AFTER 0x00000004L
// values for MDPROP_MDX_STRING_COMPOP
#define MDPROPVAL_MSC_LESSTHAN 0x00000001L
#define MDPROPVAL_MSC_GREATERTHAN 0x00000002L
#define MDPROPVAL_MSC_LESSTHANEQUAL 0x00000004L
#define MDPROPVAL_MSC_GREATERTHANEQUAL 0x00000008L
#define MDPROPVAL_MC_SINGLECASE 0x00000001L
#define MDPROPVAL_MC_SEARCHEDCASE 0x00000002L
#define MDPROPVAL_MOQ_OUTERREFERENCE 0x00000001L
#define MDPROPVAL_MOQ_DATASOURCE_CUBE 0x00000001L
#define MDPROPVAL_MOQ_CATALOG_CUBE 0x00000002L
#define MDPROPVAL_MOQ_SCHEMA_CUBE 0x00000004L
#define MDPROPVAL_MOQ_CUBE_DIM 0x00000008L
#define MDPROPVAL_MOQ_DIM_HIER 0x00000010L
#define MDPROPVAL_MOQ_DIMHIER_LEVEL 0x00000020L
#define MDPROPVAL_MOQ_LEVEL_MEMBER 0x00000040L
#define MDPROPVAL_MOQ_MEMBER_MEMBER 0x00000080L
#define MDPROPVAL_FS_FULL_SUPPORT 0x00000001L
#define MDPROPVAL_FS_GENERATED_COLUMN 0x00000002L
#define MDPROPVAL_FS_GENERATED_DIMENSION 0x00000003L
#define MDPROPVAL_FS_NO_SUPPORT 0x00000004L
#define MDPROPVAL_NL_NAMEDLEVELS 0x00000001L
#define MDPROPVAL_NL_NUMBEREDLEVELS 0x00000002L
#define MDPROPVAL_MJC_SINGLECUBE 0x00000001L
#define MDPROPVAL_MJC_MULTICUBES 0x00000002L
#define MDPROPVAL_MJC_IMPLICITCUBE 0x00000004L
#define MDPROPVAL_RR_NORANGEROWSET 0x00000001L
#define MDPROPVAL_RR_READONLY 0x00000002L
#define MDPROPVAL_RR_UPDATE 0x00000004L
#define MDPROPVAL_MS_MULTIPLETUPLES 0x00000001L
#define MDPROPVAL_MS_SINGLETUPLE 0x00000002L
#define DBPROPVAL_AO_SEQUENTIAL 0x00000000L
#define DBPROPVAL_AO_SEQUENTIALSTORAGEOBJECTS 0x00000001L
#define DBPROPVAL_AO_RANDOM 0x00000002L
#define DBPROPVAL_BD_ROWSET 0x00000000L
#define DBPROPVAL_BD_INTRANSACTION 0x00000001L
#define DBPROPVAL_BD_XTRANSACTION 0x00000002L
#define DBPROPVAL_BD_REORGANIZATION 0x00000003L
#define BMK_DURABILITY_ROWSET DBPROPVAL_BD_ROWSET
#define BMK_DURABILITY_INTRANSACTION DBPROPVAL_BD_INTRANSACTION
#define BMK_DURABILITY_XTRANSACTION DBPROPVAL_BD_XTRANSACTION
#define BMK_DURABILITY_REORGANIZATION DBPROPVAL_BD_REORGANIZATION
#define DBPROPVAL_BO_NOLOG 0x00000000L
#define DBPROPVAL_BO_NOINDEXUPDATE 0x00000001L
#define DBPROPVAL_BO_REFINTEGRITY 0x00000002L
#if !defined(_WINBASE_)
#define OF_READ 0x00000000
#define OF_WRITE 0x00000001
#define OF_READWRITE 0x00000002
#define OF_SHARE_COMPAT 0x00000000
#define OF_SHARE_EXCLUSIVE 0x00000010
#define OF_SHARE_DENY_WRITE 0x00000020
#define OF_SHARE_DENY_READ 0x00000030
#define OF_SHARE_DENY_NONE 0x00000040
#define OF_PARSE 0x00000100
#define OF_DELETE 0x00000200
#define OF_VERIFY 0x00000400
#define OF_CANCEL 0x00000800
#define OF_CREATE 0x00001000
#define OF_PROMPT 0x00002000
#define OF_EXIST 0x00004000
#define OF_REOPEN 0x00008000
#endif // !_WINBASE_
#define DBPROPVAL_STGM_READ OF_READ
#define DBPROPVAL_STGM_WRITE OF_WRITE
#define DBPROPVAL_STGM_READWRITE OF_READWRITE
#define DBPROPVAL_STGM_SHARE_DENY_NONE OF_SHARE_DENY_NONE
#define DBPROPVAL_STGM_SHARE_DENY_READ OF_SHARE_DENY_READ
#define DBPROPVAL_STGM_SHARE_DENY_WRITE OF_SHARE_DENY_WRITE
#define DBPROPVAL_STGM_SHARE_EXCLUSIVE OF_SHARE_EXCLUSIVE
#define DBPROPVAL_STGM_DIRECT 0x00010000
#define DBPROPVAL_STGM_TRANSACTED 0x00020000
#define DBPROPVAL_STGM_CREATE OF_CREATE
#define DBPROPVAL_STGM_CONVERT 0x00040000
#define DBPROPVAL_STGM_FAILIFTHERE 0x00080000
#define DBPROPVAL_STGM_PRIORITY 0x00100000
#define DBPROPVAL_STGM_DELETEONRELEASE 0x00200000
#define DBPROPVAL_GB_COLLATE 0x00000010L
#define DBPROPVAL_CS_UNINITIALIZED 0x00000000L
#define DBPROPVAL_CS_INITIALIZED 0x00000001L
#define DBPROPVAL_CS_COMMUNICATIONFAILURE 0x00000002L
#define DBPROPVAL_RD_RESETALL 0xffffffffL
#define DBPROPVAL_OS_RESOURCEPOOLING 0x00000001L
#define DBPROPVAL_OS_TXNENLISTMENT 0x00000002L
#define DBPROPVAL_OS_CLIENTCURSOR 0x00000004L
#define DBPROPVAL_OS_ENABLEALL 0xffffffffL
#define DBPROPVAL_BI_CROSSROWSET 0x00000001L
#define MDPROPVAL_NL_SCHEMAONLY 0x00000004L
#define DBPROPVAL_OS_DISABLEALL 0x00000000L
#define DBPROPVAL_OO_ROWOBJECT 0x00000004L
#define DBPROPVAL_OO_SCOPED 0x00000008L
#define DBPROPVAL_OO_DIRECTBIND 0x00000010L
#define DBPROPVAL_DST_DOCSOURCE 0x00000004L
#define DBPROPVAL_GU_NOTSUPPORTED 0x00000001L
#define DBPROPVAL_GU_SUFFIX 0x00000002L
#define DB_BINDFLAGS_DELAYFETCHCOLUMNS 0x00000001L
#define DB_BINDFLAGS_DELAYFETCHSTREAM 0x00000002L
#define DB_BINDFLAGS_RECURSIVE 0x00000004L
#define DB_BINDFLAGS_OUTPUT 0x00000008L
#define DB_BINDFLAGS_COLLECTION 0x00000010L
#define DB_BINDFLAGS_OPENIFEXISTS 0x00000020L
#define DB_BINDFLAGS_OVERWRITE 0x00000040L
#define DB_BINDFLAGS_ISSTRUCTUREDDOCUMENT 0x00000080L
#define DBPROPVAL_ORS_TABLE 0x00000000L
#define DBPROPVAL_ORS_INDEX 0x00000001L
#define DBPROPVAL_ORS_INTEGRATEDINDEX 0x00000002L
#define DBPROPVAL_TC_DDL_LOCK 0x00000010L
#define DBPROPVAL_ORS_STOREDPROC 0x00000004L
#define DBPROPVAL_IN_ALLOWNULL 0x00000000L
#define DB_IMP_LEVEL_ANONYMOUS 0x00
#define DB_IMP_LEVEL_IDENTIFY 0x01
#define DB_IMP_LEVEL_IMPERSONATE 0x02
#define DB_IMP_LEVEL_DELEGATE 0x03
#define DBPROMPT_PROMPT 0x01
#define DBPROMPT_COMPLETE 0x02
#define DBPROMPT_COMPLETEREQUIRED 0x03
#define DBPROMPT_NOPROMPT 0x04
#define DB_PROT_LEVEL_NONE 0x00
#define DB_PROT_LEVEL_CONNECT 0x01
#define DB_PROT_LEVEL_CALL 0x02
#define DB_PROT_LEVEL_PKT 0x03
#define DB_PROT_LEVEL_PKT_INTEGRITY 0x04
#define DB_PROT_LEVEL_PKT_PRIVACY 0x05
#define DB_MODE_READ 0x01
#define DB_MODE_WRITE 0x02
#define DB_MODE_READWRITE 0x03
#define DB_MODE_SHARE_DENY_READ 0x04
#define DB_MODE_SHARE_DENY_WRITE 0x08
#define DB_MODE_SHARE_EXCLUSIVE 0x0c
#define DB_MODE_SHARE_DENY_NONE 0x10
#define DBCOMPUTEMODE_COMPUTED 0x01
#define DBCOMPUTEMODE_DYNAMIC 0x02
#define DBCOMPUTEMODE_NOTCOMPUTED 0x03
#define DBPROPVAL_DF_INITIALLY_DEFERRED 0x01
#define DBPROPVAL_DF_INITIALLY_IMMEDIATE 0x02
#define DBPROPVAL_DF_NOT_DEFERRABLE 0x03
typedef struct tagDBPARAMS
{
void __RPC_FAR *pData;
ULONG cParamSets;
HACCESSOR hAccessor;
} DBPARAMS;
typedef DWORD DBPARAMFLAGS;
enum DBPARAMFLAGSENUM
{ DBPARAMFLAGS_ISINPUT = 0x1,
DBPARAMFLAGS_ISOUTPUT = 0x2,
DBPARAMFLAGS_ISSIGNED = 0x10,
DBPARAMFLAGS_ISNULLABLE = 0x40,
DBPARAMFLAGS_ISLONG = 0x80
};
enum DBPARAMFLAGSENUM20
{ DBPARAMFLAGS_SCALEISNEGATIVE = 0x100
};
typedef struct tagDBPARAMINFO
{
DBPARAMFLAGS dwFlags;
ULONG iOrdinal;
LPOLESTR pwszName;
ITypeInfo __RPC_FAR *pTypeInfo;
ULONG ulParamSize;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
} DBPARAMINFO;
typedef DWORD DBPROPID;
typedef struct tagDBPROPIDSET
{
/* [size_is] */ DBPROPID __RPC_FAR *rgPropertyIDs;
ULONG cPropertyIDs;
GUID guidPropertySet;
} DBPROPIDSET;
typedef DWORD DBPROPFLAGS;
enum DBPROPFLAGSENUM
{ DBPROPFLAGS_NOTSUPPORTED = 0,
DBPROPFLAGS_COLUMN = 0x1,
DBPROPFLAGS_DATASOURCE = 0x2,
DBPROPFLAGS_DATASOURCECREATE = 0x4,
DBPROPFLAGS_DATASOURCEINFO = 0x8,
DBPROPFLAGS_DBINIT = 0x10,
DBPROPFLAGS_INDEX = 0x20,
DBPROPFLAGS_ROWSET = 0x40,
DBPROPFLAGS_TABLE = 0x80,
DBPROPFLAGS_COLUMNOK = 0x100,
DBPROPFLAGS_READ = 0x200,
DBPROPFLAGS_WRITE = 0x400,
DBPROPFLAGS_REQUIRED = 0x800,
DBPROPFLAGS_SESSION = 0x1000
};
enum DBPROPFLAGSENUM21
{ DBPROPFLAGS_TRUSTEE = 0x2000
};
#if defined(MIPSII_FP) || defined(MIPSIV) || defined(MIPSIV_FP)
#pragma pack(push,8)
#endif
typedef struct tagDBPROPINFO
{
LPOLESTR pwszDescription;
DBPROPID dwPropertyID;
DBPROPFLAGS dwFlags;
VARTYPE vtType;
VARIANT vValues;
} DBPROPINFO;
#if defined(MIPSII_FP) || defined(MIPSIV) || defined(MIPSIV_FP)
#pragma pack(pop)
#endif
#if 0
//DBPROPINFO is an unaligned structure. MIDL workaround. 42212352
typedef DBPROPINFO __RPC_FAR *PDBPROPINFO;
#else
typedef DBPROPINFO UNALIGNED __RPC_FAR * PDBPROPINFO;
#endif
typedef struct tagDBPROPINFOSET
{
/* [size_is] */ PDBPROPINFO rgPropertyInfos;
ULONG cPropertyInfos;
GUID guidPropertySet;
} DBPROPINFOSET;
typedef DWORD DBPROPOPTIONS;
// DBPROPOPTIONS_SETIFCHEAP is deprecated; use DBPROPOPTIONS_OPTIONAL instead.
enum DBPROPOPTIONSENUM
{ DBPROPOPTIONS_REQUIRED = 0,
DBPROPOPTIONS_SETIFCHEAP = 0x1,
DBPROPOPTIONS_OPTIONAL = 0x1
};
typedef DWORD DBPROPSTATUS;
enum DBPROPSTATUSENUM
{ DBPROPSTATUS_OK = 0,
DBPROPSTATUS_NOTSUPPORTED = 1,
DBPROPSTATUS_BADVALUE = 2,
DBPROPSTATUS_BADOPTION = 3,
DBPROPSTATUS_BADCOLUMN = 4,
DBPROPSTATUS_NOTALLSETTABLE = 5,
DBPROPSTATUS_NOTSETTABLE = 6,
DBPROPSTATUS_NOTSET = 7,
DBPROPSTATUS_CONFLICTING = 8
};
enum DBPROPSTATUSENUM21
{ DBPROPSTATUS_NOTAVAILABLE = 9
};
#if defined(MIPSII_FP) || defined(MIPSIV) || defined(MIPSIV_FP)
#pragma pack(push,8)
#endif
typedef struct tagDBPROP
{
DBPROPID dwPropertyID;
DBPROPOPTIONS dwOptions;
DBPROPSTATUS dwStatus;
DBID colid;
VARIANT vValue;
} DBPROP;
#if defined(MIPSII_FP) || defined(MIPSIV) || defined(MIPSIV_FP)
#pragma pack(pop)
#endif
typedef struct tagDBPROPSET
{
/* [size_is] */ DBPROP __RPC_FAR *rgProperties;
ULONG cProperties;
GUID guidPropertySet;
} DBPROPSET;
#define DBPARAMTYPE_INPUT 0x01
#define DBPARAMTYPE_INPUTOUTPUT 0x02
#define DBPARAMTYPE_OUTPUT 0x03
#define DBPARAMTYPE_RETURNVALUE 0x04
#define DB_PT_UNKNOWN 0x01
#define DB_PT_PROCEDURE 0x02
#define DB_PT_FUNCTION 0x03
#define DB_REMOTE 0x01
#define DB_LOCAL_SHARED 0x02
#define DB_LOCAL_EXCLUSIVE 0x03
#define DB_COLLATION_ASC 0x01
#define DB_COLLATION_DESC 0x02
#define DB_UNSEARCHABLE 0x01
#define DB_LIKE_ONLY 0x02
#define DB_ALL_EXCEPT_LIKE 0x03
#define DB_SEARCHABLE 0x04
#define MDTREEOP_CHILDREN 0x01
#define MDTREEOP_SIBLINGS 0x02
#define MDTREEOP_PARENT 0x04
#define MDTREEOP_SELF 0x08
#define MDTREEOP_DESCENDANTS 0x10
#define MDTREEOP_ANCESTORS 0x20
#define MD_DIMTYPE_UNKNOWN 0x00
#define MD_DIMTYPE_TIME 0x01
#define MD_DIMTYPE_MEASURE 0x02
#define MD_DIMTYPE_OTHER 0x03
#define MDLEVEL_TYPE_UNKNOWN 0x0000
#define MDLEVEL_TYPE_REGULAR 0x0000
#define MDLEVEL_TYPE_ALL 0x0001
#define MDLEVEL_TYPE_CALCULATED 0x0002
#define MDLEVEL_TYPE_TIME 0x0004
#define MDLEVEL_TYPE_RESERVED1 0x0008
#define MDLEVEL_TYPE_TIME_YEARS 0x0014
#define MDLEVEL_TYPE_TIME_HALF_YEAR 0x0024
#define MDLEVEL_TYPE_TIME_QUARTERS 0x0044
#define MDLEVEL_TYPE_TIME_MONTHS 0x0084
#define MDLEVEL_TYPE_TIME_WEEKS 0x0104
#define MDLEVEL_TYPE_TIME_DAYS 0x0204
#define MDLEVEL_TYPE_TIME_HOURS 0x0304
#define MDLEVEL_TYPE_TIME_MINUTES 0x0404
#define MDLEVEL_TYPE_TIME_SECONDS 0x0804
#define MDLEVEL_TYPE_TIME_UNDEFINED 0x1004
#define MDMEASURE_AGGR_UNKNOWN 0x00
#define MDMEASURE_AGGR_SUM 0x01
#define MDMEASURE_AGGR_COUNT 0x02
#define MDMEASURE_AGGR_MIN 0x03
#define MDMEASURE_AGGR_MAX 0x04
#define MDMEASURE_AGGR_AVG 0x05
#define MDMEASURE_AGGR_VAR 0x06
#define MDMEASURE_AGGR_STD 0x07
#define MDMEASURE_AGGR_CALCULATED 0x7f
#define MDPROP_MEMBER 0x01
#define MDPROP_CELL 0x02
#define MDMEMBER_TYPE_UNKNOWN 0x00
#define MDMEMBER_TYPE_REGULAR 0x01
#define MDMEMBER_TYPE_ALL 0x02
#define MDMEMBER_TYPE_MEASURE 0x03
#define MDMEMBER_TYPE_FORMULA 0x04
#define MDMEMBER_TYPE_RESERVE1 0x05
#define MDMEMBER_TYPE_RESERVE2 0x06
#define MDMEMBER_TYPE_RESERVE3 0x07
#define MDMEMBER_TYPE_RESERVE4 0x08
#define MDDISPINFO_DRILLED_DOWN 0x00010000
#define MDDISPINFO_PARENT_SAME_AS_PREV 0x00020000
typedef DWORD DBINDEX_COL_ORDER;
enum DBINDEX_COL_ORDERENUM
{ DBINDEX_COL_ORDER_ASC = 0,
DBINDEX_COL_ORDER_DESC = DBINDEX_COL_ORDER_ASC + 1
};
typedef struct tagDBINDEXCOLUMNDESC
{
DBID __RPC_FAR *pColumnID;
DBINDEX_COL_ORDER eIndexColOrder;
} DBINDEXCOLUMNDESC;
typedef struct tagDBCOLUMNDESC
{
LPOLESTR pwszTypeName;
ITypeInfo __RPC_FAR *pTypeInfo;
/* [size_is] */ DBPROPSET __RPC_FAR *rgPropertySets;
CLSID __RPC_FAR *pclsid;
ULONG cPropertySets;
ULONG ulColumnSize;
DBID dbcid;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
} DBCOLUMNDESC;
typedef struct tagDBCOLUMNACCESS
{
void __RPC_FAR *pData;
DBID columnid;
ULONG cbDataLen;
DBSTATUS dwStatus;
ULONG cbMaxLen;
DWORD dwReserved;
DBTYPE wType;
BYTE bPrecision;
BYTE bScale;
} DBCOLUMNACCESS;
typedef DWORD DBCOLUMNDESCFLAGS;
enum DBCOLUMNDESCFLAGSENUM
{ DBCOLUMNDESCFLAGS_TYPENAME = 0x1,
DBCOLUMNDESCFLAGS_ITYPEINFO = 0x2,
DBCOLUMNDESCFLAGS_PROPERTIES = 0x4,
DBCOLUMNDESCFLAGS_CLSID = 0x8,
DBCOLUMNDESCFLAGS_COLSIZE = 0x10,
DBCOLUMNDESCFLAGS_DBCID = 0x20,
DBCOLUMNDESCFLAGS_WTYPE = 0x40,
DBCOLUMNDESCFLAGS_PRECISION = 0x80,
DBCOLUMNDESCFLAGS_SCALE = 0x100
};
typedef DWORD DBEVENTPHASE;
enum DBEVENTPHASEENUM
{ DBEVENTPHASE_OKTODO = 0,
DBEVENTPHASE_ABOUTTODO = DBEVENTPHASE_OKTODO + 1,
DBEVENTPHASE_SYNCHAFTER = DBEVENTPHASE_ABOUTTODO + 1,
DBEVENTPHASE_FAILEDTODO = DBEVENTPHASE_SYNCHAFTER + 1,
DBEVENTPHASE_DIDEVENT = DBEVENTPHASE_FAILEDTODO + 1
};
typedef DWORD DBREASON;
enum DBREASONENUM
{ DBREASON_ROWSET_FETCHPOSITIONCHANGE = 0,
DBREASON_ROWSET_RELEASE = DBREASON_ROWSET_FETCHPOSITIONCHANGE + 1,
DBREASON_COLUMN_SET = DBREASON_ROWSET_RELEASE + 1,
DBREASON_COLUMN_RECALCULATED = DBREASON_COLUMN_SET + 1,
DBREASON_ROW_ACTIVATE = DBREASON_COLUMN_RECALCULATED + 1,
DBREASON_ROW_RELEASE = DBREASON_ROW_ACTIVATE + 1,
DBREASON_ROW_DELETE = DBREASON_ROW_RELEASE + 1,
DBREASON_ROW_FIRSTCHANGE = DBREASON_ROW_DELETE + 1,
DBREASON_ROW_INSERT = DBREASON_ROW_FIRSTCHANGE + 1,
DBREASON_ROW_RESYNCH = DBREASON_ROW_INSERT + 1,
DBREASON_ROW_UNDOCHANGE = DBREASON_ROW_RESYNCH + 1,
DBREASON_ROW_UNDOINSERT = DBREASON_ROW_UNDOCHANGE + 1,
DBREASON_ROW_UNDODELETE = DBREASON_ROW_UNDOINSERT + 1,
DBREASON_ROW_UPDATE = DBREASON_ROW_UNDODELETE + 1,
DBREASON_ROWSET_CHANGED = DBREASON_ROW_UPDATE + 1
};
enum DBREASONENUM15
{ DBREASON_ROWPOSITION_CHANGED = DBREASON_ROWSET_CHANGED + 1,
DBREASON_ROWPOSITION_CHAPTERCHANGED = DBREASON_ROWPOSITION_CHANGED + 1,
DBREASON_ROWPOSITION_CLEARED = DBREASON_ROWPOSITION_CHAPTERCHANGED + 1,
DBREASON_ROW_ASYNCHINSERT = DBREASON_ROWPOSITION_CLEARED + 1
};
typedef DWORD DBCOMPAREOP;
enum DBCOMPAREOPSENUM
{ DBCOMPAREOPS_LT = 0,
DBCOMPAREOPS_LE = 1,
DBCOMPAREOPS_EQ = 2,
DBCOMPAREOPS_GE = 3,
DBCOMPAREOPS_GT = 4,
DBCOMPAREOPS_BEGINSWITH = 5,
DBCOMPAREOPS_CONTAINS = 6,
DBCOMPAREOPS_NE = 7,
DBCOMPAREOPS_IGNORE = 8,
DBCOMPAREOPS_CASESENSITIVE = 0x1000,
DBCOMPAREOPS_CASEINSENSITIVE = 0x2000
};
enum DBCOMPAREOPSENUM20
{ DBCOMPAREOPS_NOTBEGINSWITH = 9,
DBCOMPAREOPS_NOTCONTAINS = 10
};
typedef DWORD DBASYNCHOP;
enum DBASYNCHOPENUM
{ DBASYNCHOP_OPEN = 0
};
typedef DWORD DBASYNCHPHASE;
enum DBASYNCHPHASEENUM
{ DBASYNCHPHASE_INITIALIZATION = 0,
DBASYNCHPHASE_POPULATION = DBASYNCHPHASE_INITIALIZATION + 1,
DBASYNCHPHASE_COMPLETE = DBASYNCHPHASE_POPULATION + 1,
DBASYNCHPHASE_CANCELED = DBASYNCHPHASE_COMPLETE + 1
};
#define DB_COUNTUNAVAILABLE -1
typedef DWORD DBSORT;
enum DBSORTENUM
{ DBSORT_ASCENDING = 0,
DBSORT_DESCENDING = DBSORT_ASCENDING + 1
};
typedef DWORD DBCOMMANDPERSISTFLAG;
enum DBCOMMANDPERSISTFLAGENUM
{ DBCOMMANDPERSISTFLAG_NOSAVE = 0x1
};
enum DBCOMMANDPERSISTFLAGENUM21
{ DBCOMMANDPERSISTFLAG_DEFAULT = 0,
DBCOMMANDPERSISTFLAG_PERSISTVIEW = 0x2,
DBCOMMANDPERSISTFLAG_PERSISTPROCEDURE = 0x4
};
typedef DWORD DBCONSTRAINTTYPE;
enum DBCONSTRAINTTYPEENUM
{ DBCONSTRAINTTYPE_UNIQUE = 0,
DBCONSTRAINTTYPE_FOREIGNKEY = 0x1,
DBCONSTRAINTTYPE_PRIMARYKEY = 0x2,
DBCONSTRAINTTYPE_CHECK = 0x3,
DBCONSTRAINTTYPE_SSCE_DEFAULT = 0x4
};
typedef DWORD DBUPDELRULE;
enum DBUPDELRULEENUM
{ DBUPDELRULE_NOACTION = 0,
DBUPDELRULE_CASCADE = 0x1,
DBUPDELRULE_SETNULL = 0x2,
DBUPDELRULE_SETDEFAULT = 0x3
};
typedef DWORD DBMATCHTYPE;
enum DBMATCHTYPEENUM
{ DBMATCHTYPE_FULL = 0,
DBMATCHTYPE_NONE = 0x1,
DBMATCHTYPE_PARTIAL = 0x2
};
typedef DWORD DBDEFERRABILITY;
enum DBDEFERRABILITYENUM
{ DBDEFERRABILITY_DEFERRED = 0x1,
DBDEFERRABILITY_DEFERRABLE = 0x2
};
typedef struct tagDBCONSTRAINTDESC
{
DBID __RPC_FAR *pConstraintID;
DBCONSTRAINTTYPE ConstraintType;
ULONG cColumns;
/* [size_is] */ DBID __RPC_FAR *rgColumnList;
DBID __RPC_FAR *pReferencedTableID;
ULONG cForeignKeyColumns;
/* [size_is] */ DBID __RPC_FAR *rgForeignKeyColumnList;
OLECHAR __RPC_FAR *pwszConstraintText;
DBUPDELRULE UpdateRule;
DBUPDELRULE DeleteRule;
DBMATCHTYPE MatchType;
DBDEFERRABILITY Deferrability;
ULONG cReserved;
/* [size_is] */ DBPROPSET __RPC_FAR *rgReserved;
} DBCONSTRAINTDESC;
#define MDFF_BOLD 0x01
#define MDFF_ITALIC 0x02
#define MDFF_UNDERLINE 0x04
#define MDFF_STRIKEOUT 0x08
typedef struct tagMDAXISINFO
{
ULONG cbSize;
ULONG iAxis;
ULONG cDimensions;
ULONG cCoordinates;
ULONG __RPC_FAR *rgcColumns;
LPOLESTR __RPC_FAR *rgpwszDimensionNames;
} MDAXISINFO;
#define PMDAXISINFO_GETAT(rgAxisInfo, iAxis) ((MDAXISINFO *)(((BYTE *)(rgAxisInfo)) +((iAxis) * (rgAxisInfo)[0].cbSize)))
#define MDAXISINFO_GETAT(rgAxisInfo, iAxis) (*PMDAXISINFO_GETAT((rgAxisInfo), (iAxis)))
#define MDAXIS_COLUMNS 0x00000000
#define MDAXIS_ROWS 0x00000001
#define MDAXIS_PAGES 0x00000002
#define MDAXIS_SECTIONS 0x00000003
#define MDAXIS_CHAPTERS 0x00000004
#define MDAXIS_SLICERS 0xffffffff
extern RPC_IF_HANDLE DBStructureDefinitions_v0_0_c_ifspec;
extern RPC_IF_HANDLE DBStructureDefinitions_v0_0_s_ifspec;
#endif /* __DBStructureDefinitions_INTERFACE_DEFINED__ */
#ifndef __IAccessor_INTERFACE_DEFINED__
#define __IAccessor_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IAccessor
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef DWORD DBACCESSORFLAGS;
enum DBACCESSORFLAGSENUM
{ DBACCESSOR_INVALID = 0,
DBACCESSOR_PASSBYREF = 0x1,
DBACCESSOR_ROWDATA = 0x2,
DBACCESSOR_PARAMETERDATA = 0x4,
DBACCESSOR_OPTIMIZED = 0x8,
DBACCESSOR_INHERITED = 0x10
};
typedef DWORD DBBINDSTATUS;
enum DBBINDSTATUSENUM
{ DBBINDSTATUS_OK = 0,
DBBINDSTATUS_BADORDINAL = 1,
DBBINDSTATUS_UNSUPPORTEDCONVERSION = 2,
DBBINDSTATUS_BADBINDINFO = 3,
DBBINDSTATUS_BADSTORAGEFLAGS = 4,
DBBINDSTATUS_NOINTERFACE = 5,
DBBINDSTATUS_MULTIPLESTORAGE = 6
};
EXTERN_C const IID IID_IAccessor;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a8c-2a1c-11ce-ade5-00aa0044773d")
IAccessor : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddRefAccessor(
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateAccessor(
/* [in] */ DBACCESSORFLAGS dwAccessorFlags,
/* [in] */ ULONG cBindings,
/* [size_is][in] */ const DBBINDING __RPC_FAR rgBindings[ ],
/* [in] */ ULONG cbRowSize,
/* [out] */ HACCESSOR __RPC_FAR *phAccessor,
/* [size_is][out] */ DBBINDSTATUS __RPC_FAR rgStatus[ ]) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBindings(
/* [in] */ HACCESSOR hAccessor,
/* [out] */ DBACCESSORFLAGS __RPC_FAR *pdwAccessorFlags,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ReleaseAccessor(
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount) = 0;
};
#else /* C style interface */
typedef struct IAccessorVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IAccessor __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IAccessor __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IAccessor __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddRefAccessor )(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateAccessor )(
IAccessor __RPC_FAR * This,
/* [in] */ DBACCESSORFLAGS dwAccessorFlags,
/* [in] */ ULONG cBindings,
/* [size_is][in] */ const DBBINDING __RPC_FAR rgBindings[ ],
/* [in] */ ULONG cbRowSize,
/* [out] */ HACCESSOR __RPC_FAR *phAccessor,
/* [size_is][out] */ DBBINDSTATUS __RPC_FAR rgStatus[ ]);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetBindings )(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ DBACCESSORFLAGS __RPC_FAR *pdwAccessorFlags,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseAccessor )(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount);
END_INTERFACE
} IAccessorVtbl;
interface IAccessor
{
CONST_VTBL struct IAccessorVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IAccessor_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IAccessor_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IAccessor_Release(This) \
(This)->lpVtbl -> Release(This)
#define IAccessor_AddRefAccessor(This,hAccessor,pcRefCount) \
(This)->lpVtbl -> AddRefAccessor(This,hAccessor,pcRefCount)
#define IAccessor_CreateAccessor(This,dwAccessorFlags,cBindings,rgBindings,cbRowSize,phAccessor,rgStatus) \
(This)->lpVtbl -> CreateAccessor(This,dwAccessorFlags,cBindings,rgBindings,cbRowSize,phAccessor,rgStatus)
#define IAccessor_GetBindings(This,hAccessor,pdwAccessorFlags,pcBindings,prgBindings) \
(This)->lpVtbl -> GetBindings(This,hAccessor,pdwAccessorFlags,pcBindings,prgBindings)
#define IAccessor_ReleaseAccessor(This,hAccessor,pcRefCount) \
(This)->lpVtbl -> ReleaseAccessor(This,hAccessor,pcRefCount)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_RemoteAddRefAccessor_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IAccessor_RemoteAddRefAccessor_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_RemoteCreateAccessor_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ DBACCESSORFLAGS dwAccessorFlags,
/* [in] */ ULONG cBindings,
/* [size_is][unique][in] */ DBBINDING __RPC_FAR *rgBindings,
/* [in] */ ULONG cbRowSize,
/* [out] */ HACCESSOR __RPC_FAR *phAccessor,
/* [size_is][unique][out][in] */ DBBINDSTATUS __RPC_FAR *rgStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IAccessor_RemoteCreateAccessor_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_RemoteGetBindings_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ DBACCESSORFLAGS __RPC_FAR *pdwAccessorFlags,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IAccessor_RemoteGetBindings_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_RemoteReleaseAccessor_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IAccessor_RemoteReleaseAccessor_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IAccessor_INTERFACE_DEFINED__ */
#ifndef __IRowset_INTERFACE_DEFINED__
#define __IRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
typedef DWORD DBROWOPTIONS;
EXTERN_C const IID IID_IRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a7c-2a1c-11ce-ade5-00aa0044773d")
IRowset : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE AddRefRows(
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE GetData(
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE GetNextRows(
/* [in] */ HCHAPTER hReserved,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows) = 0;
virtual HRESULT STDMETHODCALLTYPE ReleaseRows(
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][in] */ DBROWOPTIONS __RPC_FAR rgRowOptions[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE RestartPosition(
/* [in] */ HCHAPTER hReserved) = 0;
};
#else /* C style interface */
typedef struct IRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowset __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddRefRows )(
IRowset __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetData )(
IRowset __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextRows )(
IRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseRows )(
IRowset __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][in] */ DBROWOPTIONS __RPC_FAR rgRowOptions[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RestartPosition )(
IRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved);
END_INTERFACE
} IRowsetVtbl;
interface IRowset
{
CONST_VTBL struct IRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowset_AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus)
#define IRowset_GetData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetData(This,hRow,hAccessor,pData)
#define IRowset_GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowset_ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus)
#define IRowset_RestartPosition(This,hReserved) \
(This)->lpVtbl -> RestartPosition(This,hReserved)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowset_AddRefRows_Proxy(
IRowset __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
void __RPC_STUB IRowset_AddRefRows_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowset_GetData_Proxy(
IRowset __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
void __RPC_STUB IRowset_GetData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowset_GetNextRows_Proxy(
IRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
void __RPC_STUB IRowset_GetNextRows_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowset_ReleaseRows_Proxy(
IRowset __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][in] */ DBROWOPTIONS __RPC_FAR rgRowOptions[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
void __RPC_STUB IRowset_ReleaseRows_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowset_RestartPosition_Proxy(
IRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved);
void __RPC_STUB IRowset_RestartPosition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowset_INTERFACE_DEFINED__ */
#ifndef __IRowsetInfo_INTERFACE_DEFINED__
#define __IRowsetInfo_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetInfo
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IRowsetInfo;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a55-2a1c-11ce-ade5-00aa0044773d")
IRowsetInfo : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetProperties(
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetReferencedRowset(
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppReferencedRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSpecification(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification) = 0;
};
#else /* C style interface */
typedef struct IRowsetInfoVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetInfo __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetInfo __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetProperties )(
IRowsetInfo __RPC_FAR * This,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetReferencedRowset )(
IRowsetInfo __RPC_FAR * This,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppReferencedRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSpecification )(
IRowsetInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification);
END_INTERFACE
} IRowsetInfoVtbl;
interface IRowsetInfo
{
CONST_VTBL struct IRowsetInfoVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetInfo_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetInfo_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetInfo_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetInfo_GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets) \
(This)->lpVtbl -> GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets)
#define IRowsetInfo_GetReferencedRowset(This,iOrdinal,riid,ppReferencedRowset) \
(This)->lpVtbl -> GetReferencedRowset(This,iOrdinal,riid,ppReferencedRowset)
#define IRowsetInfo_GetSpecification(This,riid,ppSpecification) \
(This)->lpVtbl -> GetSpecification(This,riid,ppSpecification)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_RemoteGetProperties_Proxy(
IRowsetInfo __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetInfo_RemoteGetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_RemoteGetReferencedRowset_Proxy(
IRowsetInfo __RPC_FAR * This,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppReferencedRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetInfo_RemoteGetReferencedRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_RemoteGetSpecification_Proxy(
IRowsetInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetInfo_RemoteGetSpecification_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetInfo_INTERFACE_DEFINED__ */
#ifndef __IRowsetLocate_INTERFACE_DEFINED__
#define __IRowsetLocate_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetLocate
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
typedef DWORD DBCOMPARE;
enum DBCOMPAREENUM
{ DBCOMPARE_LT = 0,
DBCOMPARE_EQ = DBCOMPARE_LT + 1,
DBCOMPARE_GT = DBCOMPARE_EQ + 1,
DBCOMPARE_NE = DBCOMPARE_GT + 1,
DBCOMPARE_NOTCOMPARABLE = DBCOMPARE_NE + 1
};
EXTERN_C const IID IID_IRowsetLocate;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a7d-2a1c-11ce-ade5-00aa0044773d")
IRowsetLocate : public IRowset
{
public:
virtual HRESULT STDMETHODCALLTYPE Compare(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark1,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark1,
/* [in] */ ULONG cbBookmark2,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark2,
/* [out] */ DBCOMPARE __RPC_FAR *pComparison) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRowsAt(
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRowsByBookmark(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE Hash(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cBookmarks,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ DWORD __RPC_FAR rgHashedValues[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgBookmarkStatus[ ]) = 0;
};
#else /* C style interface */
typedef struct IRowsetLocateVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetLocate __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetLocate __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddRefRows )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetData )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextRows )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseRows )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][in] */ DBROWOPTIONS __RPC_FAR rgRowOptions[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RestartPosition )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Compare )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark1,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark1,
/* [in] */ ULONG cbBookmark2,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark2,
/* [out] */ DBCOMPARE __RPC_FAR *pComparison);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsAt )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsByBookmark )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Hash )(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cBookmarks,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ DWORD __RPC_FAR rgHashedValues[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgBookmarkStatus[ ]);
END_INTERFACE
} IRowsetLocateVtbl;
interface IRowsetLocate
{
CONST_VTBL struct IRowsetLocateVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetLocate_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetLocate_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetLocate_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetLocate_AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus)
#define IRowsetLocate_GetData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetData(This,hRow,hAccessor,pData)
#define IRowsetLocate_GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowsetLocate_ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus)
#define IRowsetLocate_RestartPosition(This,hReserved) \
(This)->lpVtbl -> RestartPosition(This,hReserved)
#define IRowsetLocate_Compare(This,hReserved,cbBookmark1,pBookmark1,cbBookmark2,pBookmark2,pComparison) \
(This)->lpVtbl -> Compare(This,hReserved,cbBookmark1,pBookmark1,cbBookmark2,pBookmark2,pComparison)
#define IRowsetLocate_GetRowsAt(This,hReserved1,hReserved2,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetRowsAt(This,hReserved1,hReserved2,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowsetLocate_GetRowsByBookmark(This,hReserved,cRows,rgcbBookmarks,rgpBookmarks,rghRows,rgRowStatus) \
(This)->lpVtbl -> GetRowsByBookmark(This,hReserved,cRows,rgcbBookmarks,rgpBookmarks,rghRows,rgRowStatus)
#define IRowsetLocate_Hash(This,hReserved,cBookmarks,rgcbBookmarks,rgpBookmarks,rgHashedValues,rgBookmarkStatus) \
(This)->lpVtbl -> Hash(This,hReserved,cBookmarks,rgcbBookmarks,rgpBookmarks,rgHashedValues,rgBookmarkStatus)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetLocate_Compare_Proxy(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark1,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark1,
/* [in] */ ULONG cbBookmark2,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark2,
/* [out] */ DBCOMPARE __RPC_FAR *pComparison);
void __RPC_STUB IRowsetLocate_Compare_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetLocate_GetRowsAt_Proxy(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
void __RPC_STUB IRowsetLocate_GetRowsAt_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetLocate_GetRowsByBookmark_Proxy(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
void __RPC_STUB IRowsetLocate_GetRowsByBookmark_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetLocate_Hash_Proxy(
IRowsetLocate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cBookmarks,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ DWORD __RPC_FAR rgHashedValues[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgBookmarkStatus[ ]);
void __RPC_STUB IRowsetLocate_Hash_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetLocate_INTERFACE_DEFINED__ */
#ifndef __IRowsetResynch_INTERFACE_DEFINED__
#define __IRowsetResynch_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetResynch
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetResynch;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a84-2a1c-11ce-ade5-00aa0044773d")
IRowsetResynch : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetVisibleData(
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE ResynchRows(
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out] */ ULONG __RPC_FAR *pcRowsResynched,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRowsResynched,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus) = 0;
};
#else /* C style interface */
typedef struct IRowsetResynchVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetResynch __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetResynch __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetResynch __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetVisibleData )(
IRowsetResynch __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ResynchRows )(
IRowsetResynch __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out] */ ULONG __RPC_FAR *pcRowsResynched,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRowsResynched,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
END_INTERFACE
} IRowsetResynchVtbl;
interface IRowsetResynch
{
CONST_VTBL struct IRowsetResynchVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetResynch_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetResynch_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetResynch_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetResynch_GetVisibleData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetVisibleData(This,hRow,hAccessor,pData)
#define IRowsetResynch_ResynchRows(This,cRows,rghRows,pcRowsResynched,prghRowsResynched,prgRowStatus) \
(This)->lpVtbl -> ResynchRows(This,cRows,rghRows,pcRowsResynched,prghRowsResynched,prgRowStatus)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetResynch_GetVisibleData_Proxy(
IRowsetResynch __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
void __RPC_STUB IRowsetResynch_GetVisibleData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetResynch_ResynchRows_Proxy(
IRowsetResynch __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out] */ ULONG __RPC_FAR *pcRowsResynched,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRowsResynched,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
void __RPC_STUB IRowsetResynch_ResynchRows_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetResynch_INTERFACE_DEFINED__ */
#ifndef __IRowsetScroll_INTERFACE_DEFINED__
#define __IRowsetScroll_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetScroll
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetScroll;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a7e-2a1c-11ce-ade5-00aa0044773d")
IRowsetScroll : public IRowsetLocate
{
public:
virtual HRESULT STDMETHODCALLTYPE GetApproximatePosition(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRowsAtRatio(
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG ulNumerator,
/* [in] */ ULONG ulDenominator,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows) = 0;
};
#else /* C style interface */
typedef struct IRowsetScrollVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetScroll __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetScroll __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddRefRows )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetData )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextRows )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseRows )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][in] */ DBROWOPTIONS __RPC_FAR rgRowOptions[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RestartPosition )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Compare )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark1,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark1,
/* [in] */ ULONG cbBookmark2,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark2,
/* [out] */ DBCOMPARE __RPC_FAR *pComparison);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsAt )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsByBookmark )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Hash )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cBookmarks,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ DWORD __RPC_FAR rgHashedValues[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgBookmarkStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetApproximatePosition )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsAtRatio )(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG ulNumerator,
/* [in] */ ULONG ulDenominator,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
END_INTERFACE
} IRowsetScrollVtbl;
interface IRowsetScroll
{
CONST_VTBL struct IRowsetScrollVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetScroll_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetScroll_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetScroll_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetScroll_AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus)
#define IRowsetScroll_GetData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetData(This,hRow,hAccessor,pData)
#define IRowsetScroll_GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowsetScroll_ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus)
#define IRowsetScroll_RestartPosition(This,hReserved) \
(This)->lpVtbl -> RestartPosition(This,hReserved)
#define IRowsetScroll_Compare(This,hReserved,cbBookmark1,pBookmark1,cbBookmark2,pBookmark2,pComparison) \
(This)->lpVtbl -> Compare(This,hReserved,cbBookmark1,pBookmark1,cbBookmark2,pBookmark2,pComparison)
#define IRowsetScroll_GetRowsAt(This,hReserved1,hReserved2,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetRowsAt(This,hReserved1,hReserved2,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowsetScroll_GetRowsByBookmark(This,hReserved,cRows,rgcbBookmarks,rgpBookmarks,rghRows,rgRowStatus) \
(This)->lpVtbl -> GetRowsByBookmark(This,hReserved,cRows,rgcbBookmarks,rgpBookmarks,rghRows,rgRowStatus)
#define IRowsetScroll_Hash(This,hReserved,cBookmarks,rgcbBookmarks,rgpBookmarks,rgHashedValues,rgBookmarkStatus) \
(This)->lpVtbl -> Hash(This,hReserved,cBookmarks,rgcbBookmarks,rgpBookmarks,rgHashedValues,rgBookmarkStatus)
#define IRowsetScroll_GetApproximatePosition(This,hReserved,cbBookmark,pBookmark,pulPosition,pcRows) \
(This)->lpVtbl -> GetApproximatePosition(This,hReserved,cbBookmark,pBookmark,pulPosition,pcRows)
#define IRowsetScroll_GetRowsAtRatio(This,hReserved1,hReserved2,ulNumerator,ulDenominator,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetRowsAtRatio(This,hReserved1,hReserved2,ulNumerator,ulDenominator,cRows,pcRowsObtained,prghRows)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetScroll_GetApproximatePosition_Proxy(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows);
void __RPC_STUB IRowsetScroll_GetApproximatePosition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetScroll_GetRowsAtRatio_Proxy(
IRowsetScroll __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG ulNumerator,
/* [in] */ ULONG ulDenominator,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
void __RPC_STUB IRowsetScroll_GetRowsAtRatio_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetScroll_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0161
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
extern RPC_IF_HANDLE __MIDL_itf_oledb_0161_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0161_v0_0_s_ifspec;
#ifndef __IChapteredRowset_INTERFACE_DEFINED__
#define __IChapteredRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IChapteredRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IChapteredRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a93-2a1c-11ce-ade5-00aa0044773d")
IChapteredRowset : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddRefChapter(
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ReleaseChapter(
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount) = 0;
};
#else /* C style interface */
typedef struct IChapteredRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IChapteredRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IChapteredRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IChapteredRowset __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddRefChapter )(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseChapter )(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount);
END_INTERFACE
} IChapteredRowsetVtbl;
interface IChapteredRowset
{
CONST_VTBL struct IChapteredRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IChapteredRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IChapteredRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IChapteredRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IChapteredRowset_AddRefChapter(This,hChapter,pcRefCount) \
(This)->lpVtbl -> AddRefChapter(This,hChapter,pcRefCount)
#define IChapteredRowset_ReleaseChapter(This,hChapter,pcRefCount) \
(This)->lpVtbl -> ReleaseChapter(This,hChapter,pcRefCount)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IChapteredRowset_RemoteAddRefChapter_Proxy(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IChapteredRowset_RemoteAddRefChapter_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IChapteredRowset_RemoteReleaseChapter_Proxy(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IChapteredRowset_RemoteReleaseChapter_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IChapteredRowset_INTERFACE_DEFINED__ */
#ifndef __IRowsetFind_INTERFACE_DEFINED__
#define __IRowsetFind_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetFind
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetFind;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a9d-2a1c-11ce-ade5-00aa0044773d")
IRowsetFind : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE FindNextRow(
/* [in] */ HCHAPTER hChapter,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pFindValue,
/* [in] */ DBCOMPAREOP CompareOp,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out][in] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows) = 0;
};
#else /* C style interface */
typedef struct IRowsetFindVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetFind __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetFind __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetFind __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *FindNextRow )(
IRowsetFind __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pFindValue,
/* [in] */ DBCOMPAREOP CompareOp,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out][in] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
END_INTERFACE
} IRowsetFindVtbl;
interface IRowsetFind
{
CONST_VTBL struct IRowsetFindVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetFind_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetFind_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetFind_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetFind_FindNextRow(This,hChapter,hAccessor,pFindValue,CompareOp,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> FindNextRow(This,hChapter,hAccessor,pFindValue,CompareOp,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetFind_FindNextRow_Proxy(
IRowsetFind __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pFindValue,
/* [in] */ DBCOMPAREOP CompareOp,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out][in] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
void __RPC_STUB IRowsetFind_FindNextRow_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetFind_INTERFACE_DEFINED__ */
#ifndef __IRowPosition_INTERFACE_DEFINED__
#define __IRowPosition_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowPosition
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef DWORD DBPOSITIONFLAGS;
enum DBPOSITIONFLAGSENUM
{ DBPOSITION_OK = 0,
DBPOSITION_NOROW = DBPOSITION_OK + 1,
DBPOSITION_BOF = DBPOSITION_NOROW + 1,
DBPOSITION_EOF = DBPOSITION_BOF + 1
};
EXTERN_C const IID IID_IRowPosition;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a94-2a1c-11ce-ade5-00aa0044773d")
IRowPosition : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ClearRowPosition( void) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRowPosition(
/* [out] */ HCHAPTER __RPC_FAR *phChapter,
/* [out] */ HROW __RPC_FAR *phRow,
/* [out] */ DBPOSITIONFLAGS __RPC_FAR *pdwPositionFlags) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRowset(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Initialize(
/* [in] */ IUnknown __RPC_FAR *pRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetRowPosition(
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow,
/* [in] */ DBPOSITIONFLAGS dwPositionFlags) = 0;
};
#else /* C style interface */
typedef struct IRowPositionVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowPosition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowPosition __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowPosition __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ClearRowPosition )(
IRowPosition __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowPosition )(
IRowPosition __RPC_FAR * This,
/* [out] */ HCHAPTER __RPC_FAR *phChapter,
/* [out] */ HROW __RPC_FAR *phRow,
/* [out] */ DBPOSITIONFLAGS __RPC_FAR *pdwPositionFlags);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowset )(
IRowPosition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Initialize )(
IRowPosition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetRowPosition )(
IRowPosition __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow,
/* [in] */ DBPOSITIONFLAGS dwPositionFlags);
END_INTERFACE
} IRowPositionVtbl;
interface IRowPosition
{
CONST_VTBL struct IRowPositionVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowPosition_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowPosition_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowPosition_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowPosition_ClearRowPosition(This) \
(This)->lpVtbl -> ClearRowPosition(This)
#define IRowPosition_GetRowPosition(This,phChapter,phRow,pdwPositionFlags) \
(This)->lpVtbl -> GetRowPosition(This,phChapter,phRow,pdwPositionFlags)
#define IRowPosition_GetRowset(This,riid,ppRowset) \
(This)->lpVtbl -> GetRowset(This,riid,ppRowset)
#define IRowPosition_Initialize(This,pRowset) \
(This)->lpVtbl -> Initialize(This,pRowset)
#define IRowPosition_SetRowPosition(This,hChapter,hRow,dwPositionFlags) \
(This)->lpVtbl -> SetRowPosition(This,hChapter,hRow,dwPositionFlags)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_RemoteClearRowPosition_Proxy(
IRowPosition __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowPosition_RemoteClearRowPosition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_RemoteGetRowPosition_Proxy(
IRowPosition __RPC_FAR * This,
/* [out] */ HCHAPTER __RPC_FAR *phChapter,
/* [out] */ HROW __RPC_FAR *phRow,
/* [out] */ DBPOSITIONFLAGS __RPC_FAR *pdwPositionFlags,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowPosition_RemoteGetRowPosition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_RemoteGetRowset_Proxy(
IRowPosition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowPosition_RemoteGetRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_RemoteInitialize_Proxy(
IRowPosition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowPosition_RemoteInitialize_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_RemoteSetRowPosition_Proxy(
IRowPosition __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow,
/* [in] */ DBPOSITIONFLAGS dwPositionFlags,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowPosition_RemoteSetRowPosition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowPosition_INTERFACE_DEFINED__ */
#ifndef __IRowPositionChange_INTERFACE_DEFINED__
#define __IRowPositionChange_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowPositionChange
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IRowPositionChange;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0997a571-126e-11d0-9f8a-00a0c9a0631e")
IRowPositionChange : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnRowPositionChange(
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny) = 0;
};
#else /* C style interface */
typedef struct IRowPositionChangeVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowPositionChange __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowPositionChange __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowPositionChange __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnRowPositionChange )(
IRowPositionChange __RPC_FAR * This,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
END_INTERFACE
} IRowPositionChangeVtbl;
interface IRowPositionChange
{
CONST_VTBL struct IRowPositionChangeVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowPositionChange_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowPositionChange_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowPositionChange_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowPositionChange_OnRowPositionChange(This,eReason,ePhase,fCantDeny) \
(This)->lpVtbl -> OnRowPositionChange(This,eReason,ePhase,fCantDeny)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPositionChange_RemoteOnRowPositionChange_Proxy(
IRowPositionChange __RPC_FAR * This,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowPositionChange_RemoteOnRowPositionChange_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowPositionChange_INTERFACE_DEFINED__ */
#ifndef __IViewRowset_INTERFACE_DEFINED__
#define __IViewRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IViewRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IViewRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a97-2a1c-11ce-ade5-00aa0044773d")
IViewRowset : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSpecification(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OpenViewRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
};
#else /* C style interface */
typedef struct IViewRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IViewRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IViewRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IViewRowset __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSpecification )(
IViewRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OpenViewRowset )(
IViewRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
END_INTERFACE
} IViewRowsetVtbl;
interface IViewRowset
{
CONST_VTBL struct IViewRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IViewRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IViewRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IViewRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IViewRowset_GetSpecification(This,riid,ppObject) \
(This)->lpVtbl -> GetSpecification(This,riid,ppObject)
#define IViewRowset_OpenViewRowset(This,pUnkOuter,riid,ppRowset) \
(This)->lpVtbl -> OpenViewRowset(This,pUnkOuter,riid,ppRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewRowset_RemoteGetSpecification_Proxy(
IViewRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewRowset_RemoteGetSpecification_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewRowset_RemoteOpenViewRowset_Proxy(
IViewRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewRowset_RemoteOpenViewRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IViewRowset_INTERFACE_DEFINED__ */
#ifndef __IViewChapter_INTERFACE_DEFINED__
#define __IViewChapter_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IViewChapter
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IViewChapter;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a98-2a1c-11ce-ade5-00aa0044773d")
IViewChapter : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSpecification(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OpenViewChapter(
/* [in] */ HCHAPTER hSource,
/* [out] */ HCHAPTER __RPC_FAR *phViewChapter) = 0;
};
#else /* C style interface */
typedef struct IViewChapterVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IViewChapter __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IViewChapter __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IViewChapter __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSpecification )(
IViewChapter __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OpenViewChapter )(
IViewChapter __RPC_FAR * This,
/* [in] */ HCHAPTER hSource,
/* [out] */ HCHAPTER __RPC_FAR *phViewChapter);
END_INTERFACE
} IViewChapterVtbl;
interface IViewChapter
{
CONST_VTBL struct IViewChapterVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IViewChapter_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IViewChapter_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IViewChapter_Release(This) \
(This)->lpVtbl -> Release(This)
#define IViewChapter_GetSpecification(This,riid,ppRowset) \
(This)->lpVtbl -> GetSpecification(This,riid,ppRowset)
#define IViewChapter_OpenViewChapter(This,hSource,phViewChapter) \
(This)->lpVtbl -> OpenViewChapter(This,hSource,phViewChapter)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewChapter_RemoteGetSpecification_Proxy(
IViewChapter __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewChapter_RemoteGetSpecification_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewChapter_RemoteOpenViewChapter_Proxy(
IViewChapter __RPC_FAR * This,
/* [in] */ HCHAPTER hSource,
/* [out] */ HCHAPTER __RPC_FAR *phViewChapter,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewChapter_RemoteOpenViewChapter_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IViewChapter_INTERFACE_DEFINED__ */
#ifndef __IViewSort_INTERFACE_DEFINED__
#define __IViewSort_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IViewSort
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IViewSort;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a9a-2a1c-11ce-ade5-00aa0044773d")
IViewSort : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSortOrder(
/* [out] */ ULONG __RPC_FAR *pcValues,
/* [out] */ ULONG __RPC_FAR *__RPC_FAR prgColumns[ ],
/* [out] */ DBSORT __RPC_FAR *__RPC_FAR prgOrders[ ]) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetSortOrder(
/* [in] */ ULONG cValues,
/* [size_is][in] */ const ULONG __RPC_FAR rgColumns[ ],
/* [size_is][in] */ const DBSORT __RPC_FAR rgOrders[ ]) = 0;
};
#else /* C style interface */
typedef struct IViewSortVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IViewSort __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IViewSort __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IViewSort __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSortOrder )(
IViewSort __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcValues,
/* [out] */ ULONG __RPC_FAR *__RPC_FAR prgColumns[ ],
/* [out] */ DBSORT __RPC_FAR *__RPC_FAR prgOrders[ ]);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetSortOrder )(
IViewSort __RPC_FAR * This,
/* [in] */ ULONG cValues,
/* [size_is][in] */ const ULONG __RPC_FAR rgColumns[ ],
/* [size_is][in] */ const DBSORT __RPC_FAR rgOrders[ ]);
END_INTERFACE
} IViewSortVtbl;
interface IViewSort
{
CONST_VTBL struct IViewSortVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IViewSort_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IViewSort_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IViewSort_Release(This) \
(This)->lpVtbl -> Release(This)
#define IViewSort_GetSortOrder(This,pcValues,prgColumns,prgOrders) \
(This)->lpVtbl -> GetSortOrder(This,pcValues,prgColumns,prgOrders)
#define IViewSort_SetSortOrder(This,cValues,rgColumns,rgOrders) \
(This)->lpVtbl -> SetSortOrder(This,cValues,rgColumns,rgOrders)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewSort_RemoteGetSortOrder_Proxy(
IViewSort __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcValues,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgColumns,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgOrders,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewSort_RemoteGetSortOrder_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewSort_RemoteSetSortOrder_Proxy(
IViewSort __RPC_FAR * This,
/* [in] */ ULONG cValues,
/* [size_is][in] */ const ULONG __RPC_FAR *rgColumns,
/* [size_is][in] */ const DBSORT __RPC_FAR *rgOrders,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewSort_RemoteSetSortOrder_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IViewSort_INTERFACE_DEFINED__ */
#ifndef __IViewFilter_INTERFACE_DEFINED__
#define __IViewFilter_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IViewFilter
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IViewFilter;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a9b-2a1c-11ce-ade5-00aa0044773d")
IViewFilter : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetFilter(
/* [in] */ HACCESSOR hAccessor,
/* [out] */ ULONG __RPC_FAR *pcRows,
/* [out] */ DBCOMPAREOP __RPC_FAR *__RPC_FAR pCompareOps[ ],
/* [out] */ void __RPC_FAR *pCriteriaData) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetFilterBindings(
/* [out] */ ULONG __RPC_FAR *pcBindings,
/* [out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetFilter(
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cRows,
/* [in] */ DBCOMPAREOP __RPC_FAR CompareOps[ ],
/* [in] */ void __RPC_FAR *pCriteriaData) = 0;
};
#else /* C style interface */
typedef struct IViewFilterVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IViewFilter __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IViewFilter __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IViewFilter __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFilter )(
IViewFilter __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ ULONG __RPC_FAR *pcRows,
/* [out] */ DBCOMPAREOP __RPC_FAR *__RPC_FAR pCompareOps[ ],
/* [out] */ void __RPC_FAR *pCriteriaData);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetFilterBindings )(
IViewFilter __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcBindings,
/* [out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetFilter )(
IViewFilter __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cRows,
/* [in] */ DBCOMPAREOP __RPC_FAR CompareOps[ ],
/* [in] */ void __RPC_FAR *pCriteriaData);
END_INTERFACE
} IViewFilterVtbl;
interface IViewFilter
{
CONST_VTBL struct IViewFilterVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IViewFilter_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IViewFilter_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IViewFilter_Release(This) \
(This)->lpVtbl -> Release(This)
#define IViewFilter_GetFilter(This,hAccessor,pcRows,pCompareOps,pCriteriaData) \
(This)->lpVtbl -> GetFilter(This,hAccessor,pcRows,pCompareOps,pCriteriaData)
#define IViewFilter_GetFilterBindings(This,pcBindings,prgBindings) \
(This)->lpVtbl -> GetFilterBindings(This,pcBindings,prgBindings)
#define IViewFilter_SetFilter(This,hAccessor,cRows,CompareOps,pCriteriaData) \
(This)->lpVtbl -> SetFilter(This,hAccessor,cRows,CompareOps,pCriteriaData)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [local] */ HRESULT STDMETHODCALLTYPE IViewFilter_GetFilter_Proxy(
IViewFilter __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ ULONG __RPC_FAR *pcRows,
/* [out] */ DBCOMPAREOP __RPC_FAR *__RPC_FAR pCompareOps[ ],
/* [out] */ void __RPC_FAR *pCriteriaData);
void __RPC_STUB IViewFilter_GetFilter_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewFilter_RemoteGetFilterBindings_Proxy(
IViewFilter __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IViewFilter_RemoteGetFilterBindings_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewFilter_SetFilter_Proxy(
IViewFilter __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cRows,
/* [in] */ DBCOMPAREOP __RPC_FAR CompareOps[ ],
/* [in] */ void __RPC_FAR *pCriteriaData);
void __RPC_STUB IViewFilter_SetFilter_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IViewFilter_INTERFACE_DEFINED__ */
#ifndef __IRowsetView_INTERFACE_DEFINED__
#define __IRowsetView_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetView
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IRowsetView;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a99-2a1c-11ce-ade5-00aa0044773d")
IRowsetView : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateView(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetView(
/* [in] */ HCHAPTER hChapter,
/* [in] */ REFIID riid,
/* [out] */ HCHAPTER __RPC_FAR *phChapterSource,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView) = 0;
};
#else /* C style interface */
typedef struct IRowsetViewVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetView __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetView __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetView __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateView )(
IRowsetView __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetView )(
IRowsetView __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ REFIID riid,
/* [out] */ HCHAPTER __RPC_FAR *phChapterSource,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView);
END_INTERFACE
} IRowsetViewVtbl;
interface IRowsetView
{
CONST_VTBL struct IRowsetViewVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetView_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetView_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetView_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetView_CreateView(This,pUnkOuter,riid,ppView) \
(This)->lpVtbl -> CreateView(This,pUnkOuter,riid,ppView)
#define IRowsetView_GetView(This,hChapter,riid,phChapterSource,ppView) \
(This)->lpVtbl -> GetView(This,hChapter,riid,phChapterSource,ppView)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetView_RemoteCreateView_Proxy(
IRowsetView __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetView_RemoteCreateView_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetView_RemoteGetView_Proxy(
IRowsetView __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ REFIID riid,
/* [out] */ HCHAPTER __RPC_FAR *phChapterSource,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetView_RemoteGetView_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetView_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0170
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
//@@@+ deprecated
#ifdef deprecated
extern RPC_IF_HANDLE __MIDL_itf_oledb_0170_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0170_v0_0_s_ifspec;
#ifndef __IRowsetExactScroll_INTERFACE_DEFINED__
#define __IRowsetExactScroll_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetExactScroll
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetExactScroll;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a7f-2a1c-11ce-ade5-00aa0044773d")
IRowsetExactScroll : public IRowsetScroll
{
public:
virtual HRESULT STDMETHODCALLTYPE GetExactPosition(
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows) = 0;
};
#else /* C style interface */
typedef struct IRowsetExactScrollVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetExactScroll __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetExactScroll __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddRefRows )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetData )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetNextRows )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseRows )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][in] */ DBROWOPTIONS __RPC_FAR rgRowOptions[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgRefCounts[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RestartPosition )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Compare )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark1,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark1,
/* [in] */ ULONG cbBookmark2,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark2,
/* [out] */ DBCOMPARE __RPC_FAR *pComparison);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsAt )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [in] */ LONG lRowsOffset,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsByBookmark )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Hash )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cBookmarks,
/* [size_is][in] */ const ULONG __RPC_FAR rgcbBookmarks[ ],
/* [size_is][in] */ const BYTE __RPC_FAR *__RPC_FAR rgpBookmarks[ ],
/* [size_is][out] */ DWORD __RPC_FAR rgHashedValues[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgBookmarkStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetApproximatePosition )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowsAtRatio )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HWATCHREGION hReserved1,
/* [in] */ HCHAPTER hReserved2,
/* [in] */ ULONG ulNumerator,
/* [in] */ ULONG ulDenominator,
/* [in] */ LONG cRows,
/* [out] */ ULONG __RPC_FAR *pcRowsObtained,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prghRows);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetExactPosition )(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows);
END_INTERFACE
} IRowsetExactScrollVtbl;
interface IRowsetExactScroll
{
CONST_VTBL struct IRowsetExactScrollVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetExactScroll_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetExactScroll_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetExactScroll_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetExactScroll_AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> AddRefRows(This,cRows,rghRows,rgRefCounts,rgRowStatus)
#define IRowsetExactScroll_GetData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetData(This,hRow,hAccessor,pData)
#define IRowsetExactScroll_GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetNextRows(This,hReserved,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowsetExactScroll_ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus) \
(This)->lpVtbl -> ReleaseRows(This,cRows,rghRows,rgRowOptions,rgRefCounts,rgRowStatus)
#define IRowsetExactScroll_RestartPosition(This,hReserved) \
(This)->lpVtbl -> RestartPosition(This,hReserved)
#define IRowsetExactScroll_Compare(This,hReserved,cbBookmark1,pBookmark1,cbBookmark2,pBookmark2,pComparison) \
(This)->lpVtbl -> Compare(This,hReserved,cbBookmark1,pBookmark1,cbBookmark2,pBookmark2,pComparison)
#define IRowsetExactScroll_GetRowsAt(This,hReserved1,hReserved2,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetRowsAt(This,hReserved1,hReserved2,cbBookmark,pBookmark,lRowsOffset,cRows,pcRowsObtained,prghRows)
#define IRowsetExactScroll_GetRowsByBookmark(This,hReserved,cRows,rgcbBookmarks,rgpBookmarks,rghRows,rgRowStatus) \
(This)->lpVtbl -> GetRowsByBookmark(This,hReserved,cRows,rgcbBookmarks,rgpBookmarks,rghRows,rgRowStatus)
#define IRowsetExactScroll_Hash(This,hReserved,cBookmarks,rgcbBookmarks,rgpBookmarks,rgHashedValues,rgBookmarkStatus) \
(This)->lpVtbl -> Hash(This,hReserved,cBookmarks,rgcbBookmarks,rgpBookmarks,rgHashedValues,rgBookmarkStatus)
#define IRowsetExactScroll_GetApproximatePosition(This,hReserved,cbBookmark,pBookmark,pulPosition,pcRows) \
(This)->lpVtbl -> GetApproximatePosition(This,hReserved,cbBookmark,pBookmark,pulPosition,pcRows)
#define IRowsetExactScroll_GetRowsAtRatio(This,hReserved1,hReserved2,ulNumerator,ulDenominator,cRows,pcRowsObtained,prghRows) \
(This)->lpVtbl -> GetRowsAtRatio(This,hReserved1,hReserved2,ulNumerator,ulDenominator,cRows,pcRowsObtained,prghRows)
#define IRowsetExactScroll_GetExactPosition(This,hChapter,cbBookmark,pBookmark,pulPosition,pcRows) \
(This)->lpVtbl -> GetExactPosition(This,hChapter,cbBookmark,pBookmark,pulPosition,pcRows)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetExactScroll_GetExactPosition_Proxy(
IRowsetExactScroll __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark,
/* [out] */ ULONG __RPC_FAR *pulPosition,
/* [out] */ ULONG __RPC_FAR *pcRows);
void __RPC_STUB IRowsetExactScroll_GetExactPosition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetExactScroll_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0171
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
#endif // deprecated
//@@@- deprecated
extern RPC_IF_HANDLE __MIDL_itf_oledb_0171_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0171_v0_0_s_ifspec;
#ifndef __IRowsetChange_INTERFACE_DEFINED__
#define __IRowsetChange_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetChange
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetChange;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a05-2a1c-11ce-ade5-00aa0044773d")
IRowsetChange : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE DeleteRows(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE SetData(
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE InsertRow(
/* [in] */ HCHAPTER hReserved,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData,
/* [out] */ HROW __RPC_FAR *phRow) = 0;
};
#else /* C style interface */
typedef struct IRowsetChangeVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetChange __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetChange __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetChange __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DeleteRows )(
IRowsetChange __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetData )(
IRowsetChange __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *InsertRow )(
IRowsetChange __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData,
/* [out] */ HROW __RPC_FAR *phRow);
END_INTERFACE
} IRowsetChangeVtbl;
interface IRowsetChange
{
CONST_VTBL struct IRowsetChangeVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetChange_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetChange_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetChange_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetChange_DeleteRows(This,hReserved,cRows,rghRows,rgRowStatus) \
(This)->lpVtbl -> DeleteRows(This,hReserved,cRows,rghRows,rgRowStatus)
#define IRowsetChange_SetData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> SetData(This,hRow,hAccessor,pData)
#define IRowsetChange_InsertRow(This,hReserved,hAccessor,pData,phRow) \
(This)->lpVtbl -> InsertRow(This,hReserved,hAccessor,pData,phRow)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetChange_DeleteRows_Proxy(
IRowsetChange __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
void __RPC_STUB IRowsetChange_DeleteRows_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetChange_SetData_Proxy(
IRowsetChange __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData);
void __RPC_STUB IRowsetChange_SetData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetChange_InsertRow_Proxy(
IRowsetChange __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData,
/* [out] */ HROW __RPC_FAR *phRow);
void __RPC_STUB IRowsetChange_InsertRow_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetChange_INTERFACE_DEFINED__ */
#ifndef __IRowsetUpdate_INTERFACE_DEFINED__
#define __IRowsetUpdate_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetUpdate
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
typedef DWORD DBPENDINGSTATUS;
enum DBPENDINGSTATUSENUM
{ DBPENDINGSTATUS_NEW = 0x1,
DBPENDINGSTATUS_CHANGED = 0x2,
DBPENDINGSTATUS_DELETED = 0x4,
DBPENDINGSTATUS_UNCHANGED = 0x8,
DBPENDINGSTATUS_INVALIDROW = 0x10
};
EXTERN_C const IID IID_IRowsetUpdate;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a6d-2a1c-11ce-ade5-00aa0044773d")
IRowsetUpdate : public IRowsetChange
{
public:
virtual HRESULT STDMETHODCALLTYPE GetOriginalData(
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPendingRows(
/* [in] */ HCHAPTER hReserved,
/* [in] */ DBPENDINGSTATUS dwRowStatus,
/* [out][in] */ ULONG __RPC_FAR *pcPendingRows,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgPendingRows,
/* [size_is][size_is][out] */ DBPENDINGSTATUS __RPC_FAR *__RPC_FAR *prgPendingStatus) = 0;
virtual HRESULT STDMETHODCALLTYPE GetRowStatus(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBPENDINGSTATUS __RPC_FAR rgPendingStatus[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE Undo(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out][in] */ ULONG __RPC_FAR *pcRowsUndone,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgRowsUndone,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus) = 0;
virtual HRESULT STDMETHODCALLTYPE Update(
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out][in] */ ULONG __RPC_FAR *pcRows,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgRows,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus) = 0;
};
#else /* C style interface */
typedef struct IRowsetUpdateVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetUpdate __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetUpdate __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DeleteRows )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBROWSTATUS __RPC_FAR rgRowStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetData )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *InsertRow )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ void __RPC_FAR *pData,
/* [out] */ HROW __RPC_FAR *phRow);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetOriginalData )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetPendingRows )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ DBPENDINGSTATUS dwRowStatus,
/* [out][in] */ ULONG __RPC_FAR *pcPendingRows,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgPendingRows,
/* [size_is][size_is][out] */ DBPENDINGSTATUS __RPC_FAR *__RPC_FAR *prgPendingStatus);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowStatus )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBPENDINGSTATUS __RPC_FAR rgPendingStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Undo )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out][in] */ ULONG __RPC_FAR *pcRowsUndone,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgRowsUndone,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Update )(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out][in] */ ULONG __RPC_FAR *pcRows,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgRows,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
END_INTERFACE
} IRowsetUpdateVtbl;
interface IRowsetUpdate
{
CONST_VTBL struct IRowsetUpdateVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetUpdate_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetUpdate_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetUpdate_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetUpdate_DeleteRows(This,hReserved,cRows,rghRows,rgRowStatus) \
(This)->lpVtbl -> DeleteRows(This,hReserved,cRows,rghRows,rgRowStatus)
#define IRowsetUpdate_SetData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> SetData(This,hRow,hAccessor,pData)
#define IRowsetUpdate_InsertRow(This,hReserved,hAccessor,pData,phRow) \
(This)->lpVtbl -> InsertRow(This,hReserved,hAccessor,pData,phRow)
#define IRowsetUpdate_GetOriginalData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetOriginalData(This,hRow,hAccessor,pData)
#define IRowsetUpdate_GetPendingRows(This,hReserved,dwRowStatus,pcPendingRows,prgPendingRows,prgPendingStatus) \
(This)->lpVtbl -> GetPendingRows(This,hReserved,dwRowStatus,pcPendingRows,prgPendingRows,prgPendingStatus)
#define IRowsetUpdate_GetRowStatus(This,hReserved,cRows,rghRows,rgPendingStatus) \
(This)->lpVtbl -> GetRowStatus(This,hReserved,cRows,rghRows,rgPendingStatus)
#define IRowsetUpdate_Undo(This,hReserved,cRows,rghRows,pcRowsUndone,prgRowsUndone,prgRowStatus) \
(This)->lpVtbl -> Undo(This,hReserved,cRows,rghRows,pcRowsUndone,prgRowsUndone,prgRowStatus)
#define IRowsetUpdate_Update(This,hReserved,cRows,rghRows,pcRows,prgRows,prgRowStatus) \
(This)->lpVtbl -> Update(This,hReserved,cRows,rghRows,pcRows,prgRows,prgRowStatus)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetUpdate_GetOriginalData_Proxy(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
void __RPC_STUB IRowsetUpdate_GetOriginalData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetUpdate_GetPendingRows_Proxy(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ DBPENDINGSTATUS dwRowStatus,
/* [out][in] */ ULONG __RPC_FAR *pcPendingRows,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgPendingRows,
/* [size_is][size_is][out] */ DBPENDINGSTATUS __RPC_FAR *__RPC_FAR *prgPendingStatus);
void __RPC_STUB IRowsetUpdate_GetPendingRows_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetUpdate_GetRowStatus_Proxy(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [size_is][out] */ DBPENDINGSTATUS __RPC_FAR rgPendingStatus[ ]);
void __RPC_STUB IRowsetUpdate_GetRowStatus_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetUpdate_Undo_Proxy(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out][in] */ ULONG __RPC_FAR *pcRowsUndone,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgRowsUndone,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
void __RPC_STUB IRowsetUpdate_Undo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetUpdate_Update_Proxy(
IRowsetUpdate __RPC_FAR * This,
/* [in] */ HCHAPTER hReserved,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [out][in] */ ULONG __RPC_FAR *pcRows,
/* [size_is][size_is][out] */ HROW __RPC_FAR *__RPC_FAR *prgRows,
/* [size_is][size_is][out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
void __RPC_STUB IRowsetUpdate_Update_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetUpdate_INTERFACE_DEFINED__ */
#ifndef __IRowsetIdentity_INTERFACE_DEFINED__
#define __IRowsetIdentity_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetIdentity
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IRowsetIdentity;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a09-2a1c-11ce-ade5-00aa0044773d")
IRowsetIdentity : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE IsSameRow(
/* [in] */ HROW hThisRow,
/* [in] */ HROW hThatRow) = 0;
};
#else /* C style interface */
typedef struct IRowsetIdentityVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetIdentity __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetIdentity __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetIdentity __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *IsSameRow )(
IRowsetIdentity __RPC_FAR * This,
/* [in] */ HROW hThisRow,
/* [in] */ HROW hThatRow);
END_INTERFACE
} IRowsetIdentityVtbl;
interface IRowsetIdentity
{
CONST_VTBL struct IRowsetIdentityVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetIdentity_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetIdentity_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetIdentity_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetIdentity_IsSameRow(This,hThisRow,hThatRow) \
(This)->lpVtbl -> IsSameRow(This,hThisRow,hThatRow)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetIdentity_RemoteIsSameRow_Proxy(
IRowsetIdentity __RPC_FAR * This,
/* [in] */ HROW hThisRow,
/* [in] */ HROW hThatRow,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetIdentity_RemoteIsSameRow_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetIdentity_INTERFACE_DEFINED__ */
#ifndef __IRowsetNotify_INTERFACE_DEFINED__
#define __IRowsetNotify_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetNotify
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IRowsetNotify;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a83-2a1c-11ce-ade5-00aa0044773d")
IRowsetNotify : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnFieldChange(
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ HROW hRow,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ ULONG __RPC_FAR rgColumns[ ],
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnRowChange(
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnRowsetChange(
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny) = 0;
};
#else /* C style interface */
typedef struct IRowsetNotifyVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetNotify __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetNotify __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetNotify __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnFieldChange )(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ HROW hRow,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ ULONG __RPC_FAR rgColumns[ ],
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnRowChange )(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnRowsetChange )(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
END_INTERFACE
} IRowsetNotifyVtbl;
interface IRowsetNotify
{
CONST_VTBL struct IRowsetNotifyVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetNotify_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetNotify_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetNotify_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetNotify_OnFieldChange(This,pRowset,hRow,cColumns,rgColumns,eReason,ePhase,fCantDeny) \
(This)->lpVtbl -> OnFieldChange(This,pRowset,hRow,cColumns,rgColumns,eReason,ePhase,fCantDeny)
#define IRowsetNotify_OnRowChange(This,pRowset,cRows,rghRows,eReason,ePhase,fCantDeny) \
(This)->lpVtbl -> OnRowChange(This,pRowset,cRows,rghRows,eReason,ePhase,fCantDeny)
#define IRowsetNotify_OnRowsetChange(This,pRowset,eReason,ePhase,fCantDeny) \
(This)->lpVtbl -> OnRowsetChange(This,pRowset,eReason,ePhase,fCantDeny)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_RemoteOnFieldChange_Proxy(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ HROW hRow,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ ULONG __RPC_FAR *rgColumns,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetNotify_RemoteOnFieldChange_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_RemoteOnRowChange_Proxy(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR *rghRows,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetNotify_RemoteOnRowChange_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_RemoteOnRowsetChange_Proxy(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IRowsetNotify_RemoteOnRowsetChange_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetNotify_INTERFACE_DEFINED__ */
#ifndef __IRowsetIndex_INTERFACE_DEFINED__
#define __IRowsetIndex_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetIndex
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
typedef DWORD DBSEEK;
enum DBSEEKENUM
{ DBSEEK_INVALID = 0,
DBSEEK_FIRSTEQ = 0x1,
DBSEEK_LASTEQ = 0x2,
DBSEEK_AFTEREQ = 0x4,
DBSEEK_AFTER = 0x8,
DBSEEK_BEFOREEQ = 0x10,
DBSEEK_BEFORE = 0x20
};
#define DBSEEK_GE DBSEEK_AFTEREQ
#define DBSEEK_GT DBSEEK_AFTER
#define DBSEEK_LE DBSEEK_BEFOREEQ
#define DBSEEK_LT DBSEEK_BEFORE
typedef DWORD DBRANGE;
enum DBRANGEENUM
{ DBRANGE_INCLUSIVESTART = 0,
DBRANGE_INCLUSIVEEND = 0,
DBRANGE_EXCLUSIVESTART = 0x1,
DBRANGE_EXCLUSIVEEND = 0x2,
DBRANGE_EXCLUDENULLS = 0x4,
DBRANGE_PREFIX = 0x8,
DBRANGE_MATCH = 0x10
};
enum DBRANGEENUM20
{ DBRANGE_MATCH_N_SHIFT = 0x18,
DBRANGE_MATCH_N_MASK = 0xff
};
EXTERN_C const IID IID_IRowsetIndex;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a82-2a1c-11ce-ade5-00aa0044773d")
IRowsetIndex : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetIndexInfo(
/* [out][in] */ ULONG __RPC_FAR *pcKeyColumns,
/* [size_is][size_is][out] */ DBINDEXCOLUMNDESC __RPC_FAR *__RPC_FAR *prgIndexColumnDesc,
/* [out][in] */ ULONG __RPC_FAR *pcIndexProperties,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgIndexProperties) = 0;
virtual HRESULT STDMETHODCALLTYPE Seek(
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cKeyValues,
/* [in] */ void __RPC_FAR *pData,
/* [in] */ DBSEEK dwSeekOptions) = 0;
virtual HRESULT STDMETHODCALLTYPE SetRange(
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cStartKeyColumns,
/* [in] */ void __RPC_FAR *pStartData,
/* [in] */ ULONG cEndKeyColumns,
/* [in] */ void __RPC_FAR *pEndData,
/* [in] */ DBRANGE dwRangeOptions) = 0;
};
#else /* C style interface */
typedef struct IRowsetIndexVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetIndex __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetIndex __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetIndex __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIndexInfo )(
IRowsetIndex __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcKeyColumns,
/* [size_is][size_is][out] */ DBINDEXCOLUMNDESC __RPC_FAR *__RPC_FAR *prgIndexColumnDesc,
/* [out][in] */ ULONG __RPC_FAR *pcIndexProperties,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgIndexProperties);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Seek )(
IRowsetIndex __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cKeyValues,
/* [in] */ void __RPC_FAR *pData,
/* [in] */ DBSEEK dwSeekOptions);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetRange )(
IRowsetIndex __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cStartKeyColumns,
/* [in] */ void __RPC_FAR *pStartData,
/* [in] */ ULONG cEndKeyColumns,
/* [in] */ void __RPC_FAR *pEndData,
/* [in] */ DBRANGE dwRangeOptions);
END_INTERFACE
} IRowsetIndexVtbl;
interface IRowsetIndex
{
CONST_VTBL struct IRowsetIndexVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetIndex_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetIndex_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetIndex_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetIndex_GetIndexInfo(This,pcKeyColumns,prgIndexColumnDesc,pcIndexProperties,prgIndexProperties) \
(This)->lpVtbl -> GetIndexInfo(This,pcKeyColumns,prgIndexColumnDesc,pcIndexProperties,prgIndexProperties)
#define IRowsetIndex_Seek(This,hAccessor,cKeyValues,pData,dwSeekOptions) \
(This)->lpVtbl -> Seek(This,hAccessor,cKeyValues,pData,dwSeekOptions)
#define IRowsetIndex_SetRange(This,hAccessor,cStartKeyColumns,pStartData,cEndKeyColumns,pEndData,dwRangeOptions) \
(This)->lpVtbl -> SetRange(This,hAccessor,cStartKeyColumns,pStartData,cEndKeyColumns,pEndData,dwRangeOptions)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetIndex_GetIndexInfo_Proxy(
IRowsetIndex __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcKeyColumns,
/* [size_is][size_is][out] */ DBINDEXCOLUMNDESC __RPC_FAR *__RPC_FAR *prgIndexColumnDesc,
/* [out][in] */ ULONG __RPC_FAR *pcIndexProperties,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgIndexProperties);
void __RPC_STUB IRowsetIndex_GetIndexInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetIndex_Seek_Proxy(
IRowsetIndex __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cKeyValues,
/* [in] */ void __RPC_FAR *pData,
/* [in] */ DBSEEK dwSeekOptions);
void __RPC_STUB IRowsetIndex_Seek_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetIndex_SetRange_Proxy(
IRowsetIndex __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cStartKeyColumns,
/* [in] */ void __RPC_FAR *pStartData,
/* [in] */ ULONG cEndKeyColumns,
/* [in] */ void __RPC_FAR *pEndData,
/* [in] */ DBRANGE dwRangeOptions);
void __RPC_STUB IRowsetIndex_SetRange_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetIndex_INTERFACE_DEFINED__ */
#ifndef __ICommand_INTERFACE_DEFINED__
#define __ICommand_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICommand
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ICommand;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a63-2a1c-11ce-ade5-00aa0044773d")
ICommand : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Cancel( void) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Execute(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [out][in] */ DBPARAMS __RPC_FAR *pParams,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetDBSession(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession) = 0;
};
#else /* C style interface */
typedef struct ICommandVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICommand __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICommand __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICommand __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Cancel )(
ICommand __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Execute )(
ICommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [out][in] */ DBPARAMS __RPC_FAR *pParams,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetDBSession )(
ICommand __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession);
END_INTERFACE
} ICommandVtbl;
interface ICommand
{
CONST_VTBL struct ICommandVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICommand_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICommand_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICommand_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICommand_Cancel(This) \
(This)->lpVtbl -> Cancel(This)
#define ICommand_Execute(This,pUnkOuter,riid,pParams,pcRowsAffected,ppRowset) \
(This)->lpVtbl -> Execute(This,pUnkOuter,riid,pParams,pcRowsAffected,ppRowset)
#define ICommand_GetDBSession(This,riid,ppSession) \
(This)->lpVtbl -> GetDBSession(This,riid,ppSession)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommand_RemoteCancel_Proxy(
ICommand __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommand_RemoteCancel_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommand_RemoteExecute_Proxy(
ICommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cParamSets,
/* [in] */ ULONG cbData,
/* [size_is][unique][out][in] */ BYTE __RPC_FAR *pbData,
/* [unique][out][in] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommand_RemoteExecute_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommand_RemoteGetDBSession_Proxy(
ICommand __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommand_RemoteGetDBSession_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICommand_INTERFACE_DEFINED__ */
#ifndef __IMultipleResults_INTERFACE_DEFINED__
#define __IMultipleResults_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IMultipleResults
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IMultipleResults;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a90-2a1c-11ce-ade5-00aa0044773d")
IMultipleResults : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetResult(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LONG reserved,
/* [in] */ REFIID riid,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
};
#else /* C style interface */
typedef struct IMultipleResultsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IMultipleResults __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IMultipleResults __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IMultipleResults __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetResult )(
IMultipleResults __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LONG reserved,
/* [in] */ REFIID riid,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
END_INTERFACE
} IMultipleResultsVtbl;
interface IMultipleResults
{
CONST_VTBL struct IMultipleResultsVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IMultipleResults_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IMultipleResults_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IMultipleResults_Release(This) \
(This)->lpVtbl -> Release(This)
#define IMultipleResults_GetResult(This,pUnkOuter,reserved,riid,pcRowsAffected,ppRowset) \
(This)->lpVtbl -> GetResult(This,pUnkOuter,reserved,riid,pcRowsAffected,ppRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IMultipleResults_RemoteGetResult_Proxy(
IMultipleResults __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LONG reserved,
/* [in] */ REFIID riid,
/* [unique][out][in] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IMultipleResults_RemoteGetResult_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IMultipleResults_INTERFACE_DEFINED__ */
#ifndef __IConvertType_INTERFACE_DEFINED__
#define __IConvertType_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IConvertType
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef DWORD DBCONVERTFLAGS;
enum DBCONVERTFLAGSENUM
{ DBCONVERTFLAGS_COLUMN = 0,
DBCONVERTFLAGS_PARAMETER = 0x1
};
enum DBCONVERTFLAGSENUM20
{ DBCONVERTFLAGS_ISLONG = 0x2,
DBCONVERTFLAGS_ISFIXEDLENGTH = 0x4,
DBCONVERTFLAGS_FROMVARIANT = 0x8
};
EXTERN_C const IID IID_IConvertType;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a88-2a1c-11ce-ade5-00aa0044773d")
IConvertType : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CanConvert(
/* [in] */ DBTYPE wFromType,
/* [in] */ DBTYPE wToType,
/* [in] */ DBCONVERTFLAGS dwConvertFlags) = 0;
};
#else /* C style interface */
typedef struct IConvertTypeVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IConvertType __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IConvertType __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IConvertType __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CanConvert )(
IConvertType __RPC_FAR * This,
/* [in] */ DBTYPE wFromType,
/* [in] */ DBTYPE wToType,
/* [in] */ DBCONVERTFLAGS dwConvertFlags);
END_INTERFACE
} IConvertTypeVtbl;
interface IConvertType
{
CONST_VTBL struct IConvertTypeVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IConvertType_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IConvertType_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IConvertType_Release(This) \
(This)->lpVtbl -> Release(This)
#define IConvertType_CanConvert(This,wFromType,wToType,dwConvertFlags) \
(This)->lpVtbl -> CanConvert(This,wFromType,wToType,dwConvertFlags)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IConvertType_RemoteCanConvert_Proxy(
IConvertType __RPC_FAR * This,
/* [in] */ DBTYPE wFromType,
/* [in] */ DBTYPE wToType,
/* [in] */ DBCONVERTFLAGS dwConvertFlags,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IConvertType_RemoteCanConvert_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IConvertType_INTERFACE_DEFINED__ */
#ifndef __ICommandPrepare_INTERFACE_DEFINED__
#define __ICommandPrepare_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICommandPrepare
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ICommandPrepare;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a26-2a1c-11ce-ade5-00aa0044773d")
ICommandPrepare : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Prepare(
/* [in] */ ULONG cExpectedRuns) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Unprepare( void) = 0;
};
#else /* C style interface */
typedef struct ICommandPrepareVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICommandPrepare __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICommandPrepare __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICommandPrepare __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Prepare )(
ICommandPrepare __RPC_FAR * This,
/* [in] */ ULONG cExpectedRuns);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Unprepare )(
ICommandPrepare __RPC_FAR * This);
END_INTERFACE
} ICommandPrepareVtbl;
interface ICommandPrepare
{
CONST_VTBL struct ICommandPrepareVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICommandPrepare_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICommandPrepare_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICommandPrepare_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICommandPrepare_Prepare(This,cExpectedRuns) \
(This)->lpVtbl -> Prepare(This,cExpectedRuns)
#define ICommandPrepare_Unprepare(This) \
(This)->lpVtbl -> Unprepare(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandPrepare_RemotePrepare_Proxy(
ICommandPrepare __RPC_FAR * This,
/* [in] */ ULONG cExpectedRuns,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandPrepare_RemotePrepare_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandPrepare_RemoteUnprepare_Proxy(
ICommandPrepare __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandPrepare_RemoteUnprepare_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICommandPrepare_INTERFACE_DEFINED__ */
#ifndef __ICommandProperties_INTERFACE_DEFINED__
#define __ICommandProperties_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICommandProperties
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ICommandProperties;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a79-2a1c-11ce-ade5-00aa0044773d")
ICommandProperties : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetProperties(
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetProperties(
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
};
#else /* C style interface */
typedef struct ICommandPropertiesVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICommandProperties __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICommandProperties __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICommandProperties __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetProperties )(
ICommandProperties __RPC_FAR * This,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetProperties )(
ICommandProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
END_INTERFACE
} ICommandPropertiesVtbl;
interface ICommandProperties
{
CONST_VTBL struct ICommandPropertiesVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICommandProperties_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICommandProperties_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICommandProperties_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICommandProperties_GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets) \
(This)->lpVtbl -> GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets)
#define ICommandProperties_SetProperties(This,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> SetProperties(This,cPropertySets,rgPropertySets)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandProperties_RemoteGetProperties_Proxy(
ICommandProperties __RPC_FAR * This,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandProperties_RemoteGetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandProperties_RemoteSetProperties_Proxy(
ICommandProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandProperties_RemoteSetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICommandProperties_INTERFACE_DEFINED__ */
#ifndef __ICommandText_INTERFACE_DEFINED__
#define __ICommandText_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICommandText
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ICommandText;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a27-2a1c-11ce-ade5-00aa0044773d")
ICommandText : public ICommand
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetCommandText(
/* [out][in] */ GUID __RPC_FAR *pguidDialect,
/* [out] */ LPOLESTR __RPC_FAR *ppwszCommand) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetCommandText(
/* [in] */ REFGUID rguidDialect,
/* [unique][in] */ LPCOLESTR pwszCommand) = 0;
};
#else /* C style interface */
typedef struct ICommandTextVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICommandText __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICommandText __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICommandText __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Cancel )(
ICommandText __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Execute )(
ICommandText __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [out][in] */ DBPARAMS __RPC_FAR *pParams,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetDBSession )(
ICommandText __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetCommandText )(
ICommandText __RPC_FAR * This,
/* [out][in] */ GUID __RPC_FAR *pguidDialect,
/* [out] */ LPOLESTR __RPC_FAR *ppwszCommand);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetCommandText )(
ICommandText __RPC_FAR * This,
/* [in] */ REFGUID rguidDialect,
/* [unique][in] */ LPCOLESTR pwszCommand);
END_INTERFACE
} ICommandTextVtbl;
interface ICommandText
{
CONST_VTBL struct ICommandTextVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICommandText_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICommandText_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICommandText_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICommandText_Cancel(This) \
(This)->lpVtbl -> Cancel(This)
#define ICommandText_Execute(This,pUnkOuter,riid,pParams,pcRowsAffected,ppRowset) \
(This)->lpVtbl -> Execute(This,pUnkOuter,riid,pParams,pcRowsAffected,ppRowset)
#define ICommandText_GetDBSession(This,riid,ppSession) \
(This)->lpVtbl -> GetDBSession(This,riid,ppSession)
#define ICommandText_GetCommandText(This,pguidDialect,ppwszCommand) \
(This)->lpVtbl -> GetCommandText(This,pguidDialect,ppwszCommand)
#define ICommandText_SetCommandText(This,rguidDialect,pwszCommand) \
(This)->lpVtbl -> SetCommandText(This,rguidDialect,pwszCommand)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandText_RemoteGetCommandText_Proxy(
ICommandText __RPC_FAR * This,
/* [unique][out][in] */ GUID __RPC_FAR *pguidDialect,
/* [out] */ LPOLESTR __RPC_FAR *ppwszCommand,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandText_RemoteGetCommandText_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandText_RemoteSetCommandText_Proxy(
ICommandText __RPC_FAR * This,
/* [in] */ REFGUID rguidDialect,
/* [unique][in] */ LPCOLESTR pwszCommand,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandText_RemoteSetCommandText_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICommandText_INTERFACE_DEFINED__ */
#ifndef __ICommandWithParameters_INTERFACE_DEFINED__
#define __ICommandWithParameters_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICommandWithParameters
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef struct tagDBPARAMBINDINFO
{
LPOLESTR pwszDataSourceType;
LPOLESTR pwszName;
ULONG ulParamSize;
DBPARAMFLAGS dwFlags;
BYTE bPrecision;
BYTE bScale;
} DBPARAMBINDINFO;
EXTERN_C const IID IID_ICommandWithParameters;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a64-2a1c-11ce-ade5-00aa0044773d")
ICommandWithParameters : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetParameterInfo(
/* [out][in] */ ULONG __RPC_FAR *pcParams,
/* [size_is][size_is][out] */ DBPARAMINFO __RPC_FAR *__RPC_FAR *prgParamInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppNamesBuffer) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE MapParameterNames(
/* [in] */ ULONG cParamNames,
/* [size_is][in] */ const OLECHAR __RPC_FAR *__RPC_FAR rgParamNames[ ],
/* [size_is][out] */ LONG __RPC_FAR rgParamOrdinals[ ]) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetParameterInfo(
/* [in] */ ULONG cParams,
/* [size_is][unique][in] */ const ULONG __RPC_FAR rgParamOrdinals[ ],
/* [size_is][unique][in] */ const DBPARAMBINDINFO __RPC_FAR rgParamBindInfo[ ]) = 0;
};
#else /* C style interface */
typedef struct ICommandWithParametersVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICommandWithParameters __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICommandWithParameters __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetParameterInfo )(
ICommandWithParameters __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcParams,
/* [size_is][size_is][out] */ DBPARAMINFO __RPC_FAR *__RPC_FAR *prgParamInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppNamesBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *MapParameterNames )(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParamNames,
/* [size_is][in] */ const OLECHAR __RPC_FAR *__RPC_FAR rgParamNames[ ],
/* [size_is][out] */ LONG __RPC_FAR rgParamOrdinals[ ]);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetParameterInfo )(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParams,
/* [size_is][unique][in] */ const ULONG __RPC_FAR rgParamOrdinals[ ],
/* [size_is][unique][in] */ const DBPARAMBINDINFO __RPC_FAR rgParamBindInfo[ ]);
END_INTERFACE
} ICommandWithParametersVtbl;
interface ICommandWithParameters
{
CONST_VTBL struct ICommandWithParametersVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICommandWithParameters_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICommandWithParameters_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICommandWithParameters_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICommandWithParameters_GetParameterInfo(This,pcParams,prgParamInfo,ppNamesBuffer) \
(This)->lpVtbl -> GetParameterInfo(This,pcParams,prgParamInfo,ppNamesBuffer)
#define ICommandWithParameters_MapParameterNames(This,cParamNames,rgParamNames,rgParamOrdinals) \
(This)->lpVtbl -> MapParameterNames(This,cParamNames,rgParamNames,rgParamOrdinals)
#define ICommandWithParameters_SetParameterInfo(This,cParams,rgParamOrdinals,rgParamBindInfo) \
(This)->lpVtbl -> SetParameterInfo(This,cParams,rgParamOrdinals,rgParamBindInfo)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_RemoteGetParameterInfo_Proxy(
ICommandWithParameters __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcParams,
/* [size_is][size_is][out] */ DBPARAMINFO __RPC_FAR *__RPC_FAR *prgParamInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgNameOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbNamesBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppNamesBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandWithParameters_RemoteGetParameterInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_RemoteMapParameterNames_Proxy(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParamNames,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgParamNames,
/* [size_is][out] */ LONG __RPC_FAR *rgParamOrdinals,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandWithParameters_RemoteMapParameterNames_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_RemoteSetParameterInfo_Proxy(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParams,
/* [size_is][unique][in] */ const ULONG __RPC_FAR *rgParamOrdinals,
/* [size_is][unique][in] */ const DBPARAMBINDINFO __RPC_FAR *rgParamBindInfo,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ICommandWithParameters_RemoteSetParameterInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICommandWithParameters_INTERFACE_DEFINED__ */
#ifndef __IColumnsRowset_INTERFACE_DEFINED__
#define __IColumnsRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IColumnsRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IColumnsRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a10-2a1c-11ce-ade5-00aa0044773d")
IColumnsRowset : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetAvailableColumns(
/* [out][in] */ ULONG __RPC_FAR *pcOptColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgOptColumns) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetColumnsRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG cOptColumns,
/* [size_is][in] */ const DBID __RPC_FAR rgOptColumns[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppColRowset) = 0;
};
#else /* C style interface */
typedef struct IColumnsRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IColumnsRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IColumnsRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IColumnsRowset __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetAvailableColumns )(
IColumnsRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcOptColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgOptColumns);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetColumnsRowset )(
IColumnsRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG cOptColumns,
/* [size_is][in] */ const DBID __RPC_FAR rgOptColumns[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppColRowset);
END_INTERFACE
} IColumnsRowsetVtbl;
interface IColumnsRowset
{
CONST_VTBL struct IColumnsRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IColumnsRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IColumnsRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IColumnsRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IColumnsRowset_GetAvailableColumns(This,pcOptColumns,prgOptColumns) \
(This)->lpVtbl -> GetAvailableColumns(This,pcOptColumns,prgOptColumns)
#define IColumnsRowset_GetColumnsRowset(This,pUnkOuter,cOptColumns,rgOptColumns,riid,cPropertySets,rgPropertySets,ppColRowset) \
(This)->lpVtbl -> GetColumnsRowset(This,pUnkOuter,cOptColumns,rgOptColumns,riid,cPropertySets,rgPropertySets,ppColRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsRowset_RemoteGetAvailableColumns_Proxy(
IColumnsRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcOptColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgOptColumns,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IColumnsRowset_RemoteGetAvailableColumns_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsRowset_RemoteGetColumnsRowset_Proxy(
IColumnsRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG cOptColumns,
/* [size_is][unique][in] */ const DBID __RPC_FAR *rgOptColumns,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppColRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IColumnsRowset_RemoteGetColumnsRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IColumnsRowset_INTERFACE_DEFINED__ */
#ifndef __IColumnsInfo_INTERFACE_DEFINED__
#define __IColumnsInfo_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IColumnsInfo
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IColumnsInfo;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a11-2a1c-11ce-ade5-00aa0044773d")
IColumnsInfo : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetColumnInfo(
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE MapColumnIDs(
/* [in] */ ULONG cColumnIDs,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgColumns[ ]) = 0;
};
#else /* C style interface */
typedef struct IColumnsInfoVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IColumnsInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IColumnsInfo __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IColumnsInfo __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetColumnInfo )(
IColumnsInfo __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *MapColumnIDs )(
IColumnsInfo __RPC_FAR * This,
/* [in] */ ULONG cColumnIDs,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgColumns[ ]);
END_INTERFACE
} IColumnsInfoVtbl;
interface IColumnsInfo
{
CONST_VTBL struct IColumnsInfoVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IColumnsInfo_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IColumnsInfo_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IColumnsInfo_Release(This) \
(This)->lpVtbl -> Release(This)
#define IColumnsInfo_GetColumnInfo(This,pcColumns,prgInfo,ppStringsBuffer) \
(This)->lpVtbl -> GetColumnInfo(This,pcColumns,prgInfo,ppStringsBuffer)
#define IColumnsInfo_MapColumnIDs(This,cColumnIDs,rgColumnIDs,rgColumns) \
(This)->lpVtbl -> MapColumnIDs(This,cColumnIDs,rgColumnIDs,rgColumns)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsInfo_RemoteGetColumnInfo_Proxy(
IColumnsInfo __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgNameOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgcolumnidOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IColumnsInfo_RemoteGetColumnInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsInfo_RemoteMapColumnIDs_Proxy(
IColumnsInfo __RPC_FAR * This,
/* [in] */ ULONG cColumnIDs,
/* [size_is][in] */ const DBID __RPC_FAR *rgColumnIDs,
/* [size_is][out] */ ULONG __RPC_FAR *rgColumns,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IColumnsInfo_RemoteMapColumnIDs_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IColumnsInfo_INTERFACE_DEFINED__ */
#ifndef __IDBCreateCommand_INTERFACE_DEFINED__
#define __IDBCreateCommand_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBCreateCommand
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBCreateCommand;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a1d-2a1c-11ce-ade5-00aa0044773d")
IDBCreateCommand : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateCommand(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppCommand) = 0;
};
#else /* C style interface */
typedef struct IDBCreateCommandVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBCreateCommand __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBCreateCommand __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBCreateCommand __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateCommand )(
IDBCreateCommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppCommand);
END_INTERFACE
} IDBCreateCommandVtbl;
interface IDBCreateCommand
{
CONST_VTBL struct IDBCreateCommandVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBCreateCommand_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBCreateCommand_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBCreateCommand_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBCreateCommand_CreateCommand(This,pUnkOuter,riid,ppCommand) \
(This)->lpVtbl -> CreateCommand(This,pUnkOuter,riid,ppCommand)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBCreateCommand_RemoteCreateCommand_Proxy(
IDBCreateCommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppCommand,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBCreateCommand_RemoteCreateCommand_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBCreateCommand_INTERFACE_DEFINED__ */
#ifndef __IDBCreateSession_INTERFACE_DEFINED__
#define __IDBCreateSession_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBCreateSession
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBCreateSession;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a5d-2a1c-11ce-ade5-00aa0044773d")
IDBCreateSession : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateSession(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession) = 0;
};
#else /* C style interface */
typedef struct IDBCreateSessionVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBCreateSession __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBCreateSession __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBCreateSession __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateSession )(
IDBCreateSession __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession);
END_INTERFACE
} IDBCreateSessionVtbl;
interface IDBCreateSession
{
CONST_VTBL struct IDBCreateSessionVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBCreateSession_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBCreateSession_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBCreateSession_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBCreateSession_CreateSession(This,pUnkOuter,riid,ppDBSession) \
(This)->lpVtbl -> CreateSession(This,pUnkOuter,riid,ppDBSession)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBCreateSession_RemoteCreateSession_Proxy(
IDBCreateSession __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBCreateSession_RemoteCreateSession_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBCreateSession_INTERFACE_DEFINED__ */
#ifndef __ISourcesRowset_INTERFACE_DEFINED__
#define __ISourcesRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ISourcesRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef DWORD DBSOURCETYPE;
enum DBSOURCETYPEENUM
{ DBSOURCETYPE_DATASOURCE = 1,
DBSOURCETYPE_ENUMERATOR = 2
};
enum DBSOURCETYPEENUM20
{ DBSOURCETYPE_DATASOURCE_TDP = 1,
DBSOURCETYPE_DATASOURCE_MDP = 3
};
EXTERN_C const IID IID_ISourcesRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a1e-2a1c-11ce-ade5-00aa0044773d")
ISourcesRowset : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSourcesRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgProperties[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSourcesRowset) = 0;
};
#else /* C style interface */
typedef struct ISourcesRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ISourcesRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ISourcesRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ISourcesRowset __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSourcesRowset )(
ISourcesRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgProperties[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSourcesRowset);
END_INTERFACE
} ISourcesRowsetVtbl;
interface ISourcesRowset
{
CONST_VTBL struct ISourcesRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ISourcesRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ISourcesRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ISourcesRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define ISourcesRowset_GetSourcesRowset(This,pUnkOuter,riid,cPropertySets,rgProperties,ppSourcesRowset) \
(This)->lpVtbl -> GetSourcesRowset(This,pUnkOuter,riid,cPropertySets,rgProperties,ppSourcesRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISourcesRowset_RemoteGetSourcesRowset_Proxy(
ISourcesRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgProperties,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSourcesRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ISourcesRowset_RemoteGetSourcesRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ISourcesRowset_INTERFACE_DEFINED__ */
#ifndef __IDBProperties_INTERFACE_DEFINED__
#define __IDBProperties_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBProperties
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBProperties;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a8a-2a1c-11ce-ade5-00aa0044773d")
IDBProperties : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetProperties(
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetPropertyInfo(
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetProperties(
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
};
#else /* C style interface */
typedef struct IDBPropertiesVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBProperties __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBProperties __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBProperties __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetProperties )(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetPropertyInfo )(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetProperties )(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
END_INTERFACE
} IDBPropertiesVtbl;
interface IDBProperties
{
CONST_VTBL struct IDBPropertiesVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBProperties_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBProperties_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBProperties_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBProperties_GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets) \
(This)->lpVtbl -> GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets)
#define IDBProperties_GetPropertyInfo(This,cPropertyIDSets,rgPropertyIDSets,pcPropertyInfoSets,prgPropertyInfoSets,ppDescBuffer) \
(This)->lpVtbl -> GetPropertyInfo(This,cPropertyIDSets,rgPropertyIDSets,pcPropertyInfoSets,prgPropertyInfoSets,ppDescBuffer)
#define IDBProperties_SetProperties(This,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> SetProperties(This,cPropertySets,rgPropertySets)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBProperties_RemoteGetProperties_Proxy(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBProperties_RemoteGetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBProperties_RemoteGetPropertyInfo_Proxy(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out][in] */ ULONG __RPC_FAR *pcOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgDescOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbDescBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBProperties_RemoteGetPropertyInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBProperties_RemoteSetProperties_Proxy(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBProperties_RemoteSetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBProperties_INTERFACE_DEFINED__ */
#ifndef __IDBInitialize_INTERFACE_DEFINED__
#define __IDBInitialize_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBInitialize
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBInitialize;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a8b-2a1c-11ce-ade5-00aa0044773d")
IDBInitialize : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Initialize( void) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Uninitialize( void) = 0;
};
#else /* C style interface */
typedef struct IDBInitializeVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBInitialize __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBInitialize __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBInitialize __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Initialize )(
IDBInitialize __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Uninitialize )(
IDBInitialize __RPC_FAR * This);
END_INTERFACE
} IDBInitializeVtbl;
interface IDBInitialize
{
CONST_VTBL struct IDBInitializeVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBInitialize_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBInitialize_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBInitialize_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBInitialize_Initialize(This) \
(This)->lpVtbl -> Initialize(This)
#define IDBInitialize_Uninitialize(This) \
(This)->lpVtbl -> Uninitialize(This)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInitialize_RemoteInitialize_Proxy(
IDBInitialize __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBInitialize_RemoteInitialize_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInitialize_RemoteUninitialize_Proxy(
IDBInitialize __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBInitialize_RemoteUninitialize_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBInitialize_INTERFACE_DEFINED__ */
#ifndef __IDBInfo_INTERFACE_DEFINED__
#define __IDBInfo_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBInfo
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef DWORD DBLITERAL;
enum DBLITERALENUM
{ DBLITERAL_INVALID = 0,
DBLITERAL_BINARY_LITERAL = 1,
DBLITERAL_CATALOG_NAME = 2,
DBLITERAL_CATALOG_SEPARATOR = 3,
DBLITERAL_CHAR_LITERAL = 4,
DBLITERAL_COLUMN_ALIAS = 5,
DBLITERAL_COLUMN_NAME = 6,
DBLITERAL_CORRELATION_NAME = 7,
DBLITERAL_CURSOR_NAME = 8,
DBLITERAL_ESCAPE_PERCENT = 9,
DBLITERAL_ESCAPE_UNDERSCORE = 10,
DBLITERAL_INDEX_NAME = 11,
DBLITERAL_LIKE_PERCENT = 12,
DBLITERAL_LIKE_UNDERSCORE = 13,
DBLITERAL_PROCEDURE_NAME = 14,
DBLITERAL_QUOTE = 15,
DBLITERAL_SCHEMA_NAME = 16,
DBLITERAL_TABLE_NAME = 17,
DBLITERAL_TEXT_COMMAND = 18,
DBLITERAL_USER_NAME = 19,
DBLITERAL_VIEW_NAME = 20
};
#define DBLITERAL_QUOTE_PREFIX DBLITERAL_QUOTE
enum DBLITERALENUM20
{ DBLITERAL_CUBE_NAME = 21,
DBLITERAL_DIMENSION_NAME = 22,
DBLITERAL_HIERARCHY_NAME = 23,
DBLITERAL_LEVEL_NAME = 24,
DBLITERAL_MEMBER_NAME = 25,
DBLITERAL_PROPERTY_NAME = 26,
DBLITERAL_SCHEMA_SEPARATOR = 27,
DBLITERAL_QUOTE_SUFFIX = 28
};
#define DBLITERAL_ESCAPE_PERCENT_PREFIX DBLITERAL_ESCAPE_PERCENT
#define DBLITERAL_ESCAPE_UNDERSCORE_PREFIX DBLITERAL_ESCAPE_UNDERSCORE
enum DBLITERALENUM21
{ DBLITERAL_ESCAPE_PERCENT_SUFFIX = 29,
DBLITERAL_ESCAPE_UNDERSCORE_SUFFIX = 30
};
typedef struct tagDBLITERALINFO
{
LPOLESTR pwszLiteralValue;
LPOLESTR pwszInvalidChars;
LPOLESTR pwszInvalidStartingChars;
DBLITERAL lt;
BOOL fSupported;
ULONG cchMaxLen;
} DBLITERALINFO;
EXTERN_C const IID IID_IDBInfo;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a89-2a1c-11ce-ade5-00aa0044773d")
IDBInfo : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetKeywords(
/* [out] */ LPOLESTR __RPC_FAR *ppwszKeywords) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetLiteralInfo(
/* [in] */ ULONG cLiterals,
/* [size_is][in] */ const DBLITERAL __RPC_FAR rgLiterals[ ],
/* [out][in] */ ULONG __RPC_FAR *pcLiteralInfo,
/* [size_is][size_is][out] */ DBLITERALINFO __RPC_FAR *__RPC_FAR *prgLiteralInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppCharBuffer) = 0;
};
#else /* C style interface */
typedef struct IDBInfoVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBInfo __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBInfo __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetKeywords )(
IDBInfo __RPC_FAR * This,
/* [out] */ LPOLESTR __RPC_FAR *ppwszKeywords);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetLiteralInfo )(
IDBInfo __RPC_FAR * This,
/* [in] */ ULONG cLiterals,
/* [size_is][in] */ const DBLITERAL __RPC_FAR rgLiterals[ ],
/* [out][in] */ ULONG __RPC_FAR *pcLiteralInfo,
/* [size_is][size_is][out] */ DBLITERALINFO __RPC_FAR *__RPC_FAR *prgLiteralInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppCharBuffer);
END_INTERFACE
} IDBInfoVtbl;
interface IDBInfo
{
CONST_VTBL struct IDBInfoVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBInfo_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBInfo_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBInfo_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBInfo_GetKeywords(This,ppwszKeywords) \
(This)->lpVtbl -> GetKeywords(This,ppwszKeywords)
#define IDBInfo_GetLiteralInfo(This,cLiterals,rgLiterals,pcLiteralInfo,prgLiteralInfo,ppCharBuffer) \
(This)->lpVtbl -> GetLiteralInfo(This,cLiterals,rgLiterals,pcLiteralInfo,prgLiteralInfo,ppCharBuffer)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInfo_RemoteGetKeywords_Proxy(
IDBInfo __RPC_FAR * This,
/* [unique][out][in] */ LPOLESTR __RPC_FAR *ppwszKeywords,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBInfo_RemoteGetKeywords_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInfo_RemoteGetLiteralInfo_Proxy(
IDBInfo __RPC_FAR * This,
/* [in] */ ULONG cLiterals,
/* [size_is][unique][in] */ const DBLITERAL __RPC_FAR *rgLiterals,
/* [out][in] */ ULONG __RPC_FAR *pcLiteralInfo,
/* [size_is][size_is][out] */ DBLITERALINFO __RPC_FAR *__RPC_FAR *prgLiteralInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgLVOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgICOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgISCOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbCharBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppCharBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBInfo_RemoteGetLiteralInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBInfo_INTERFACE_DEFINED__ */
#ifndef __IDBDataSourceAdmin_INTERFACE_DEFINED__
#define __IDBDataSourceAdmin_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBDataSourceAdmin
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBDataSourceAdmin;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a7a-2a1c-11ce-ade5-00aa0044773d")
IDBDataSourceAdmin : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateDataSource(
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE DestroyDataSource( void) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetCreationProperties(
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ModifyDataSource(
/* [in] */ ULONG cPropertySets,
/* [size_is][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
};
#else /* C style interface */
typedef struct IDBDataSourceAdminVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBDataSourceAdmin __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBDataSourceAdmin __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateDataSource )(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DestroyDataSource )(
IDBDataSourceAdmin __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetCreationProperties )(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ModifyDataSource )(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
END_INTERFACE
} IDBDataSourceAdminVtbl;
interface IDBDataSourceAdmin
{
CONST_VTBL struct IDBDataSourceAdminVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBDataSourceAdmin_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBDataSourceAdmin_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBDataSourceAdmin_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBDataSourceAdmin_CreateDataSource(This,cPropertySets,rgPropertySets,pUnkOuter,riid,ppDBSession) \
(This)->lpVtbl -> CreateDataSource(This,cPropertySets,rgPropertySets,pUnkOuter,riid,ppDBSession)
#define IDBDataSourceAdmin_DestroyDataSource(This) \
(This)->lpVtbl -> DestroyDataSource(This)
#define IDBDataSourceAdmin_GetCreationProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertyInfoSets,prgPropertyInfoSets,ppDescBuffer) \
(This)->lpVtbl -> GetCreationProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertyInfoSets,prgPropertyInfoSets,ppDescBuffer)
#define IDBDataSourceAdmin_ModifyDataSource(This,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> ModifyDataSource(This,cPropertySets,rgPropertySets)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_RemoteCreateDataSource_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBDataSourceAdmin_RemoteCreateDataSource_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_RemoteDestroyDataSource_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBDataSourceAdmin_RemoteDestroyDataSource_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_RemoteGetCreationProperties_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out][in] */ ULONG __RPC_FAR *pcOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgDescOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbDescBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBDataSourceAdmin_RemoteGetCreationProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_RemoteModifyDataSource_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBDataSourceAdmin_RemoteModifyDataSource_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBDataSourceAdmin_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0192
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
extern RPC_IF_HANDLE __MIDL_itf_oledb_0192_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0192_v0_0_s_ifspec;
#ifndef __IDBAsynchNotify_INTERFACE_DEFINED__
#define __IDBAsynchNotify_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBAsynchNotify
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBAsynchNotify;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a96-2a1c-11ce-ade5-00aa0044773d")
IDBAsynchNotify : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnLowResource(
/* [in] */ DWORD dwReserved) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnProgress(
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ ULONG ulProgress,
/* [in] */ ULONG ulProgressMax,
/* [in] */ DBASYNCHPHASE eAsynchPhase,
/* [in] */ LPOLESTR pwszStatusText) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OnStop(
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ HRESULT hrStatus,
/* [in] */ LPOLESTR pwszStatusText) = 0;
};
#else /* C style interface */
typedef struct IDBAsynchNotifyVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBAsynchNotify __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBAsynchNotify __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnLowResource )(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ DWORD dwReserved);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnProgress )(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ ULONG ulProgress,
/* [in] */ ULONG ulProgressMax,
/* [in] */ DBASYNCHPHASE eAsynchPhase,
/* [in] */ LPOLESTR pwszStatusText);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OnStop )(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ HRESULT hrStatus,
/* [in] */ LPOLESTR pwszStatusText);
END_INTERFACE
} IDBAsynchNotifyVtbl;
interface IDBAsynchNotify
{
CONST_VTBL struct IDBAsynchNotifyVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBAsynchNotify_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBAsynchNotify_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBAsynchNotify_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBAsynchNotify_OnLowResource(This,dwReserved) \
(This)->lpVtbl -> OnLowResource(This,dwReserved)
#define IDBAsynchNotify_OnProgress(This,hChapter,eOperation,ulProgress,ulProgressMax,eAsynchPhase,pwszStatusText) \
(This)->lpVtbl -> OnProgress(This,hChapter,eOperation,ulProgress,ulProgressMax,eAsynchPhase,pwszStatusText)
#define IDBAsynchNotify_OnStop(This,hChapter,eOperation,hrStatus,pwszStatusText) \
(This)->lpVtbl -> OnStop(This,hChapter,eOperation,hrStatus,pwszStatusText)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_RemoteOnLowResource_Proxy(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ DWORD dwReserved,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBAsynchNotify_RemoteOnLowResource_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_RemoteOnProgress_Proxy(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ ULONG ulProgress,
/* [in] */ ULONG ulProgressMax,
/* [in] */ DBASYNCHPHASE eAsynchPhase,
/* [in] */ LPOLESTR pwszStatusText,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBAsynchNotify_RemoteOnProgress_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_RemoteOnStop_Proxy(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ HRESULT hrStatus,
/* [in] */ LPOLESTR pwszStatusText,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBAsynchNotify_RemoteOnStop_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBAsynchNotify_INTERFACE_DEFINED__ */
#ifndef __IDBAsynchStatus_INTERFACE_DEFINED__
#define __IDBAsynchStatus_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBAsynchStatus
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBAsynchStatus;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a95-2a1c-11ce-ade5-00aa0044773d")
IDBAsynchStatus : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Abort(
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetStatus(
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ ULONG __RPC_FAR *pulProgress,
/* [out] */ ULONG __RPC_FAR *pulProgressMax,
/* [out] */ DBASYNCHPHASE __RPC_FAR *peAsynchPhase,
/* [out] */ LPOLESTR __RPC_FAR *ppwszStatusText) = 0;
};
#else /* C style interface */
typedef struct IDBAsynchStatusVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBAsynchStatus __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBAsynchStatus __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Abort )(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetStatus )(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ ULONG __RPC_FAR *pulProgress,
/* [out] */ ULONG __RPC_FAR *pulProgressMax,
/* [out] */ DBASYNCHPHASE __RPC_FAR *peAsynchPhase,
/* [out] */ LPOLESTR __RPC_FAR *ppwszStatusText);
END_INTERFACE
} IDBAsynchStatusVtbl;
interface IDBAsynchStatus
{
CONST_VTBL struct IDBAsynchStatusVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBAsynchStatus_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBAsynchStatus_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBAsynchStatus_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBAsynchStatus_Abort(This,hChapter,eOperation) \
(This)->lpVtbl -> Abort(This,hChapter,eOperation)
#define IDBAsynchStatus_GetStatus(This,hChapter,eOperation,pulProgress,pulProgressMax,peAsynchPhase,ppwszStatusText) \
(This)->lpVtbl -> GetStatus(This,hChapter,eOperation,pulProgress,pulProgressMax,peAsynchPhase,ppwszStatusText)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchStatus_RemoteAbort_Proxy(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBAsynchStatus_RemoteAbort_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchStatus_RemoteGetStatus_Proxy(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ ULONG __RPC_FAR *pulProgress,
/* [out] */ ULONG __RPC_FAR *pulProgressMax,
/* [out] */ DBASYNCHPHASE __RPC_FAR *peAsynchPhase,
/* [out] */ LPOLESTR __RPC_FAR *ppwszStatusText,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBAsynchStatus_RemoteGetStatus_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBAsynchStatus_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0194
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
extern RPC_IF_HANDLE __MIDL_itf_oledb_0194_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0194_v0_0_s_ifspec;
#ifndef __ISessionProperties_INTERFACE_DEFINED__
#define __ISessionProperties_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ISessionProperties
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ISessionProperties;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a85-2a1c-11ce-ade5-00aa0044773d")
ISessionProperties : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetProperties(
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetProperties(
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
};
#else /* C style interface */
typedef struct ISessionPropertiesVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ISessionProperties __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ISessionProperties __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ISessionProperties __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetProperties )(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetProperties )(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
END_INTERFACE
} ISessionPropertiesVtbl;
interface ISessionProperties
{
CONST_VTBL struct ISessionPropertiesVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ISessionProperties_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ISessionProperties_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ISessionProperties_Release(This) \
(This)->lpVtbl -> Release(This)
#define ISessionProperties_GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets) \
(This)->lpVtbl -> GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets)
#define ISessionProperties_SetProperties(This,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> SetProperties(This,cPropertySets,rgPropertySets)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISessionProperties_RemoteGetProperties_Proxy(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ISessionProperties_RemoteGetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISessionProperties_RemoteSetProperties_Proxy(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ISessionProperties_RemoteSetProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ISessionProperties_INTERFACE_DEFINED__ */
#ifndef __IIndexDefinition_INTERFACE_DEFINED__
#define __IIndexDefinition_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IIndexDefinition
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IIndexDefinition;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a68-2a1c-11ce-ade5-00aa0044773d")
IIndexDefinition : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateIndex(
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ ULONG cIndexColumnDescs,
/* [size_is][in] */ const DBINDEXCOLUMNDESC __RPC_FAR rgIndexColumnDescs[ ],
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE DropIndex(
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID) = 0;
};
#else /* C style interface */
typedef struct IIndexDefinitionVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IIndexDefinition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IIndexDefinition __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IIndexDefinition __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateIndex )(
IIndexDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ ULONG cIndexColumnDescs,
/* [size_is][in] */ const DBINDEXCOLUMNDESC __RPC_FAR rgIndexColumnDescs[ ],
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropIndex )(
IIndexDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID);
END_INTERFACE
} IIndexDefinitionVtbl;
interface IIndexDefinition
{
CONST_VTBL struct IIndexDefinitionVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IIndexDefinition_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IIndexDefinition_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IIndexDefinition_Release(This) \
(This)->lpVtbl -> Release(This)
#define IIndexDefinition_CreateIndex(This,pTableID,pIndexID,cIndexColumnDescs,rgIndexColumnDescs,cPropertySets,rgPropertySets,ppIndexID) \
(This)->lpVtbl -> CreateIndex(This,pTableID,pIndexID,cIndexColumnDescs,rgIndexColumnDescs,cPropertySets,rgPropertySets,ppIndexID)
#define IIndexDefinition_DropIndex(This,pTableID,pIndexID) \
(This)->lpVtbl -> DropIndex(This,pTableID,pIndexID)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IIndexDefinition_RemoteCreateIndex_Proxy(
IIndexDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ ULONG cIndexColumnDescs,
/* [size_is][in] */ const DBINDEXCOLUMNDESC __RPC_FAR *rgIndexColumnDescs,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IIndexDefinition_RemoteCreateIndex_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IIndexDefinition_RemoteDropIndex_Proxy(
IIndexDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IIndexDefinition_RemoteDropIndex_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IIndexDefinition_INTERFACE_DEFINED__ */
#ifndef __ITableDefinition_INTERFACE_DEFINED__
#define __ITableDefinition_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITableDefinition
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITableDefinition;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a86-2a1c-11ce-ade5-00aa0044773d")
ITableDefinition : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateTable(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE DropTable(
/* [unique][in] */ DBID __RPC_FAR *pTableID) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddColumn(
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out][in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE DropColumn(
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID) = 0;
};
#else /* C style interface */
typedef struct ITableDefinitionVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITableDefinition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITableDefinition __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITableDefinition __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateTable )(
ITableDefinition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropTable )(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddColumn )(
ITableDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out][in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropColumn )(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID);
END_INTERFACE
} ITableDefinitionVtbl;
interface ITableDefinition
{
CONST_VTBL struct ITableDefinitionVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITableDefinition_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITableDefinition_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITableDefinition_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITableDefinition_CreateTable(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset) \
(This)->lpVtbl -> CreateTable(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset)
#define ITableDefinition_DropTable(This,pTableID) \
(This)->lpVtbl -> DropTable(This,pTableID)
#define ITableDefinition_AddColumn(This,pTableID,pColumnDesc,ppColumnID) \
(This)->lpVtbl -> AddColumn(This,pTableID,pColumnDesc,ppColumnID)
#define ITableDefinition_DropColumn(This,pTableID,pColumnID) \
(This)->lpVtbl -> DropColumn(This,pTableID,pColumnID)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_RemoteCreateTable_Proxy(
ITableDefinition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR *rgColumnDescs,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITableDefinition_RemoteCreateTable_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_RemoteDropTable_Proxy(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITableDefinition_RemoteDropTable_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_RemoteAddColumn_Proxy(
ITableDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITableDefinition_RemoteAddColumn_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_RemoteDropColumn_Proxy(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITableDefinition_RemoteDropColumn_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITableDefinition_INTERFACE_DEFINED__ */
#ifndef __IOpenRowset_INTERFACE_DEFINED__
#define __IOpenRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IOpenRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IOpenRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a69-2a1c-11ce-ade5-00aa0044773d")
IOpenRowset : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OpenRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
};
#else /* C style interface */
typedef struct IOpenRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IOpenRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IOpenRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IOpenRowset __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OpenRowset )(
IOpenRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
END_INTERFACE
} IOpenRowsetVtbl;
interface IOpenRowset
{
CONST_VTBL struct IOpenRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IOpenRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IOpenRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IOpenRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IOpenRowset_OpenRowset(This,pUnkOuter,pTableID,pIndexID,riid,cPropertySets,rgPropertySets,ppRowset) \
(This)->lpVtbl -> OpenRowset(This,pUnkOuter,pTableID,pIndexID,riid,cPropertySets,rgPropertySets,ppRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IOpenRowset_RemoteOpenRowset_Proxy(
IOpenRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IOpenRowset_RemoteOpenRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IOpenRowset_INTERFACE_DEFINED__ */
#ifndef __IDBSchemaRowset_INTERFACE_DEFINED__
#define __IDBSchemaRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBSchemaRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
#define CRESTRICTIONS_DBSCHEMA_ASSERTIONS 3
#define CRESTRICTIONS_DBSCHEMA_CATALOGS 1
#define CRESTRICTIONS_DBSCHEMA_CHARACTER_SETS 3
#define CRESTRICTIONS_DBSCHEMA_COLLATIONS 3
#define CRESTRICTIONS_DBSCHEMA_COLUMNS 4
#define CRESTRICTIONS_DBSCHEMA_CHECK_CONSTRAINTS 3
#define CRESTRICTIONS_DBSCHEMA_CONSTRAINT_COLUMN_USAGE 4
#define CRESTRICTIONS_DBSCHEMA_CONSTRAINT_TABLE_USAGE 3
#define CRESTRICTIONS_DBSCHEMA_KEY_COLUMN_USAGE 7
#define CRESTRICTIONS_DBSCHEMA_REFERENTIAL_CONSTRAINTS 3
#define CRESTRICTIONS_DBSCHEMA_TABLE_CONSTRAINTS 7
#define CRESTRICTIONS_DBSCHEMA_COLUMN_DOMAIN_USAGE 4
#define CRESTRICTIONS_DBSCHEMA_INDEXES 5
#define CRESTRICTIONS_DBSCHEMA_OBJECT_ACTIONS 1
#define CRESTRICTIONS_DBSCHEMA_OBJECTS 1
#define CRESTRICTIONS_DBSCHEMA_COLUMN_PRIVILEGES 6
#define CRESTRICTIONS_DBSCHEMA_TABLE_PRIVILEGES 5
#define CRESTRICTIONS_DBSCHEMA_USAGE_PRIVILEGES 6
#define CRESTRICTIONS_DBSCHEMA_PROCEDURES 4
#define CRESTRICTIONS_DBSCHEMA_SCHEMATA 3
#define CRESTRICTIONS_DBSCHEMA_SQL_LANGUAGES 0
#define CRESTRICTIONS_DBSCHEMA_STATISTICS 3
#define CRESTRICTIONS_DBSCHEMA_TABLES 4
#define CRESTRICTIONS_DBSCHEMA_TRANSLATIONS 3
#define CRESTRICTIONS_DBSCHEMA_PROVIDER_TYPES 2
#define CRESTRICTIONS_DBSCHEMA_VIEWS 3
#define CRESTRICTIONS_DBSCHEMA_VIEW_COLUMN_USAGE 3
#define CRESTRICTIONS_DBSCHEMA_VIEW_TABLE_USAGE 3
#define CRESTRICTIONS_DBSCHEMA_PROCEDURE_PARAMETERS 4
#define CRESTRICTIONS_DBSCHEMA_FOREIGN_KEYS 6
#define CRESTRICTIONS_DBSCHEMA_PRIMARY_KEYS 3
#define CRESTRICTIONS_DBSCHEMA_PROCEDURE_COLUMNS 4
#define CRESTRICTIONS_DBSCHEMA_TABLES_INFO 4
#define CRESTRICTIONS_MDSCHEMA_CUBES 3
#define CRESTRICTIONS_MDSCHEMA_DIMENSIONS 5
#define CRESTRICTIONS_MDSCHEMA_HIERARCHIES 6
#define CRESTRICTIONS_MDSCHEMA_LEVELS 7
#define CRESTRICTIONS_MDSCHEMA_MEASURES 5
#define CRESTRICTIONS_MDSCHEMA_PROPERTIES 9
#define CRESTRICTIONS_MDSCHEMA_MEMBERS 12
#define CRESTRICTIONS_DBSCHEMA_TRUSTEE 4
EXTERN_C const IID IID_IDBSchemaRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a7b-2a1c-11ce-ade5-00aa0044773d")
IDBSchemaRowset : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFGUID rguidSchema,
/* [in] */ ULONG cRestrictions,
/* [size_is][in] */ const VARIANT __RPC_FAR rgRestrictions[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSchemas(
/* [out][in] */ ULONG __RPC_FAR *pcSchemas,
/* [size_is][size_is][out] */ GUID __RPC_FAR *__RPC_FAR *prgSchemas,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgRestrictionSupport) = 0;
};
#else /* C style interface */
typedef struct IDBSchemaRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBSchemaRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBSchemaRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBSchemaRowset __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowset )(
IDBSchemaRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFGUID rguidSchema,
/* [in] */ ULONG cRestrictions,
/* [size_is][in] */ const VARIANT __RPC_FAR rgRestrictions[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSchemas )(
IDBSchemaRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcSchemas,
/* [size_is][size_is][out] */ GUID __RPC_FAR *__RPC_FAR *prgSchemas,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgRestrictionSupport);
END_INTERFACE
} IDBSchemaRowsetVtbl;
interface IDBSchemaRowset
{
CONST_VTBL struct IDBSchemaRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBSchemaRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBSchemaRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBSchemaRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBSchemaRowset_GetRowset(This,pUnkOuter,rguidSchema,cRestrictions,rgRestrictions,riid,cPropertySets,rgPropertySets,ppRowset) \
(This)->lpVtbl -> GetRowset(This,pUnkOuter,rguidSchema,cRestrictions,rgRestrictions,riid,cPropertySets,rgPropertySets,ppRowset)
#define IDBSchemaRowset_GetSchemas(This,pcSchemas,prgSchemas,prgRestrictionSupport) \
(This)->lpVtbl -> GetSchemas(This,pcSchemas,prgSchemas,prgRestrictionSupport)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBSchemaRowset_RemoteGetRowset_Proxy(
IDBSchemaRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFGUID rguidSchema,
/* [in] */ ULONG cRestrictions,
/* [size_is][unique][in] */ const VARIANT __RPC_FAR *rgRestrictions,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBSchemaRowset_RemoteGetRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBSchemaRowset_RemoteGetSchemas_Proxy(
IDBSchemaRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcSchemas,
/* [size_is][size_is][out] */ GUID __RPC_FAR *__RPC_FAR *prgSchemas,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgRestrictionSupport,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IDBSchemaRowset_RemoteGetSchemas_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBSchemaRowset_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0199
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
extern RPC_IF_HANDLE __MIDL_itf_oledb_0199_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0199_v0_0_s_ifspec;
#ifndef __IMDDataset_INTERFACE_DEFINED__
#define __IMDDataset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IMDDataset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IMDDataset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("a07cccd1-8148-11d0-87bb-00c04fc33942")
IMDDataset : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE FreeAxisInfo(
/* [in] */ ULONG cAxes,
/* [size_is][in] */ MDAXISINFO __RPC_FAR *rgAxisInfo) = 0;
virtual HRESULT STDMETHODCALLTYPE GetAxisInfo(
/* [out][in] */ ULONG __RPC_FAR *pcAxes,
/* [size_is][size_is][out] */ MDAXISINFO __RPC_FAR *__RPC_FAR *prgAxisInfo) = 0;
virtual HRESULT STDMETHODCALLTYPE GetAxisRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG iAxis,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCellData(
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG ulStartCell,
/* [in] */ ULONG ulEndCell,
/* [out] */ void __RPC_FAR *pData) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSpecification(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification) = 0;
};
#else /* C style interface */
typedef struct IMDDatasetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IMDDataset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IMDDataset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IMDDataset __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *FreeAxisInfo )(
IMDDataset __RPC_FAR * This,
/* [in] */ ULONG cAxes,
/* [size_is][in] */ MDAXISINFO __RPC_FAR *rgAxisInfo);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetAxisInfo )(
IMDDataset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcAxes,
/* [size_is][size_is][out] */ MDAXISINFO __RPC_FAR *__RPC_FAR *prgAxisInfo);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetAxisRowset )(
IMDDataset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG iAxis,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetCellData )(
IMDDataset __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG ulStartCell,
/* [in] */ ULONG ulEndCell,
/* [out] */ void __RPC_FAR *pData);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSpecification )(
IMDDataset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification);
END_INTERFACE
} IMDDatasetVtbl;
interface IMDDataset
{
CONST_VTBL struct IMDDatasetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IMDDataset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IMDDataset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IMDDataset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IMDDataset_FreeAxisInfo(This,cAxes,rgAxisInfo) \
(This)->lpVtbl -> FreeAxisInfo(This,cAxes,rgAxisInfo)
#define IMDDataset_GetAxisInfo(This,pcAxes,prgAxisInfo) \
(This)->lpVtbl -> GetAxisInfo(This,pcAxes,prgAxisInfo)
#define IMDDataset_GetAxisRowset(This,pUnkOuter,iAxis,riid,cPropertySets,rgPropertySets,ppRowset) \
(This)->lpVtbl -> GetAxisRowset(This,pUnkOuter,iAxis,riid,cPropertySets,rgPropertySets,ppRowset)
#define IMDDataset_GetCellData(This,hAccessor,ulStartCell,ulEndCell,pData) \
(This)->lpVtbl -> GetCellData(This,hAccessor,ulStartCell,ulEndCell,pData)
#define IMDDataset_GetSpecification(This,riid,ppSpecification) \
(This)->lpVtbl -> GetSpecification(This,riid,ppSpecification)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IMDDataset_FreeAxisInfo_Proxy(
IMDDataset __RPC_FAR * This,
/* [in] */ ULONG cAxes,
/* [size_is][in] */ MDAXISINFO __RPC_FAR *rgAxisInfo);
void __RPC_STUB IMDDataset_FreeAxisInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMDDataset_GetAxisInfo_Proxy(
IMDDataset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcAxes,
/* [size_is][size_is][out] */ MDAXISINFO __RPC_FAR *__RPC_FAR *prgAxisInfo);
void __RPC_STUB IMDDataset_GetAxisInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMDDataset_GetAxisRowset_Proxy(
IMDDataset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG iAxis,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
void __RPC_STUB IMDDataset_GetAxisRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMDDataset_GetCellData_Proxy(
IMDDataset __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG ulStartCell,
/* [in] */ ULONG ulEndCell,
/* [out] */ void __RPC_FAR *pData);
void __RPC_STUB IMDDataset_GetCellData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMDDataset_GetSpecification_Proxy(
IMDDataset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification);
void __RPC_STUB IMDDataset_GetSpecification_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IMDDataset_INTERFACE_DEFINED__ */
#ifndef __IMDFind_INTERFACE_DEFINED__
#define __IMDFind_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IMDFind
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IMDFind;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("a07cccd2-8148-11d0-87bb-00c04fc33942")
IMDFind : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE FindCell(
/* [in] */ ULONG ulStartingOrdinal,
/* [in] */ ULONG cMembers,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszMember,
/* [out] */ ULONG __RPC_FAR *pulCellOrdinal) = 0;
virtual HRESULT STDMETHODCALLTYPE FindTuple(
/* [in] */ ULONG ulAxisIdentifier,
/* [in] */ ULONG ulStartingOrdinal,
/* [in] */ ULONG cMembers,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszMember,
/* [out] */ ULONG __RPC_FAR *pulTupleOrdinal) = 0;
};
#else /* C style interface */
typedef struct IMDFindVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IMDFind __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IMDFind __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IMDFind __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *FindCell )(
IMDFind __RPC_FAR * This,
/* [in] */ ULONG ulStartingOrdinal,
/* [in] */ ULONG cMembers,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszMember,
/* [out] */ ULONG __RPC_FAR *pulCellOrdinal);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *FindTuple )(
IMDFind __RPC_FAR * This,
/* [in] */ ULONG ulAxisIdentifier,
/* [in] */ ULONG ulStartingOrdinal,
/* [in] */ ULONG cMembers,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszMember,
/* [out] */ ULONG __RPC_FAR *pulTupleOrdinal);
END_INTERFACE
} IMDFindVtbl;
interface IMDFind
{
CONST_VTBL struct IMDFindVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IMDFind_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IMDFind_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IMDFind_Release(This) \
(This)->lpVtbl -> Release(This)
#define IMDFind_FindCell(This,ulStartingOrdinal,cMembers,rgpwszMember,pulCellOrdinal) \
(This)->lpVtbl -> FindCell(This,ulStartingOrdinal,cMembers,rgpwszMember,pulCellOrdinal)
#define IMDFind_FindTuple(This,ulAxisIdentifier,ulStartingOrdinal,cMembers,rgpwszMember,pulTupleOrdinal) \
(This)->lpVtbl -> FindTuple(This,ulAxisIdentifier,ulStartingOrdinal,cMembers,rgpwszMember,pulTupleOrdinal)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IMDFind_FindCell_Proxy(
IMDFind __RPC_FAR * This,
/* [in] */ ULONG ulStartingOrdinal,
/* [in] */ ULONG cMembers,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszMember,
/* [out] */ ULONG __RPC_FAR *pulCellOrdinal);
void __RPC_STUB IMDFind_FindCell_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IMDFind_FindTuple_Proxy(
IMDFind __RPC_FAR * This,
/* [in] */ ULONG ulAxisIdentifier,
/* [in] */ ULONG ulStartingOrdinal,
/* [in] */ ULONG cMembers,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszMember,
/* [out] */ ULONG __RPC_FAR *pulTupleOrdinal);
void __RPC_STUB IMDFind_FindTuple_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IMDFind_INTERFACE_DEFINED__ */
#ifndef __IMDRangeRowset_INTERFACE_DEFINED__
#define __IMDRangeRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IMDRangeRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IMDRangeRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa0-2a1c-11ce-ade5-00aa0044773d")
IMDRangeRowset : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetRangeRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG ulStartCell,
/* [in] */ ULONG ulEndCell,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
};
#else /* C style interface */
typedef struct IMDRangeRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IMDRangeRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IMDRangeRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IMDRangeRowset __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRangeRowset )(
IMDRangeRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG ulStartCell,
/* [in] */ ULONG ulEndCell,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
END_INTERFACE
} IMDRangeRowsetVtbl;
interface IMDRangeRowset
{
CONST_VTBL struct IMDRangeRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IMDRangeRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IMDRangeRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IMDRangeRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IMDRangeRowset_GetRangeRowset(This,pUnkOuter,ulStartCell,ulEndCell,riid,cPropertySets,rgPropertySets,ppRowset) \
(This)->lpVtbl -> GetRangeRowset(This,pUnkOuter,ulStartCell,ulEndCell,riid,cPropertySets,rgPropertySets,ppRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IMDRangeRowset_GetRangeRowset_Proxy(
IMDRangeRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG ulStartCell,
/* [in] */ ULONG ulEndCell,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
void __RPC_STUB IMDRangeRowset_GetRangeRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IMDRangeRowset_INTERFACE_DEFINED__ */
#ifndef __IAlterTable_INTERFACE_DEFINED__
#define __IAlterTable_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IAlterTable
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IAlterTable;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa5-2a1c-11ce-ade5-00aa0044773d")
IAlterTable : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE AlterColumn(
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pColumnId,
/* [in] */ DBCOLUMNDESCFLAGS ColumnDescFlags,
/* [in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc) = 0;
virtual HRESULT STDMETHODCALLTYPE AlterTable(
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pNewTableId,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
};
#else /* C style interface */
typedef struct IAlterTableVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IAlterTable __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IAlterTable __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IAlterTable __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AlterColumn )(
IAlterTable __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pColumnId,
/* [in] */ DBCOLUMNDESCFLAGS ColumnDescFlags,
/* [in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AlterTable )(
IAlterTable __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pNewTableId,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
END_INTERFACE
} IAlterTableVtbl;
interface IAlterTable
{
CONST_VTBL struct IAlterTableVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IAlterTable_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IAlterTable_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IAlterTable_Release(This) \
(This)->lpVtbl -> Release(This)
#define IAlterTable_AlterColumn(This,pTableId,pColumnId,ColumnDescFlags,pColumnDesc) \
(This)->lpVtbl -> AlterColumn(This,pTableId,pColumnId,ColumnDescFlags,pColumnDesc)
#define IAlterTable_AlterTable(This,pTableId,pNewTableId,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> AlterTable(This,pTableId,pNewTableId,cPropertySets,rgPropertySets)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IAlterTable_AlterColumn_Proxy(
IAlterTable __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pColumnId,
/* [in] */ DBCOLUMNDESCFLAGS ColumnDescFlags,
/* [in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc);
void __RPC_STUB IAlterTable_AlterColumn_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IAlterTable_AlterTable_Proxy(
IAlterTable __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pNewTableId,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
void __RPC_STUB IAlterTable_AlterTable_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IAlterTable_INTERFACE_DEFINED__ */
#ifndef __IAlterIndex_INTERFACE_DEFINED__
#define __IAlterIndex_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IAlterIndex
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IAlterIndex;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa6-2a1c-11ce-ade5-00aa0044773d")
IAlterIndex : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE AlterIndex(
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pIndexId,
/* [in] */ DBID __RPC_FAR *pNewIndexId,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySet[ ]) = 0;
};
#else /* C style interface */
typedef struct IAlterIndexVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IAlterIndex __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IAlterIndex __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IAlterIndex __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AlterIndex )(
IAlterIndex __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pIndexId,
/* [in] */ DBID __RPC_FAR *pNewIndexId,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySet[ ]);
END_INTERFACE
} IAlterIndexVtbl;
interface IAlterIndex
{
CONST_VTBL struct IAlterIndexVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IAlterIndex_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IAlterIndex_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IAlterIndex_Release(This) \
(This)->lpVtbl -> Release(This)
#define IAlterIndex_AlterIndex(This,pTableId,pIndexId,pNewIndexId,cPropertySets,rgPropertySet) \
(This)->lpVtbl -> AlterIndex(This,pTableId,pIndexId,pNewIndexId,cPropertySets,rgPropertySet)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IAlterIndex_AlterIndex_Proxy(
IAlterIndex __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableId,
/* [in] */ DBID __RPC_FAR *pIndexId,
/* [in] */ DBID __RPC_FAR *pNewIndexId,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySet[ ]);
void __RPC_STUB IAlterIndex_AlterIndex_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IAlterIndex_INTERFACE_DEFINED__ */
#ifndef __IRowsetChapterMember_INTERFACE_DEFINED__
#define __IRowsetChapterMember_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetChapterMember
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetChapterMember;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa8-2a1c-11ce-ade5-00aa0044773d")
IRowsetChapterMember : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE IsRowInChapter(
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow) = 0;
};
#else /* C style interface */
typedef struct IRowsetChapterMemberVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetChapterMember __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetChapterMember __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetChapterMember __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *IsRowInChapter )(
IRowsetChapterMember __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow);
END_INTERFACE
} IRowsetChapterMemberVtbl;
interface IRowsetChapterMember
{
CONST_VTBL struct IRowsetChapterMemberVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetChapterMember_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetChapterMember_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetChapterMember_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetChapterMember_IsRowInChapter(This,hChapter,hRow) \
(This)->lpVtbl -> IsRowInChapter(This,hChapter,hRow)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetChapterMember_IsRowInChapter_Proxy(
IRowsetChapterMember __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow);
void __RPC_STUB IRowsetChapterMember_IsRowInChapter_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetChapterMember_INTERFACE_DEFINED__ */
#ifndef __ICommandPersist_INTERFACE_DEFINED__
#define __ICommandPersist_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICommandPersist
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_ICommandPersist;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa7-2a1c-11ce-ade5-00aa0044773d")
ICommandPersist : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE DeleteCommand(
/* [in] */ DBID __RPC_FAR *pCommandID) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurrentCommand(
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppCommandID) = 0;
virtual HRESULT STDMETHODCALLTYPE LoadCommand(
/* [in] */ DBID __RPC_FAR *pCommandID,
/* [in] */ DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE SaveCommand(
/* [in] */ DBID __RPC_FAR *pCommandID,
/* [in] */ DWORD dwFlags) = 0;
};
#else /* C style interface */
typedef struct ICommandPersistVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICommandPersist __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICommandPersist __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICommandPersist __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DeleteCommand )(
ICommandPersist __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pCommandID);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetCurrentCommand )(
ICommandPersist __RPC_FAR * This,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppCommandID);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *LoadCommand )(
ICommandPersist __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pCommandID,
/* [in] */ DWORD dwFlags);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SaveCommand )(
ICommandPersist __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pCommandID,
/* [in] */ DWORD dwFlags);
END_INTERFACE
} ICommandPersistVtbl;
interface ICommandPersist
{
CONST_VTBL struct ICommandPersistVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICommandPersist_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICommandPersist_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICommandPersist_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICommandPersist_DeleteCommand(This,pCommandID) \
(This)->lpVtbl -> DeleteCommand(This,pCommandID)
#define ICommandPersist_GetCurrentCommand(This,ppCommandID) \
(This)->lpVtbl -> GetCurrentCommand(This,ppCommandID)
#define ICommandPersist_LoadCommand(This,pCommandID,dwFlags) \
(This)->lpVtbl -> LoadCommand(This,pCommandID,dwFlags)
#define ICommandPersist_SaveCommand(This,pCommandID,dwFlags) \
(This)->lpVtbl -> SaveCommand(This,pCommandID,dwFlags)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ICommandPersist_DeleteCommand_Proxy(
ICommandPersist __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pCommandID);
void __RPC_STUB ICommandPersist_DeleteCommand_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ICommandPersist_GetCurrentCommand_Proxy(
ICommandPersist __RPC_FAR * This,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppCommandID);
void __RPC_STUB ICommandPersist_GetCurrentCommand_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ICommandPersist_LoadCommand_Proxy(
ICommandPersist __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pCommandID,
/* [in] */ DWORD dwFlags);
void __RPC_STUB ICommandPersist_LoadCommand_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ICommandPersist_SaveCommand_Proxy(
ICommandPersist __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pCommandID,
/* [in] */ DWORD dwFlags);
void __RPC_STUB ICommandPersist_SaveCommand_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICommandPersist_INTERFACE_DEFINED__ */
#ifndef __IRowsetRefresh_INTERFACE_DEFINED__
#define __IRowsetRefresh_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetRefresh
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetRefresh;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa9-2a1c-11ce-ade5-00aa0044773d")
IRowsetRefresh : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE RefreshVisibleData(
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cRows,
/* [in] */ const HROW __RPC_FAR rghRows[ ],
/* [in] */ BOOL fOverWrite,
/* [out] */ ULONG __RPC_FAR *pcRowsRefreshed,
/* [out] */ HROW __RPC_FAR *__RPC_FAR *prghRowsRefreshed,
/* [out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus) = 0;
virtual HRESULT STDMETHODCALLTYPE GetLastVisibleData(
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData) = 0;
};
#else /* C style interface */
typedef struct IRowsetRefreshVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetRefresh __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetRefresh __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetRefresh __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *RefreshVisibleData )(
IRowsetRefresh __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cRows,
/* [in] */ const HROW __RPC_FAR rghRows[ ],
/* [in] */ BOOL fOverWrite,
/* [out] */ ULONG __RPC_FAR *pcRowsRefreshed,
/* [out] */ HROW __RPC_FAR *__RPC_FAR *prghRowsRefreshed,
/* [out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetLastVisibleData )(
IRowsetRefresh __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
END_INTERFACE
} IRowsetRefreshVtbl;
interface IRowsetRefresh
{
CONST_VTBL struct IRowsetRefreshVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetRefresh_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetRefresh_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetRefresh_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetRefresh_RefreshVisibleData(This,hChapter,cRows,rghRows,fOverWrite,pcRowsRefreshed,prghRowsRefreshed,prgRowStatus) \
(This)->lpVtbl -> RefreshVisibleData(This,hChapter,cRows,rghRows,fOverWrite,pcRowsRefreshed,prghRowsRefreshed,prgRowStatus)
#define IRowsetRefresh_GetLastVisibleData(This,hRow,hAccessor,pData) \
(This)->lpVtbl -> GetLastVisibleData(This,hRow,hAccessor,pData)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetRefresh_RefreshVisibleData_Proxy(
IRowsetRefresh __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cRows,
/* [in] */ const HROW __RPC_FAR rghRows[ ],
/* [in] */ BOOL fOverWrite,
/* [out] */ ULONG __RPC_FAR *pcRowsRefreshed,
/* [out] */ HROW __RPC_FAR *__RPC_FAR *prghRowsRefreshed,
/* [out] */ DBROWSTATUS __RPC_FAR *__RPC_FAR *prgRowStatus);
void __RPC_STUB IRowsetRefresh_RefreshVisibleData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetRefresh_GetLastVisibleData_Proxy(
IRowsetRefresh __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ void __RPC_FAR *pData);
void __RPC_STUB IRowsetRefresh_GetLastVisibleData_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetRefresh_INTERFACE_DEFINED__ */
#ifndef __IParentRowset_INTERFACE_DEFINED__
#define __IParentRowset_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IParentRowset
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IParentRowset;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aaa-2a1c-11ce-ade5-00aa0044773d")
IParentRowset : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetChildRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
};
#else /* C style interface */
typedef struct IParentRowsetVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IParentRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IParentRowset __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IParentRowset __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetChildRowset )(
IParentRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
END_INTERFACE
} IParentRowsetVtbl;
interface IParentRowset
{
CONST_VTBL struct IParentRowsetVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IParentRowset_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IParentRowset_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IParentRowset_Release(This) \
(This)->lpVtbl -> Release(This)
#define IParentRowset_GetChildRowset(This,pUnkOuter,iOrdinal,riid,ppRowset) \
(This)->lpVtbl -> GetChildRowset(This,pUnkOuter,iOrdinal,riid,ppRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IParentRowset_GetChildRowset_Proxy(
IParentRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
void __RPC_STUB IParentRowset_GetChildRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IParentRowset_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0208
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
extern RPC_IF_HANDLE __MIDL_itf_oledb_0208_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0208_v0_0_s_ifspec;
#ifndef __IErrorRecords_INTERFACE_DEFINED__
#define __IErrorRecords_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IErrorRecords
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
#define IDENTIFIER_SDK_MASK 0xF0000000
#define IDENTIFIER_SDK_ERROR 0x10000000
typedef struct tagERRORINFO
{
HRESULT hrError;
DWORD dwMinor;
CLSID clsid;
IID iid;
DISPID dispid;
} ERRORINFO;
EXTERN_C const IID IID_IErrorRecords;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a67-2a1c-11ce-ade5-00aa0044773d")
IErrorRecords : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE AddErrorRecord(
/* [in] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ IUnknown __RPC_FAR *punkCustomError,
/* [in] */ DWORD dwDynamicErrorID) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetBasicErrorInfo(
/* [in] */ ULONG ulRecordNum,
/* [out] */ ERRORINFO __RPC_FAR *pErrorInfo) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetCustomErrorObject(
/* [in] */ ULONG ulRecordNum,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorInfo(
/* [in] */ ULONG ulRecordNum,
/* [in] */ LCID lcid,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfo) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorParameters(
/* [in] */ ULONG ulRecordNum,
/* [out] */ DISPPARAMS __RPC_FAR *pdispparams) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRecordCount(
/* [out] */ ULONG __RPC_FAR *pcRecords) = 0;
};
#else /* C style interface */
typedef struct IErrorRecordsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IErrorRecords __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IErrorRecords __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IErrorRecords __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddErrorRecord )(
IErrorRecords __RPC_FAR * This,
/* [in] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ IUnknown __RPC_FAR *punkCustomError,
/* [in] */ DWORD dwDynamicErrorID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetBasicErrorInfo )(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ ERRORINFO __RPC_FAR *pErrorInfo);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetCustomErrorObject )(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetErrorInfo )(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ LCID lcid,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfo);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetErrorParameters )(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ DISPPARAMS __RPC_FAR *pdispparams);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRecordCount )(
IErrorRecords __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcRecords);
END_INTERFACE
} IErrorRecordsVtbl;
interface IErrorRecords
{
CONST_VTBL struct IErrorRecordsVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IErrorRecords_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IErrorRecords_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IErrorRecords_Release(This) \
(This)->lpVtbl -> Release(This)
#define IErrorRecords_AddErrorRecord(This,pErrorInfo,dwLookupID,pdispparams,punkCustomError,dwDynamicErrorID) \
(This)->lpVtbl -> AddErrorRecord(This,pErrorInfo,dwLookupID,pdispparams,punkCustomError,dwDynamicErrorID)
#define IErrorRecords_GetBasicErrorInfo(This,ulRecordNum,pErrorInfo) \
(This)->lpVtbl -> GetBasicErrorInfo(This,ulRecordNum,pErrorInfo)
#define IErrorRecords_GetCustomErrorObject(This,ulRecordNum,riid,ppObject) \
(This)->lpVtbl -> GetCustomErrorObject(This,ulRecordNum,riid,ppObject)
#define IErrorRecords_GetErrorInfo(This,ulRecordNum,lcid,ppErrorInfo) \
(This)->lpVtbl -> GetErrorInfo(This,ulRecordNum,lcid,ppErrorInfo)
#define IErrorRecords_GetErrorParameters(This,ulRecordNum,pdispparams) \
(This)->lpVtbl -> GetErrorParameters(This,ulRecordNum,pdispparams)
#define IErrorRecords_GetRecordCount(This,pcRecords) \
(This)->lpVtbl -> GetRecordCount(This,pcRecords)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_RemoteAddErrorRecord_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ IUnknown __RPC_FAR *punkCustomError,
/* [in] */ DWORD dwDynamicErrorID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorRecords_RemoteAddErrorRecord_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_RemoteGetBasicErrorInfo_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorRecords_RemoteGetBasicErrorInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_RemoteGetCustomErrorObject_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorRecords_RemoteGetCustomErrorObject_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_RemoteGetErrorInfo_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ LCID lcid,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfo,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorRecords_RemoteGetErrorInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_RemoteGetErrorParameters_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorRecords_RemoteGetErrorParameters_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_RemoteGetRecordCount_Proxy(
IErrorRecords __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcRecords,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorRecords_RemoteGetRecordCount_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IErrorRecords_INTERFACE_DEFINED__ */
#ifndef __IErrorLookup_INTERFACE_DEFINED__
#define __IErrorLookup_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IErrorLookup
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IErrorLookup;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a66-2a1c-11ce-ade5-00aa0044773d")
IErrorLookup : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetErrorDescription(
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrSource,
/* [out] */ BSTR __RPC_FAR *pbstrDescription) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetHelpInfo(
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrHelpFile,
/* [out] */ DWORD __RPC_FAR *pdwHelpContext) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ReleaseErrors(
/* [in] */ const DWORD dwDynamicErrorID) = 0;
};
#else /* C style interface */
typedef struct IErrorLookupVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IErrorLookup __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IErrorLookup __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IErrorLookup __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetErrorDescription )(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrSource,
/* [out] */ BSTR __RPC_FAR *pbstrDescription);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetHelpInfo )(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrHelpFile,
/* [out] */ DWORD __RPC_FAR *pdwHelpContext);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *ReleaseErrors )(
IErrorLookup __RPC_FAR * This,
/* [in] */ const DWORD dwDynamicErrorID);
END_INTERFACE
} IErrorLookupVtbl;
interface IErrorLookup
{
CONST_VTBL struct IErrorLookupVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IErrorLookup_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IErrorLookup_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IErrorLookup_Release(This) \
(This)->lpVtbl -> Release(This)
#define IErrorLookup_GetErrorDescription(This,hrError,dwLookupID,pdispparams,lcid,pbstrSource,pbstrDescription) \
(This)->lpVtbl -> GetErrorDescription(This,hrError,dwLookupID,pdispparams,lcid,pbstrSource,pbstrDescription)
#define IErrorLookup_GetHelpInfo(This,hrError,dwLookupID,lcid,pbstrHelpFile,pdwHelpContext) \
(This)->lpVtbl -> GetHelpInfo(This,hrError,dwLookupID,lcid,pbstrHelpFile,pdwHelpContext)
#define IErrorLookup_ReleaseErrors(This,dwDynamicErrorID) \
(This)->lpVtbl -> ReleaseErrors(This,dwDynamicErrorID)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorLookup_RemoteGetErrorDescription_Proxy(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrSource,
/* [out] */ BSTR __RPC_FAR *pbstrDescription,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorLookup_RemoteGetErrorDescription_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorLookup_RemoteGetHelpInfo_Proxy(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrHelpFile,
/* [out] */ DWORD __RPC_FAR *pdwHelpContext,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorLookup_RemoteGetHelpInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorLookup_RemoteReleaseErrors_Proxy(
IErrorLookup __RPC_FAR * This,
/* [in] */ const DWORD dwDynamicErrorID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IErrorLookup_RemoteReleaseErrors_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IErrorLookup_INTERFACE_DEFINED__ */
#ifndef __ISQLErrorInfo_INTERFACE_DEFINED__
#define __ISQLErrorInfo_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ISQLErrorInfo
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ISQLErrorInfo;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a74-2a1c-11ce-ade5-00aa0044773d")
ISQLErrorInfo : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetSQLInfo(
/* [out] */ BSTR __RPC_FAR *pbstrSQLState,
/* [out] */ LONG __RPC_FAR *plNativeError) = 0;
};
#else /* C style interface */
typedef struct ISQLErrorInfoVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ISQLErrorInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ISQLErrorInfo __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ISQLErrorInfo __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSQLInfo )(
ISQLErrorInfo __RPC_FAR * This,
/* [out] */ BSTR __RPC_FAR *pbstrSQLState,
/* [out] */ LONG __RPC_FAR *plNativeError);
END_INTERFACE
} ISQLErrorInfoVtbl;
interface ISQLErrorInfo
{
CONST_VTBL struct ISQLErrorInfoVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ISQLErrorInfo_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ISQLErrorInfo_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ISQLErrorInfo_Release(This) \
(This)->lpVtbl -> Release(This)
#define ISQLErrorInfo_GetSQLInfo(This,pbstrSQLState,plNativeError) \
(This)->lpVtbl -> GetSQLInfo(This,pbstrSQLState,plNativeError)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISQLErrorInfo_RemoteGetSQLInfo_Proxy(
ISQLErrorInfo __RPC_FAR * This,
/* [out] */ BSTR __RPC_FAR *pbstrSQLState,
/* [out] */ LONG __RPC_FAR *plNativeError,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ISQLErrorInfo_RemoteGetSQLInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ISQLErrorInfo_INTERFACE_DEFINED__ */
#ifndef __IGetDataSource_INTERFACE_DEFINED__
#define __IGetDataSource_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IGetDataSource
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IGetDataSource;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a75-2a1c-11ce-ade5-00aa0044773d")
IGetDataSource : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetDataSource(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDataSource) = 0;
};
#else /* C style interface */
typedef struct IGetDataSourceVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IGetDataSource __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IGetDataSource __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IGetDataSource __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetDataSource )(
IGetDataSource __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDataSource);
END_INTERFACE
} IGetDataSourceVtbl;
interface IGetDataSource
{
CONST_VTBL struct IGetDataSourceVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IGetDataSource_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IGetDataSource_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IGetDataSource_Release(This) \
(This)->lpVtbl -> Release(This)
#define IGetDataSource_GetDataSource(This,riid,ppDataSource) \
(This)->lpVtbl -> GetDataSource(This,riid,ppDataSource)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IGetDataSource_RemoteGetDataSource_Proxy(
IGetDataSource __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDataSource,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB IGetDataSource_RemoteGetDataSource_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IGetDataSource_INTERFACE_DEFINED__ */
#ifndef __ITransactionLocal_INTERFACE_DEFINED__
#define __ITransactionLocal_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITransactionLocal
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITransactionLocal;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a5f-2a1c-11ce-ade5-00aa0044773d")
ITransactionLocal : public ITransaction
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetOptionsObject(
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE StartTransaction(
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [out] */ ULONG __RPC_FAR *pulTransactionLevel) = 0;
};
#else /* C style interface */
typedef struct ITransactionLocalVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITransactionLocal __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITransactionLocal __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITransactionLocal __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Commit )(
ITransactionLocal __RPC_FAR * This,
/* [in] */ BOOL fRetaining,
/* [in] */ DWORD grfTC,
/* [in] */ DWORD grfRM);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Abort )(
ITransactionLocal __RPC_FAR * This,
/* [unique][in] */ BOID __RPC_FAR *pboidReason,
/* [in] */ BOOL fRetaining,
/* [in] */ BOOL fAsync);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTransactionInfo )(
ITransactionLocal __RPC_FAR * This,
/* [out] */ XACTTRANSINFO __RPC_FAR *pinfo);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetOptionsObject )(
ITransactionLocal __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *StartTransaction )(
ITransactionLocal __RPC_FAR * This,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [out] */ ULONG __RPC_FAR *pulTransactionLevel);
END_INTERFACE
} ITransactionLocalVtbl;
interface ITransactionLocal
{
CONST_VTBL struct ITransactionLocalVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITransactionLocal_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITransactionLocal_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITransactionLocal_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITransactionLocal_Commit(This,fRetaining,grfTC,grfRM) \
(This)->lpVtbl -> Commit(This,fRetaining,grfTC,grfRM)
#define ITransactionLocal_Abort(This,pboidReason,fRetaining,fAsync) \
(This)->lpVtbl -> Abort(This,pboidReason,fRetaining,fAsync)
#define ITransactionLocal_GetTransactionInfo(This,pinfo) \
(This)->lpVtbl -> GetTransactionInfo(This,pinfo)
#define ITransactionLocal_GetOptionsObject(This,ppOptions) \
(This)->lpVtbl -> GetOptionsObject(This,ppOptions)
#define ITransactionLocal_StartTransaction(This,isoLevel,isoFlags,pOtherOptions,pulTransactionLevel) \
(This)->lpVtbl -> StartTransaction(This,isoLevel,isoFlags,pOtherOptions,pulTransactionLevel)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionLocal_RemoteGetOptionsObject_Proxy(
ITransactionLocal __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITransactionLocal_RemoteGetOptionsObject_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionLocal_RemoteStartTransaction_Proxy(
ITransactionLocal __RPC_FAR * This,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [unique][out][in] */ ULONG __RPC_FAR *pulTransactionLevel,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITransactionLocal_RemoteStartTransaction_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITransactionLocal_INTERFACE_DEFINED__ */
#ifndef __ITransactionJoin_INTERFACE_DEFINED__
#define __ITransactionJoin_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITransactionJoin
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITransactionJoin;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a5e-2a1c-11ce-ade5-00aa0044773d")
ITransactionJoin : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetOptionsObject(
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE JoinTransaction(
/* [in] */ IUnknown __RPC_FAR *punkTransactionCoord,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions) = 0;
};
#else /* C style interface */
typedef struct ITransactionJoinVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITransactionJoin __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITransactionJoin __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITransactionJoin __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetOptionsObject )(
ITransactionJoin __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *JoinTransaction )(
ITransactionJoin __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *punkTransactionCoord,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions);
END_INTERFACE
} ITransactionJoinVtbl;
interface ITransactionJoin
{
CONST_VTBL struct ITransactionJoinVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITransactionJoin_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITransactionJoin_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITransactionJoin_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITransactionJoin_GetOptionsObject(This,ppOptions) \
(This)->lpVtbl -> GetOptionsObject(This,ppOptions)
#define ITransactionJoin_JoinTransaction(This,punkTransactionCoord,isoLevel,isoFlags,pOtherOptions) \
(This)->lpVtbl -> JoinTransaction(This,punkTransactionCoord,isoLevel,isoFlags,pOtherOptions)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionJoin_RemoteGetOptionsObject_Proxy(
ITransactionJoin __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITransactionJoin_RemoteGetOptionsObject_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionJoin_RemoteJoinTransaction_Proxy(
ITransactionJoin __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *punkTransactionCoord,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITransactionJoin_RemoteJoinTransaction_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITransactionJoin_INTERFACE_DEFINED__ */
#ifndef __ITransactionObject_INTERFACE_DEFINED__
#define __ITransactionObject_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITransactionObject
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ITransactionObject;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733a60-2a1c-11ce-ade5-00aa0044773d")
ITransactionObject : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetTransactionObject(
/* [in] */ ULONG ulTransactionLevel,
/* [out] */ ITransaction __RPC_FAR *__RPC_FAR *ppTransactionObject) = 0;
};
#else /* C style interface */
typedef struct ITransactionObjectVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITransactionObject __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITransactionObject __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITransactionObject __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTransactionObject )(
ITransactionObject __RPC_FAR * This,
/* [in] */ ULONG ulTransactionLevel,
/* [out] */ ITransaction __RPC_FAR *__RPC_FAR *ppTransactionObject);
END_INTERFACE
} ITransactionObjectVtbl;
interface ITransactionObject
{
CONST_VTBL struct ITransactionObjectVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITransactionObject_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITransactionObject_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITransactionObject_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITransactionObject_GetTransactionObject(This,ulTransactionLevel,ppTransactionObject) \
(This)->lpVtbl -> GetTransactionObject(This,ulTransactionLevel,ppTransactionObject)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionObject_RemoteGetTransactionObject_Proxy(
ITransactionObject __RPC_FAR * This,
/* [in] */ ULONG ulTransactionLevel,
/* [out] */ ITransaction __RPC_FAR *__RPC_FAR *ppTransactionObject,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
void __RPC_STUB ITransactionObject_RemoteGetTransactionObject_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITransactionObject_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0223
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
#ifndef UNDER_CE
#if 0 // to get around a MIDL limitation
typedef
enum _TRUSTEE_TYPE
{ TRUSTEE_IS_UNKNOWN = 0,
TRUSTEE_IS_USER = TRUSTEE_IS_UNKNOWN + 1,
TRUSTEE_IS_GROUP = TRUSTEE_IS_USER + 1
} TRUSTEE_TYPE;
typedef
enum _TRUSTEE_FORM
{ TRUSTEE_IS_SID = 0,
TRUSTEE_IS_NAME = TRUSTEE_IS_SID + 1
} TRUSTEE_FORM;
typedef
enum _MULTIPLE_TRUSTEE_OPERATION
{ NO_MULTIPLE_TRUSTEE = 0,
TRUSTEE_IS_IMPERSONATE = NO_MULTIPLE_TRUSTEE + 1
} MULTIPLE_TRUSTEE_OPERATION;
typedef struct _TRUSTEE_A __RPC_FAR *PTRUSTEE_A;
typedef struct _TRUSTEE_W __RPC_FAR *PTRUSTEE_W;
typedef struct _TRUSTEE_W
{
PTRUSTEE_W pMultipleTrustee;
MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation;
TRUSTEE_FORM TrusteeForm;
TRUSTEE_TYPE TrusteeType;
LPWSTR ptstrName;
} TRUSTEE_W;
typedef struct _TRUSTEE_A
{
PTRUSTEE_A pMultipleTrustee;
MULTIPLE_TRUSTEE_OPERATION MultipleTrusteeOperation;
TRUSTEE_FORM TrusteeForm;
TRUSTEE_TYPE TrusteeType;
LPSTR ptstrName;
} TRUSTEE_A;
typedef
enum _ACCESS_MODE
{ NOT_USED_ACCESS = 0,
GRANT_ACCESS = NOT_USED_ACCESS + 1,
SET_ACCESS = GRANT_ACCESS + 1,
DENY_ACCESS = SET_ACCESS + 1,
REVOKE_ACCESS = DENY_ACCESS + 1,
SET_AUDIT_SUCCESS = REVOKE_ACCESS + 1,
SET_AUDIT_FAILURE = SET_AUDIT_SUCCESS + 1
} ACCESS_MODE;
typedef
enum _SE_OBJECT_TYPE
{ SE_UNKNOWN_OBJECT_TYPE = 0,
SE_FILE_OBJECT = SE_UNKNOWN_OBJECT_TYPE + 1,
SE_SERVICE = SE_FILE_OBJECT + 1,
SE_PRINTER = SE_SERVICE + 1,
SE_REGISTRY_KEY = SE_PRINTER + 1,
SE_LMSHARE = SE_REGISTRY_KEY + 1,
SE_KERNEL_OBJECT = SE_LMSHARE + 1,
SE_WINDOW_OBJECT = SE_KERNEL_OBJECT + 1
} SE_OBJECT_TYPE;
typedef struct _EXPLICIT_ACCESS_W
{
DWORD grfAccessPermissions;
ACCESS_MODE grfAccessMode;
DWORD grfInheritance;
TRUSTEE_W Trustee;
} EXPLICIT_ACCESS_W;
typedef struct _EXPLICIT_ACCESS_W __RPC_FAR *PEXPLICIT_ACCESS_W;
typedef struct _EXPLICIT_ACCESS_A
{
DWORD grfAccessPermissions;
ACCESS_MODE grfAccessMode;
DWORD grfInheritance;
TRUSTEE_A Trustee;
} EXPLICIT_ACCESS_A;
typedef struct _EXPLICIT_ACCESS_A __RPC_FAR *PEXPLICIT_ACCESS_A;
#else
#include <accctrl.h>
#endif
extern RPC_IF_HANDLE __MIDL_itf_oledb_0223_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0223_v0_0_s_ifspec;
#ifndef __ITrusteeAdmin_INTERFACE_DEFINED__
#define __ITrusteeAdmin_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITrusteeAdmin
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_ITrusteeAdmin;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa1-2a1c-11ce-ade5-00aa0044773d")
ITrusteeAdmin : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE CompareTrustees(
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee1,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee2) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateTrustee(
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE DeleteTrustee(
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee) = 0;
virtual HRESULT STDMETHODCALLTYPE SetTrusteeProperties(
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE GetTrusteeProperties(
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets) = 0;
};
#else /* C style interface */
typedef struct ITrusteeAdminVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITrusteeAdmin __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITrusteeAdmin __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CompareTrustees )(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee1,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee2);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateTrustee )(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DeleteTrustee )(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetTrusteeProperties )(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTrusteeProperties )(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
END_INTERFACE
} ITrusteeAdminVtbl;
interface ITrusteeAdmin
{
CONST_VTBL struct ITrusteeAdminVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITrusteeAdmin_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITrusteeAdmin_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITrusteeAdmin_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITrusteeAdmin_CompareTrustees(This,pTrustee1,pTrustee2) \
(This)->lpVtbl -> CompareTrustees(This,pTrustee1,pTrustee2)
#define ITrusteeAdmin_CreateTrustee(This,pTrustee,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> CreateTrustee(This,pTrustee,cPropertySets,rgPropertySets)
#define ITrusteeAdmin_DeleteTrustee(This,pTrustee) \
(This)->lpVtbl -> DeleteTrustee(This,pTrustee)
#define ITrusteeAdmin_SetTrusteeProperties(This,pTrustee,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> SetTrusteeProperties(This,pTrustee,cPropertySets,rgPropertySets)
#define ITrusteeAdmin_GetTrusteeProperties(This,pTrustee,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets) \
(This)->lpVtbl -> GetTrusteeProperties(This,pTrustee,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ITrusteeAdmin_CompareTrustees_Proxy(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee1,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee2);
void __RPC_STUB ITrusteeAdmin_CompareTrustees_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeAdmin_CreateTrustee_Proxy(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
void __RPC_STUB ITrusteeAdmin_CreateTrustee_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeAdmin_DeleteTrustee_Proxy(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee);
void __RPC_STUB ITrusteeAdmin_DeleteTrustee_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeAdmin_SetTrusteeProperties_Proxy(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
void __RPC_STUB ITrusteeAdmin_SetTrusteeProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeAdmin_GetTrusteeProperties_Proxy(
ITrusteeAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
void __RPC_STUB ITrusteeAdmin_GetTrusteeProperties_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITrusteeAdmin_INTERFACE_DEFINED__ */
#ifndef __ITrusteeGroupAdmin_INTERFACE_DEFINED__
#define __ITrusteeGroupAdmin_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITrusteeGroupAdmin
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_ITrusteeGroupAdmin;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa2-2a1c-11ce-ade5-00aa0044773d")
ITrusteeGroupAdmin : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE AddMember(
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee) = 0;
virtual HRESULT STDMETHODCALLTYPE DeleteMember(
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee) = 0;
virtual HRESULT STDMETHODCALLTYPE IsMember(
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee,
/* [out] */ BOOL __RPC_FAR *pfStatus) = 0;
virtual HRESULT STDMETHODCALLTYPE GetMembers(
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [out] */ ULONG __RPC_FAR *pcMembers,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *prgMembers) = 0;
virtual HRESULT STDMETHODCALLTYPE GetMemberships(
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [out] */ ULONG __RPC_FAR *pcMemberships,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *prgMemberships) = 0;
};
#else /* C style interface */
typedef struct ITrusteeGroupAdminVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITrusteeGroupAdmin __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITrusteeGroupAdmin __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddMember )(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DeleteMember )(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *IsMember )(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee,
/* [out] */ BOOL __RPC_FAR *pfStatus);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetMembers )(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [out] */ ULONG __RPC_FAR *pcMembers,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *prgMembers);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetMemberships )(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [out] */ ULONG __RPC_FAR *pcMemberships,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *prgMemberships);
END_INTERFACE
} ITrusteeGroupAdminVtbl;
interface ITrusteeGroupAdmin
{
CONST_VTBL struct ITrusteeGroupAdminVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITrusteeGroupAdmin_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITrusteeGroupAdmin_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITrusteeGroupAdmin_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITrusteeGroupAdmin_AddMember(This,pMembershipTrustee,pMemberTrustee) \
(This)->lpVtbl -> AddMember(This,pMembershipTrustee,pMemberTrustee)
#define ITrusteeGroupAdmin_DeleteMember(This,pMembershipTrustee,pMemberTrustee) \
(This)->lpVtbl -> DeleteMember(This,pMembershipTrustee,pMemberTrustee)
#define ITrusteeGroupAdmin_IsMember(This,pMembershipTrustee,pMemberTrustee,pfStatus) \
(This)->lpVtbl -> IsMember(This,pMembershipTrustee,pMemberTrustee,pfStatus)
#define ITrusteeGroupAdmin_GetMembers(This,pMembershipTrustee,pcMembers,prgMembers) \
(This)->lpVtbl -> GetMembers(This,pMembershipTrustee,pcMembers,prgMembers)
#define ITrusteeGroupAdmin_GetMemberships(This,pTrustee,pcMemberships,prgMemberships) \
(This)->lpVtbl -> GetMemberships(This,pTrustee,pcMemberships,prgMemberships)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ITrusteeGroupAdmin_AddMember_Proxy(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee);
void __RPC_STUB ITrusteeGroupAdmin_AddMember_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeGroupAdmin_DeleteMember_Proxy(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee);
void __RPC_STUB ITrusteeGroupAdmin_DeleteMember_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeGroupAdmin_IsMember_Proxy(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [in] */ TRUSTEE_W __RPC_FAR *pMemberTrustee,
/* [out] */ BOOL __RPC_FAR *pfStatus);
void __RPC_STUB ITrusteeGroupAdmin_IsMember_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeGroupAdmin_GetMembers_Proxy(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pMembershipTrustee,
/* [out] */ ULONG __RPC_FAR *pcMembers,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *prgMembers);
void __RPC_STUB ITrusteeGroupAdmin_GetMembers_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITrusteeGroupAdmin_GetMemberships_Proxy(
ITrusteeGroupAdmin __RPC_FAR * This,
/* [in] */ TRUSTEE_W __RPC_FAR *pTrustee,
/* [out] */ ULONG __RPC_FAR *pcMemberships,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *prgMemberships);
void __RPC_STUB ITrusteeGroupAdmin_GetMemberships_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITrusteeGroupAdmin_INTERFACE_DEFINED__ */
#ifndef __IObjectAccessControl_INTERFACE_DEFINED__
#define __IObjectAccessControl_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IObjectAccessControl
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IObjectAccessControl;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa3-2a1c-11ce-ade5-00aa0044773d")
IObjectAccessControl : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetObjectAccessRights(
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [out][in] */ ULONG __RPC_FAR *pcAccessEntries,
/* [out][in] */ EXPLICIT_ACCESS_W __RPC_FAR *__RPC_FAR *prgAccessEntries) = 0;
virtual HRESULT STDMETHODCALLTYPE GetObjectOwner(
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *ppOwner) = 0;
virtual HRESULT STDMETHODCALLTYPE IsObjectAccessAllowed(
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ EXPLICIT_ACCESS_W __RPC_FAR *pAccessEntry,
/* [out] */ BOOL __RPC_FAR *pfResult) = 0;
virtual HRESULT STDMETHODCALLTYPE SetObjectAccessRights(
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ ULONG cAccessEntries,
/* [out][in] */ EXPLICIT_ACCESS_W __RPC_FAR *prgAccessEntries) = 0;
virtual HRESULT STDMETHODCALLTYPE SetObjectOwner(
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ TRUSTEE_W __RPC_FAR *pOwner) = 0;
};
#else /* C style interface */
typedef struct IObjectAccessControlVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IObjectAccessControl __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IObjectAccessControl __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetObjectAccessRights )(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [out][in] */ ULONG __RPC_FAR *pcAccessEntries,
/* [out][in] */ EXPLICIT_ACCESS_W __RPC_FAR *__RPC_FAR *prgAccessEntries);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetObjectOwner )(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *ppOwner);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *IsObjectAccessAllowed )(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ EXPLICIT_ACCESS_W __RPC_FAR *pAccessEntry,
/* [out] */ BOOL __RPC_FAR *pfResult);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetObjectAccessRights )(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ ULONG cAccessEntries,
/* [out][in] */ EXPLICIT_ACCESS_W __RPC_FAR *prgAccessEntries);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetObjectOwner )(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ TRUSTEE_W __RPC_FAR *pOwner);
END_INTERFACE
} IObjectAccessControlVtbl;
interface IObjectAccessControl
{
CONST_VTBL struct IObjectAccessControlVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IObjectAccessControl_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IObjectAccessControl_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IObjectAccessControl_Release(This) \
(This)->lpVtbl -> Release(This)
#define IObjectAccessControl_GetObjectAccessRights(This,pObject,pcAccessEntries,prgAccessEntries) \
(This)->lpVtbl -> GetObjectAccessRights(This,pObject,pcAccessEntries,prgAccessEntries)
#define IObjectAccessControl_GetObjectOwner(This,pObject,ppOwner) \
(This)->lpVtbl -> GetObjectOwner(This,pObject,ppOwner)
#define IObjectAccessControl_IsObjectAccessAllowed(This,pObject,pAccessEntry,pfResult) \
(This)->lpVtbl -> IsObjectAccessAllowed(This,pObject,pAccessEntry,pfResult)
#define IObjectAccessControl_SetObjectAccessRights(This,pObject,cAccessEntries,prgAccessEntries) \
(This)->lpVtbl -> SetObjectAccessRights(This,pObject,cAccessEntries,prgAccessEntries)
#define IObjectAccessControl_SetObjectOwner(This,pObject,pOwner) \
(This)->lpVtbl -> SetObjectOwner(This,pObject,pOwner)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IObjectAccessControl_GetObjectAccessRights_Proxy(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [out][in] */ ULONG __RPC_FAR *pcAccessEntries,
/* [out][in] */ EXPLICIT_ACCESS_W __RPC_FAR *__RPC_FAR *prgAccessEntries);
void __RPC_STUB IObjectAccessControl_GetObjectAccessRights_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IObjectAccessControl_GetObjectOwner_Proxy(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *ppOwner);
void __RPC_STUB IObjectAccessControl_GetObjectOwner_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IObjectAccessControl_IsObjectAccessAllowed_Proxy(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ EXPLICIT_ACCESS_W __RPC_FAR *pAccessEntry,
/* [out] */ BOOL __RPC_FAR *pfResult);
void __RPC_STUB IObjectAccessControl_IsObjectAccessAllowed_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IObjectAccessControl_SetObjectAccessRights_Proxy(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ ULONG cAccessEntries,
/* [out][in] */ EXPLICIT_ACCESS_W __RPC_FAR *prgAccessEntries);
void __RPC_STUB IObjectAccessControl_SetObjectAccessRights_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IObjectAccessControl_SetObjectOwner_Proxy(
IObjectAccessControl __RPC_FAR * This,
/* [in] */ SEC_OBJECT __RPC_FAR *pObject,
/* [in] */ TRUSTEE_W __RPC_FAR *pOwner);
void __RPC_STUB IObjectAccessControl_SetObjectOwner_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IObjectAccessControl_INTERFACE_DEFINED__ */
#ifndef __ISecurityInfo_INTERFACE_DEFINED__
#define __ISecurityInfo_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ISecurityInfo
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
typedef DWORD ACCESS_MASK;
enum ACCESS_MASKENUM
{ PERM_EXCLUSIVE = 0x200L,
PERM_READDESIGN = 0x400L,
PERM_WRITEDESIGN = 0x800L,
PERM_WITHGRANT = 0x1000L,
PERM_REFERENCE = 0x2000L,
PERM_CREATE = 0x4000L,
PERM_INSERT = 0x8000L,
PERM_DELETE = 0x10000L,
PERM_READCONTROL = 0x20000L,
PERM_WRITEPERMISSIONS = 0x40000L,
PERM_WRITEOWNER = 0x80000L,
PERM_MAXIMUM_ALLOWED = 0x2000000L,
PERM_ALL = 0x10000000L,
PERM_EXECUTE = 0x20000000L,
PERM_READ = 0x80000000L,
PERM_UPDATE = 0x40000000L,
PERM_DROP = 0x100L
};
#define PERM_DESIGN PERM_WRITEDESIGN
EXTERN_C const IID IID_ISecurityInfo;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aa4-2a1c-11ce-ade5-00aa0044773d")
ISecurityInfo : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetCurrentTrustee(
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *ppTrustee) = 0;
virtual HRESULT STDMETHODCALLTYPE GetObjectTypes(
/* [out] */ ULONG __RPC_FAR *cObjectTypes,
/* [out] */ GUID __RPC_FAR *__RPC_FAR *rgObjectTypes) = 0;
virtual HRESULT STDMETHODCALLTYPE GetPermissions(
/* [in] */ GUID ObjectType,
/* [out] */ ACCESS_MASK __RPC_FAR *pPermissions) = 0;
};
#else /* C style interface */
typedef struct ISecurityInfoVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ISecurityInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ISecurityInfo __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ISecurityInfo __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetCurrentTrustee )(
ISecurityInfo __RPC_FAR * This,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *ppTrustee);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetObjectTypes )(
ISecurityInfo __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *cObjectTypes,
/* [out] */ GUID __RPC_FAR *__RPC_FAR *rgObjectTypes);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetPermissions )(
ISecurityInfo __RPC_FAR * This,
/* [in] */ GUID ObjectType,
/* [out] */ ACCESS_MASK __RPC_FAR *pPermissions);
END_INTERFACE
} ISecurityInfoVtbl;
interface ISecurityInfo
{
CONST_VTBL struct ISecurityInfoVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ISecurityInfo_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ISecurityInfo_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ISecurityInfo_Release(This) \
(This)->lpVtbl -> Release(This)
#define ISecurityInfo_GetCurrentTrustee(This,ppTrustee) \
(This)->lpVtbl -> GetCurrentTrustee(This,ppTrustee)
#define ISecurityInfo_GetObjectTypes(This,cObjectTypes,rgObjectTypes) \
(This)->lpVtbl -> GetObjectTypes(This,cObjectTypes,rgObjectTypes)
#define ISecurityInfo_GetPermissions(This,ObjectType,pPermissions) \
(This)->lpVtbl -> GetPermissions(This,ObjectType,pPermissions)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ISecurityInfo_GetCurrentTrustee_Proxy(
ISecurityInfo __RPC_FAR * This,
/* [out] */ TRUSTEE_W __RPC_FAR *__RPC_FAR *ppTrustee);
void __RPC_STUB ISecurityInfo_GetCurrentTrustee_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ISecurityInfo_GetObjectTypes_Proxy(
ISecurityInfo __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *cObjectTypes,
/* [out] */ GUID __RPC_FAR *__RPC_FAR *rgObjectTypes);
void __RPC_STUB ISecurityInfo_GetObjectTypes_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ISecurityInfo_GetPermissions_Proxy(
ISecurityInfo __RPC_FAR * This,
/* [in] */ GUID ObjectType,
/* [out] */ ACCESS_MASK __RPC_FAR *pPermissions);
void __RPC_STUB ISecurityInfo_GetPermissions_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ISecurityInfo_INTERFACE_DEFINED__ */
#endif // (UNDER_CE)
#ifndef __ITableCreation_INTERFACE_DEFINED__
#define __ITableCreation_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITableCreation
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_ITableCreation;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733abc-2a1c-11ce-ade5-00aa0044773d")
ITableCreation : public ITableDefinition
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetTableDefinition(
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out] */ ULONG __RPC_FAR *pcColumnDescs,
/* [size_is][size_is][out] */ DBCOLUMNDESC __RPC_FAR *__RPC_FAR prgColumnDescs[ ],
/* [out] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR prgPropertySets[ ],
/* [out] */ ULONG __RPC_FAR *pcConstraintDescs,
/* [size_is][size_is][out] */ DBCONSTRAINTDESC __RPC_FAR *__RPC_FAR prgConstraintDescs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppwszStringBuffer) = 0;
};
#else /* C style interface */
typedef struct ITableCreationVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITableCreation __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITableCreation __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITableCreation __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateTable )(
ITableCreation __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropTable )(
ITableCreation __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddColumn )(
ITableCreation __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out][in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropColumn )(
ITableCreation __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTableDefinition )(
ITableCreation __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out] */ ULONG __RPC_FAR *pcColumnDescs,
/* [size_is][size_is][out] */ DBCOLUMNDESC __RPC_FAR *__RPC_FAR prgColumnDescs[ ],
/* [out] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR prgPropertySets[ ],
/* [out] */ ULONG __RPC_FAR *pcConstraintDescs,
/* [size_is][size_is][out] */ DBCONSTRAINTDESC __RPC_FAR *__RPC_FAR prgConstraintDescs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppwszStringBuffer);
END_INTERFACE
} ITableCreationVtbl;
interface ITableCreation
{
CONST_VTBL struct ITableCreationVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITableCreation_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITableCreation_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITableCreation_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITableCreation_CreateTable(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset) \
(This)->lpVtbl -> CreateTable(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset)
#define ITableCreation_DropTable(This,pTableID) \
(This)->lpVtbl -> DropTable(This,pTableID)
#define ITableCreation_AddColumn(This,pTableID,pColumnDesc,ppColumnID) \
(This)->lpVtbl -> AddColumn(This,pTableID,pColumnDesc,ppColumnID)
#define ITableCreation_DropColumn(This,pTableID,pColumnID) \
(This)->lpVtbl -> DropColumn(This,pTableID,pColumnID)
#define ITableCreation_GetTableDefinition(This,pTableID,pcColumnDescs,prgColumnDescs,pcPropertySets,prgPropertySets,pcConstraintDescs,prgConstraintDescs,ppwszStringBuffer) \
(This)->lpVtbl -> GetTableDefinition(This,pTableID,pcColumnDescs,prgColumnDescs,pcPropertySets,prgPropertySets,pcConstraintDescs,prgConstraintDescs,ppwszStringBuffer)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [local] */ HRESULT STDMETHODCALLTYPE ITableCreation_GetTableDefinition_Proxy(
ITableCreation __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out] */ ULONG __RPC_FAR *pcColumnDescs,
/* [size_is][size_is][out] */ DBCOLUMNDESC __RPC_FAR *__RPC_FAR prgColumnDescs[ ],
/* [out] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR prgPropertySets[ ],
/* [out] */ ULONG __RPC_FAR *pcConstraintDescs,
/* [size_is][size_is][out] */ DBCONSTRAINTDESC __RPC_FAR *__RPC_FAR prgConstraintDescs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppwszStringBuffer);
void __RPC_STUB ITableCreation_GetTableDefinition_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITableCreation_INTERFACE_DEFINED__ */
#ifndef __ITableDefinitionWithConstraints_INTERFACE_DEFINED__
#define __ITableDefinitionWithConstraints_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ITableDefinitionWithConstraints
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_ITableDefinitionWithConstraints;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aab-2a1c-11ce-ade5-00aa0044773d")
ITableDefinitionWithConstraints : public ITableCreation
{
public:
virtual HRESULT STDMETHODCALLTYPE AddConstraint(
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBCONSTRAINTDESC __RPC_FAR *pConstraintDesc) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateTableWithConstraints(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [out][size_is][in] */ DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ ULONG cConstraintDescs,
/* [size_is][in] */ DBCONSTRAINTDESC __RPC_FAR rgConstraintDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [out][size_is][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
virtual HRESULT STDMETHODCALLTYPE DropConstraint(
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBID __RPC_FAR *pConstraintID) = 0;
};
#else /* C style interface */
typedef struct ITableDefinitionWithConstraintsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ITableDefinitionWithConstraints __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ITableDefinitionWithConstraints __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateTable )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropTable )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddColumn )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out][in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropColumn )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetTableDefinition )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out] */ ULONG __RPC_FAR *pcColumnDescs,
/* [size_is][size_is][out] */ DBCOLUMNDESC __RPC_FAR *__RPC_FAR prgColumnDescs[ ],
/* [out] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR prgPropertySets[ ],
/* [out] */ ULONG __RPC_FAR *pcConstraintDescs,
/* [size_is][size_is][out] */ DBCONSTRAINTDESC __RPC_FAR *__RPC_FAR prgConstraintDescs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppwszStringBuffer);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddConstraint )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBCONSTRAINTDESC __RPC_FAR *pConstraintDesc);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateTableWithConstraints )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [out][size_is][in] */ DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ ULONG cConstraintDescs,
/* [size_is][in] */ DBCONSTRAINTDESC __RPC_FAR rgConstraintDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [out][size_is][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DropConstraint )(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBID __RPC_FAR *pConstraintID);
END_INTERFACE
} ITableDefinitionWithConstraintsVtbl;
interface ITableDefinitionWithConstraints
{
CONST_VTBL struct ITableDefinitionWithConstraintsVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ITableDefinitionWithConstraints_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ITableDefinitionWithConstraints_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ITableDefinitionWithConstraints_Release(This) \
(This)->lpVtbl -> Release(This)
#define ITableDefinitionWithConstraints_CreateTable(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset) \
(This)->lpVtbl -> CreateTable(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset)
#define ITableDefinitionWithConstraints_DropTable(This,pTableID) \
(This)->lpVtbl -> DropTable(This,pTableID)
#define ITableDefinitionWithConstraints_AddColumn(This,pTableID,pColumnDesc,ppColumnID) \
(This)->lpVtbl -> AddColumn(This,pTableID,pColumnDesc,ppColumnID)
#define ITableDefinitionWithConstraints_DropColumn(This,pTableID,pColumnID) \
(This)->lpVtbl -> DropColumn(This,pTableID,pColumnID)
#define ITableDefinitionWithConstraints_GetTableDefinition(This,pTableID,pcColumnDescs,prgColumnDescs,pcPropertySets,prgPropertySets,pcConstraintDescs,prgConstraintDescs,ppwszStringBuffer) \
(This)->lpVtbl -> GetTableDefinition(This,pTableID,pcColumnDescs,prgColumnDescs,pcPropertySets,prgPropertySets,pcConstraintDescs,prgConstraintDescs,ppwszStringBuffer)
#define ITableDefinitionWithConstraints_AddConstraint(This,pTableID,pConstraintDesc) \
(This)->lpVtbl -> AddConstraint(This,pTableID,pConstraintDesc)
#define ITableDefinitionWithConstraints_CreateTableWithConstraints(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,cConstraintDescs,rgConstraintDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset) \
(This)->lpVtbl -> CreateTableWithConstraints(This,pUnkOuter,pTableID,cColumnDescs,rgColumnDescs,cConstraintDescs,rgConstraintDescs,riid,cPropertySets,rgPropertySets,ppTableID,ppRowset)
#define ITableDefinitionWithConstraints_DropConstraint(This,pTableID,pConstraintID) \
(This)->lpVtbl -> DropConstraint(This,pTableID,pConstraintID)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE ITableDefinitionWithConstraints_AddConstraint_Proxy(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBCONSTRAINTDESC __RPC_FAR *pConstraintDesc);
void __RPC_STUB ITableDefinitionWithConstraints_AddConstraint_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITableDefinitionWithConstraints_CreateTableWithConstraints_Proxy(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [out][size_is][in] */ DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ ULONG cConstraintDescs,
/* [size_is][in] */ DBCONSTRAINTDESC __RPC_FAR rgConstraintDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [out][size_is][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
void __RPC_STUB ITableDefinitionWithConstraints_CreateTableWithConstraints_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE ITableDefinitionWithConstraints_DropConstraint_Proxy(
ITableDefinitionWithConstraints __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBID __RPC_FAR *pConstraintID);
void __RPC_STUB ITableDefinitionWithConstraints_DropConstraint_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ITableDefinitionWithConstraints_INTERFACE_DEFINED__ */
#ifndef UNDER_CE
#ifndef __IRow_INTERFACE_DEFINED__
#define __IRow_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRow
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRow;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab4-2a1c-11ce-ade5-00aa0044773d")
IRow : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetColumns(
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE GetSourceRowset(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ HROW __RPC_FAR *phRow) = 0;
virtual HRESULT STDMETHODCALLTYPE Open(
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pColumnID,
/* [in] */ REFGUID rguidColumnType,
/* [in] */ DWORD dwBindFlags,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk) = 0;
};
#else /* C style interface */
typedef struct IRowVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRow __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRow __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetColumns )(
IRow __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSourceRowset )(
IRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ HROW __RPC_FAR *phRow);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Open )(
IRow __RPC_FAR * This,
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pColumnID,
/* [in] */ REFGUID rguidColumnType,
/* [in] */ DWORD dwBindFlags,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
END_INTERFACE
} IRowVtbl;
interface IRow
{
CONST_VTBL struct IRowVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRow_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRow_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRow_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRow_GetColumns(This,cColumns,rgColumns) \
(This)->lpVtbl -> GetColumns(This,cColumns,rgColumns)
#define IRow_GetSourceRowset(This,riid,ppRowset,phRow) \
(This)->lpVtbl -> GetSourceRowset(This,riid,ppRowset,phRow)
#define IRow_Open(This,pUnkOuter,pColumnID,rguidColumnType,dwBindFlags,riid,ppUnk) \
(This)->lpVtbl -> Open(This,pUnkOuter,pColumnID,rguidColumnType,dwBindFlags,riid,ppUnk)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [local] */ HRESULT STDMETHODCALLTYPE IRow_GetColumns_Proxy(
IRow __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
void __RPC_STUB IRow_GetColumns_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRow_GetSourceRowset_Proxy(
IRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ HROW __RPC_FAR *phRow);
void __RPC_STUB IRow_GetSourceRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRow_Open_Proxy(
IRow __RPC_FAR * This,
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pColumnID,
/* [in] */ REFGUID rguidColumnType,
/* [in] */ DWORD dwBindFlags,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
void __RPC_STUB IRow_Open_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRow_INTERFACE_DEFINED__ */
#ifndef __IRowChange_INTERFACE_DEFINED__
#define __IRowChange_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowChange
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowChange;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab5-2a1c-11ce-ade5-00aa0044773d")
IRowChange : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE SetColumns(
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]) = 0;
};
#else /* C style interface */
typedef struct IRowChangeVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowChange __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowChange __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowChange __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetColumns )(
IRowChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
END_INTERFACE
} IRowChangeVtbl;
interface IRowChange
{
CONST_VTBL struct IRowChangeVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowChange_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowChange_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowChange_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowChange_SetColumns(This,cColumns,rgColumns) \
(This)->lpVtbl -> SetColumns(This,cColumns,rgColumns)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [local] */ HRESULT STDMETHODCALLTYPE IRowChange_SetColumns_Proxy(
IRowChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
void __RPC_STUB IRowChange_SetColumns_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowChange_INTERFACE_DEFINED__ */
#ifndef __IRowSchemaChange_INTERFACE_DEFINED__
#define __IRowSchemaChange_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowSchemaChange
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowSchemaChange;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aae-2a1c-11ce-ade5-00aa0044773d")
IRowSchemaChange : public IRowChange
{
public:
virtual HRESULT STDMETHODCALLTYPE DeleteColumns(
/* [in] */ ULONG cColumns,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ]) = 0;
virtual HRESULT STDMETHODCALLTYPE AddColumns(
/* [in] */ ULONG cColumns,
/* [size_is][in] */ const DBCOLUMNINFO __RPC_FAR rgNewColumnInfo[ ],
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]) = 0;
};
#else /* C style interface */
typedef struct IRowSchemaChangeVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowSchemaChange __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowSchemaChange __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowSchemaChange __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetColumns )(
IRowSchemaChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *DeleteColumns )(
IRowSchemaChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *AddColumns )(
IRowSchemaChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ const DBCOLUMNINFO __RPC_FAR rgNewColumnInfo[ ],
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
END_INTERFACE
} IRowSchemaChangeVtbl;
interface IRowSchemaChange
{
CONST_VTBL struct IRowSchemaChangeVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowSchemaChange_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowSchemaChange_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowSchemaChange_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowSchemaChange_SetColumns(This,cColumns,rgColumns) \
(This)->lpVtbl -> SetColumns(This,cColumns,rgColumns)
#define IRowSchemaChange_DeleteColumns(This,cColumns,rgColumnIDs,rgdwStatus) \
(This)->lpVtbl -> DeleteColumns(This,cColumns,rgColumnIDs,rgdwStatus)
#define IRowSchemaChange_AddColumns(This,cColumns,rgNewColumnInfo,rgColumns) \
(This)->lpVtbl -> AddColumns(This,cColumns,rgNewColumnInfo,rgColumns)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowSchemaChange_DeleteColumns_Proxy(
IRowSchemaChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ]);
void __RPC_STUB IRowSchemaChange_DeleteColumns_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowSchemaChange_AddColumns_Proxy(
IRowSchemaChange __RPC_FAR * This,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ const DBCOLUMNINFO __RPC_FAR rgNewColumnInfo[ ],
/* [size_is][out][in] */ DBCOLUMNACCESS __RPC_FAR rgColumns[ ]);
void __RPC_STUB IRowSchemaChange_AddColumns_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowSchemaChange_INTERFACE_DEFINED__ */
#ifndef __IGetRow_INTERFACE_DEFINED__
#define __IGetRow_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IGetRow
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IGetRow;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aaf-2a1c-11ce-ade5-00aa0044773d")
IGetRow : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetRowFromHROW(
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ HROW hRow,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk) = 0;
virtual HRESULT STDMETHODCALLTYPE GetURLFromHROW(
/* [in] */ HROW hRow,
/* [out] */ LPOLESTR __RPC_FAR *ppwszURL) = 0;
};
#else /* C style interface */
typedef struct IGetRowVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IGetRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IGetRow __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IGetRow __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRowFromHROW )(
IGetRow __RPC_FAR * This,
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ HROW hRow,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetURLFromHROW )(
IGetRow __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [out] */ LPOLESTR __RPC_FAR *ppwszURL);
END_INTERFACE
} IGetRowVtbl;
interface IGetRow
{
CONST_VTBL struct IGetRowVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IGetRow_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IGetRow_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IGetRow_Release(This) \
(This)->lpVtbl -> Release(This)
#define IGetRow_GetRowFromHROW(This,pUnkOuter,hRow,riid,ppUnk) \
(This)->lpVtbl -> GetRowFromHROW(This,pUnkOuter,hRow,riid,ppUnk)
#define IGetRow_GetURLFromHROW(This,hRow,ppwszURL) \
(This)->lpVtbl -> GetURLFromHROW(This,hRow,ppwszURL)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IGetRow_GetRowFromHROW_Proxy(
IGetRow __RPC_FAR * This,
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ HROW hRow,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
void __RPC_STUB IGetRow_GetRowFromHROW_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IGetRow_GetURLFromHROW_Proxy(
IGetRow __RPC_FAR * This,
/* [in] */ HROW hRow,
/* [out] */ LPOLESTR __RPC_FAR *ppwszURL);
void __RPC_STUB IGetRow_GetURLFromHROW_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IGetRow_INTERFACE_DEFINED__ */
#ifndef __IBindResource_INTERFACE_DEFINED__
#define __IBindResource_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IBindResource
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IBindResource;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab1-2a1c-11ce-ade5-00aa0044773d")
IBindResource : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Bind(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk) = 0;
};
#else /* C style interface */
typedef struct IBindResourceVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IBindResource __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IBindResource __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IBindResource __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Bind )(
IBindResource __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
END_INTERFACE
} IBindResourceVtbl;
interface IBindResource
{
CONST_VTBL struct IBindResourceVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IBindResource_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IBindResource_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IBindResource_Release(This) \
(This)->lpVtbl -> Release(This)
#define IBindResource_Bind(This,pUnkOuter,pwszURL,dwBindURLFlags,rguid,riid,pAuthenticate,pImplSession,pdwBindStatus,ppUnk) \
(This)->lpVtbl -> Bind(This,pUnkOuter,pwszURL,dwBindURLFlags,rguid,riid,pAuthenticate,pImplSession,pdwBindStatus,ppUnk)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IBindResource_RemoteBind_Proxy(
IBindResource __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
void __RPC_STUB IBindResource_RemoteBind_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IBindResource_INTERFACE_DEFINED__ */
#ifndef __IScopedOperations_INTERFACE_DEFINED__
#define __IScopedOperations_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IScopedOperations
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
typedef DWORD DBCOPYFLAGS;
enum DBCOPYFLAGSENUM
{ DBCOPY_ASYNC = 0x100,
DBCOPY_REPLACE_EXISTING = 0x200,
DBCOPY_ALLOW_EMULATION = 0x400,
DBCOPY_NON_RECURSIVE = 0x800,
DBCOPY_ATOMIC = 0x1000
};
typedef DWORD DBMOVEFLAGS;
enum DBMOVEFLAGSENUM
{ DBMOVE_REPLACE_EXISTING = 0x1,
DBMOVE_ASYNC = 0x100,
DBMOVE_DONT_UPDATE_LINKS = 0x200,
DBMOVE_ALLOW_EMULATION = 0x400,
DBMOVE_ATOMIC = 0x1000
};
typedef DWORD DBDELETEFLAGS;
enum DBDELETEFLAGSENUM
{ DBDELETE_ASYNC = 0x100,
DBDELETE_ATOMIC = 0x1000
};
EXTERN_C const IID IID_IScopedOperations;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab0-2a1c-11ce-ade5-00aa0044773d")
IScopedOperations : public IBindResource
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Copy(
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszSourceURLs[ ],
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszDestURLs[ ],
/* [in] */ DWORD dwCopyFlags,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ],
/* [size_is][out] */ LPOLESTR __RPC_FAR rgpwszNewURLs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Move(
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszSourceURLs[ ],
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszDestURLs[ ],
/* [in] */ DWORD dwMoveFlags,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ],
/* [size_is][out] */ LPOLESTR __RPC_FAR rgpwszNewURLs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Delete(
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszURLs[ ],
/* [in] */ DWORD dwDeleteFlags,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ]) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE OpenRowset(
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset) = 0;
};
#else /* C style interface */
typedef struct IScopedOperationsVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IScopedOperations __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IScopedOperations __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IScopedOperations __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Bind )(
IScopedOperations __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Copy )(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszSourceURLs[ ],
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszDestURLs[ ],
/* [in] */ DWORD dwCopyFlags,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ],
/* [size_is][out] */ LPOLESTR __RPC_FAR rgpwszNewURLs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Move )(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszSourceURLs[ ],
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszDestURLs[ ],
/* [in] */ DWORD dwMoveFlags,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ],
/* [size_is][out] */ LPOLESTR __RPC_FAR rgpwszNewURLs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Delete )(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszURLs[ ],
/* [in] */ DWORD dwDeleteFlags,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ]);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *OpenRowset )(
IScopedOperations __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
END_INTERFACE
} IScopedOperationsVtbl;
interface IScopedOperations
{
CONST_VTBL struct IScopedOperationsVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IScopedOperations_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IScopedOperations_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IScopedOperations_Release(This) \
(This)->lpVtbl -> Release(This)
#define IScopedOperations_Bind(This,pUnkOuter,pwszURL,dwBindURLFlags,rguid,riid,pAuthenticate,pImplSession,pdwBindStatus,ppUnk) \
(This)->lpVtbl -> Bind(This,pUnkOuter,pwszURL,dwBindURLFlags,rguid,riid,pAuthenticate,pImplSession,pdwBindStatus,ppUnk)
#define IScopedOperations_Copy(This,cRows,rgpwszSourceURLs,rgpwszDestURLs,dwCopyFlags,pAuthenticate,rgdwStatus,rgpwszNewURLs,ppStringsBuffer) \
(This)->lpVtbl -> Copy(This,cRows,rgpwszSourceURLs,rgpwszDestURLs,dwCopyFlags,pAuthenticate,rgdwStatus,rgpwszNewURLs,ppStringsBuffer)
#define IScopedOperations_Move(This,cRows,rgpwszSourceURLs,rgpwszDestURLs,dwMoveFlags,pAuthenticate,rgdwStatus,rgpwszNewURLs,ppStringsBuffer) \
(This)->lpVtbl -> Move(This,cRows,rgpwszSourceURLs,rgpwszDestURLs,dwMoveFlags,pAuthenticate,rgdwStatus,rgpwszNewURLs,ppStringsBuffer)
#define IScopedOperations_Delete(This,cRows,rgpwszURLs,dwDeleteFlags,rgdwStatus) \
(This)->lpVtbl -> Delete(This,cRows,rgpwszURLs,dwDeleteFlags,rgdwStatus)
#define IScopedOperations_OpenRowset(This,pUnkOuter,pTableID,pIndexID,riid,cPropertySets,rgPropertySets,ppRowset) \
(This)->lpVtbl -> OpenRowset(This,pUnkOuter,pTableID,pIndexID,riid,cPropertySets,rgPropertySets,ppRowset)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_RemoteCopy_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszSourceURLs,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszDestURLs,
/* [in] */ DWORD dwCopyFlags,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out] */ DBSTATUS __RPC_FAR *rgdwStatus,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgulNewURLOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
void __RPC_STUB IScopedOperations_RemoteCopy_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_RemoteMove_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszSourceURLs,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszDestURLs,
/* [in] */ DWORD dwMoveFlags,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out] */ DBSTATUS __RPC_FAR *rgdwStatus,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgulNewURLOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
void __RPC_STUB IScopedOperations_RemoteMove_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_RemoteDelete_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszURLs,
/* [in] */ DWORD dwDeleteFlags,
/* [size_is][out] */ DBSTATUS __RPC_FAR *rgdwStatus);
void __RPC_STUB IScopedOperations_RemoteDelete_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_RemoteOpenRowset_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus);
void __RPC_STUB IScopedOperations_RemoteOpenRowset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IScopedOperations_INTERFACE_DEFINED__ */
#ifndef __ICreateRow_INTERFACE_DEFINED__
#define __ICreateRow_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: ICreateRow
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_ICreateRow;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab2-2a1c-11ce-ade5-00aa0044773d")
ICreateRow : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE CreateRow(
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out][in] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [out] */ LPOLESTR __RPC_FAR *ppwszNewURL,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk) = 0;
};
#else /* C style interface */
typedef struct ICreateRowVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
ICreateRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
ICreateRow __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
ICreateRow __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *CreateRow )(
ICreateRow __RPC_FAR * This,
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out][in] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [out] */ LPOLESTR __RPC_FAR *ppwszNewURL,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
END_INTERFACE
} ICreateRowVtbl;
interface ICreateRow
{
CONST_VTBL struct ICreateRowVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define ICreateRow_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define ICreateRow_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define ICreateRow_Release(This) \
(This)->lpVtbl -> Release(This)
#define ICreateRow_CreateRow(This,pUnkOuter,pwszURL,dwBindURLFlags,rguid,riid,pAuthenticate,pImplSession,pdwBindStatus,ppwszNewURL,ppUnk) \
(This)->lpVtbl -> CreateRow(This,pUnkOuter,pwszURL,dwBindURLFlags,rguid,riid,pAuthenticate,pImplSession,pdwBindStatus,ppwszNewURL,ppUnk)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICreateRow_RemoteCreateRow_Proxy(
ICreateRow __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [unique][out][in] */ LPOLESTR __RPC_FAR *ppwszNewURL,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
void __RPC_STUB ICreateRow_RemoteCreateRow_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __ICreateRow_INTERFACE_DEFINED__ */
#ifndef __IDBBinderProperties_INTERFACE_DEFINED__
#define __IDBBinderProperties_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IDBBinderProperties
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IDBBinderProperties;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab3-2a1c-11ce-ade5-00aa0044773d")
IDBBinderProperties : public IDBProperties
{
public:
virtual HRESULT STDMETHODCALLTYPE Reset( void) = 0;
};
#else /* C style interface */
typedef struct IDBBinderPropertiesVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IDBBinderProperties __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IDBBinderProperties __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IDBBinderProperties __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetProperties )(
IDBBinderProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetPropertyInfo )(
IDBBinderProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetProperties )(
IDBBinderProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Reset )(
IDBBinderProperties __RPC_FAR * This);
END_INTERFACE
} IDBBinderPropertiesVtbl;
interface IDBBinderProperties
{
CONST_VTBL struct IDBBinderPropertiesVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IDBBinderProperties_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IDBBinderProperties_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IDBBinderProperties_Release(This) \
(This)->lpVtbl -> Release(This)
#define IDBBinderProperties_GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets) \
(This)->lpVtbl -> GetProperties(This,cPropertyIDSets,rgPropertyIDSets,pcPropertySets,prgPropertySets)
#define IDBBinderProperties_GetPropertyInfo(This,cPropertyIDSets,rgPropertyIDSets,pcPropertyInfoSets,prgPropertyInfoSets,ppDescBuffer) \
(This)->lpVtbl -> GetPropertyInfo(This,cPropertyIDSets,rgPropertyIDSets,pcPropertyInfoSets,prgPropertyInfoSets,ppDescBuffer)
#define IDBBinderProperties_SetProperties(This,cPropertySets,rgPropertySets) \
(This)->lpVtbl -> SetProperties(This,cPropertySets,rgPropertySets)
#define IDBBinderProperties_Reset(This) \
(This)->lpVtbl -> Reset(This)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IDBBinderProperties_Reset_Proxy(
IDBBinderProperties __RPC_FAR * This);
void __RPC_STUB IDBBinderProperties_Reset_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IDBBinderProperties_INTERFACE_DEFINED__ */
#ifndef __IColumnsInfo2_INTERFACE_DEFINED__
#define __IColumnsInfo2_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IColumnsInfo2
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IColumnsInfo2;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab8-2a1c-11ce-ade5-00aa0044773d")
IColumnsInfo2 : public IColumnsInfo
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetRestrictedColumnInfo(
/* [in] */ ULONG cColumnIDMasks,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDMasks[ ],
/* [in] */ DWORD dwFlags,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgColumnIDs,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgColumnInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer) = 0;
};
#else /* C style interface */
typedef struct IColumnsInfo2Vtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IColumnsInfo2 __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IColumnsInfo2 __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IColumnsInfo2 __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetColumnInfo )(
IColumnsInfo2 __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *MapColumnIDs )(
IColumnsInfo2 __RPC_FAR * This,
/* [in] */ ULONG cColumnIDs,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgColumns[ ]);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetRestrictedColumnInfo )(
IColumnsInfo2 __RPC_FAR * This,
/* [in] */ ULONG cColumnIDMasks,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDMasks[ ],
/* [in] */ DWORD dwFlags,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgColumnIDs,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgColumnInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
END_INTERFACE
} IColumnsInfo2Vtbl;
interface IColumnsInfo2
{
CONST_VTBL struct IColumnsInfo2Vtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IColumnsInfo2_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IColumnsInfo2_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IColumnsInfo2_Release(This) \
(This)->lpVtbl -> Release(This)
#define IColumnsInfo2_GetColumnInfo(This,pcColumns,prgInfo,ppStringsBuffer) \
(This)->lpVtbl -> GetColumnInfo(This,pcColumns,prgInfo,ppStringsBuffer)
#define IColumnsInfo2_MapColumnIDs(This,cColumnIDs,rgColumnIDs,rgColumns) \
(This)->lpVtbl -> MapColumnIDs(This,cColumnIDs,rgColumnIDs,rgColumns)
#define IColumnsInfo2_GetRestrictedColumnInfo(This,cColumnIDMasks,rgColumnIDMasks,dwFlags,pcColumns,prgColumnIDs,prgColumnInfo,ppStringsBuffer) \
(This)->lpVtbl -> GetRestrictedColumnInfo(This,cColumnIDMasks,rgColumnIDMasks,dwFlags,pcColumns,prgColumnIDs,prgColumnInfo,ppStringsBuffer)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsInfo2_RemoteGetRestrictedColumnInfo_Proxy(
IColumnsInfo2 __RPC_FAR * This,
/* [in] */ ULONG cColumnIDMasks,
/* [size_is][unique][in] */ const DBID __RPC_FAR *rgColumnIDMasks,
/* [in] */ DWORD dwFlags,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *prgColumnIDs,
/* [size_is][size_is][unique][out][in] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgColumnInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgNameOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgcolumnidOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
void __RPC_STUB IColumnsInfo2_RemoteGetRestrictedColumnInfo_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IColumnsInfo2_INTERFACE_DEFINED__ */
#ifndef __IRegisterProvider_INTERFACE_DEFINED__
#define __IRegisterProvider_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRegisterProvider
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IRegisterProvider;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733ab9-2a1c-11ce-ade5-00aa0044773d")
IRegisterProvider : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetURLMapping(
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [out] */ CLSID __RPC_FAR *pclsidProvider) = 0;
virtual HRESULT STDMETHODCALLTYPE SetURLMapping(
/* [unique][in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [unique][in] */ REFCLSID rclsidProvider) = 0;
virtual HRESULT STDMETHODCALLTYPE UnregisterProvider(
/* [unique][in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [unique][in] */ REFCLSID rclsidProvider) = 0;
};
#else /* C style interface */
typedef struct IRegisterProviderVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRegisterProvider __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRegisterProvider __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRegisterProvider __RPC_FAR * This);
/* [local] */ HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetURLMapping )(
IRegisterProvider __RPC_FAR * This,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [out] */ CLSID __RPC_FAR *pclsidProvider);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetURLMapping )(
IRegisterProvider __RPC_FAR * This,
/* [unique][in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [unique][in] */ REFCLSID rclsidProvider);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *UnregisterProvider )(
IRegisterProvider __RPC_FAR * This,
/* [unique][in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [unique][in] */ REFCLSID rclsidProvider);
END_INTERFACE
} IRegisterProviderVtbl;
interface IRegisterProvider
{
CONST_VTBL struct IRegisterProviderVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRegisterProvider_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRegisterProvider_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRegisterProvider_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRegisterProvider_GetURLMapping(This,pwszURL,dwReserved,pclsidProvider) \
(This)->lpVtbl -> GetURLMapping(This,pwszURL,dwReserved,pclsidProvider)
#define IRegisterProvider_SetURLMapping(This,pwszURL,dwReserved,rclsidProvider) \
(This)->lpVtbl -> SetURLMapping(This,pwszURL,dwReserved,rclsidProvider)
#define IRegisterProvider_UnregisterProvider(This,pwszURL,dwReserved,rclsidProvider) \
(This)->lpVtbl -> UnregisterProvider(This,pwszURL,dwReserved,rclsidProvider)
#endif /* COBJMACROS */
#endif /* C style interface */
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRegisterProvider_RemoteGetURLMapping_Proxy(
IRegisterProvider __RPC_FAR * This,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [out] */ CLSID __RPC_FAR *pclsidProvider);
void __RPC_STUB IRegisterProvider_RemoteGetURLMapping_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRegisterProvider_SetURLMapping_Proxy(
IRegisterProvider __RPC_FAR * This,
/* [unique][in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [unique][in] */ REFCLSID rclsidProvider);
void __RPC_STUB IRegisterProvider_SetURLMapping_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRegisterProvider_UnregisterProvider_Proxy(
IRegisterProvider __RPC_FAR * This,
/* [unique][in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [unique][in] */ REFCLSID rclsidProvider);
void __RPC_STUB IRegisterProvider_UnregisterProvider_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRegisterProvider_INTERFACE_DEFINED__ */
#endif // UNDER_CE
#ifndef __IGetSession_INTERFACE_DEFINED__
#define __IGetSession_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IGetSession
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object] */
EXTERN_C const IID IID_IGetSession;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733aba-2a1c-11ce-ade5-00aa0044773d")
IGetSession : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetSession(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession) = 0;
};
#else /* C style interface */
typedef struct IGetSessionVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IGetSession __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IGetSession __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IGetSession __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSession )(
IGetSession __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession);
END_INTERFACE
} IGetSessionVtbl;
interface IGetSession
{
CONST_VTBL struct IGetSessionVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IGetSession_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IGetSession_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IGetSession_Release(This) \
(This)->lpVtbl -> Release(This)
#define IGetSession_GetSession(This,riid,ppSession) \
(This)->lpVtbl -> GetSession(This,riid,ppSession)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IGetSession_GetSession_Proxy(
IGetSession __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession);
void __RPC_STUB IGetSession_GetSession_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IGetSession_INTERFACE_DEFINED__ */
#ifndef __IGetSourceRow_INTERFACE_DEFINED__
#define __IGetSourceRow_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IGetSourceRow
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IGetSourceRow;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733abb-2a1c-11ce-ade5-00aa0044773d")
IGetSourceRow : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetSourceRow(
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRow) = 0;
};
#else /* C style interface */
typedef struct IGetSourceRowVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IGetSourceRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IGetSourceRow __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IGetSourceRow __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetSourceRow )(
IGetSourceRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRow);
END_INTERFACE
} IGetSourceRowVtbl;
interface IGetSourceRow
{
CONST_VTBL struct IGetSourceRowVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IGetSourceRow_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IGetSourceRow_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IGetSourceRow_Release(This) \
(This)->lpVtbl -> Release(This)
#define IGetSourceRow_GetSourceRow(This,riid,ppRow) \
(This)->lpVtbl -> GetSourceRow(This,riid,ppRow)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IGetSourceRow_GetSourceRow_Proxy(
IGetSourceRow __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRow);
void __RPC_STUB IGetSourceRow_GetSourceRow_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IGetSourceRow_INTERFACE_DEFINED__ */
#ifndef __IRowsetCurrentIndex_INTERFACE_DEFINED__
#define __IRowsetCurrentIndex_INTERFACE_DEFINED__
/****************************************
* Generated header for interface: IRowsetCurrentIndex
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [unique][uuid][object][local] */
EXTERN_C const IID IID_IRowsetCurrentIndex;
#if defined(__cplusplus) && !defined(CINTERFACE)
interface DECLSPEC_UUID("0c733abd-2a1c-11ce-ade5-00aa0044773d")
IRowsetCurrentIndex : public IRowsetIndex
{
public:
virtual HRESULT STDMETHODCALLTYPE GetIndex(
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID) = 0;
virtual HRESULT STDMETHODCALLTYPE SetIndex(
/* [in] */ DBID __RPC_FAR *pIndexID) = 0;
};
#else /* C style interface */
typedef struct IRowsetCurrentIndexVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *QueryInterface )(
IRowsetCurrentIndex __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *AddRef )(
IRowsetCurrentIndex __RPC_FAR * This);
ULONG ( STDMETHODCALLTYPE __RPC_FAR *Release )(
IRowsetCurrentIndex __RPC_FAR * This);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIndexInfo )(
IRowsetCurrentIndex __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcKeyColumns,
/* [size_is][size_is][out] */ DBINDEXCOLUMNDESC __RPC_FAR *__RPC_FAR *prgIndexColumnDesc,
/* [out][in] */ ULONG __RPC_FAR *pcIndexProperties,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgIndexProperties);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *Seek )(
IRowsetCurrentIndex __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cKeyValues,
/* [in] */ void __RPC_FAR *pData,
/* [in] */ DBSEEK dwSeekOptions);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetRange )(
IRowsetCurrentIndex __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cStartKeyColumns,
/* [in] */ void __RPC_FAR *pStartData,
/* [in] */ ULONG cEndKeyColumns,
/* [in] */ void __RPC_FAR *pEndData,
/* [in] */ DBRANGE dwRangeOptions);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *GetIndex )(
IRowsetCurrentIndex __RPC_FAR * This,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID);
HRESULT ( STDMETHODCALLTYPE __RPC_FAR *SetIndex )(
IRowsetCurrentIndex __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pIndexID);
END_INTERFACE
} IRowsetCurrentIndexVtbl;
interface IRowsetCurrentIndex
{
CONST_VTBL struct IRowsetCurrentIndexVtbl __RPC_FAR *lpVtbl;
};
#ifdef COBJMACROS
#define IRowsetCurrentIndex_QueryInterface(This,riid,ppvObject) \
(This)->lpVtbl -> QueryInterface(This,riid,ppvObject)
#define IRowsetCurrentIndex_AddRef(This) \
(This)->lpVtbl -> AddRef(This)
#define IRowsetCurrentIndex_Release(This) \
(This)->lpVtbl -> Release(This)
#define IRowsetCurrentIndex_GetIndexInfo(This,pcKeyColumns,prgIndexColumnDesc,pcIndexProperties,prgIndexProperties) \
(This)->lpVtbl -> GetIndexInfo(This,pcKeyColumns,prgIndexColumnDesc,pcIndexProperties,prgIndexProperties)
#define IRowsetCurrentIndex_Seek(This,hAccessor,cKeyValues,pData,dwSeekOptions) \
(This)->lpVtbl -> Seek(This,hAccessor,cKeyValues,pData,dwSeekOptions)
#define IRowsetCurrentIndex_SetRange(This,hAccessor,cStartKeyColumns,pStartData,cEndKeyColumns,pEndData,dwRangeOptions) \
(This)->lpVtbl -> SetRange(This,hAccessor,cStartKeyColumns,pStartData,cEndKeyColumns,pEndData,dwRangeOptions)
#define IRowsetCurrentIndex_GetIndex(This,ppIndexID) \
(This)->lpVtbl -> GetIndex(This,ppIndexID)
#define IRowsetCurrentIndex_SetIndex(This,pIndexID) \
(This)->lpVtbl -> SetIndex(This,pIndexID)
#endif /* COBJMACROS */
#endif /* C style interface */
HRESULT STDMETHODCALLTYPE IRowsetCurrentIndex_GetIndex_Proxy(
IRowsetCurrentIndex __RPC_FAR * This,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID);
void __RPC_STUB IRowsetCurrentIndex_GetIndex_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
HRESULT STDMETHODCALLTYPE IRowsetCurrentIndex_SetIndex_Proxy(
IRowsetCurrentIndex __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pIndexID);
void __RPC_STUB IRowsetCurrentIndex_SetIndex_Stub(
IRpcStubBuffer *This,
IRpcChannelBuffer *_pRpcChannelBuffer,
PRPC_MESSAGE _pRpcMessage,
DWORD *_pdwStubPhase);
#endif /* __IRowsetCurrentIndex_INTERFACE_DEFINED__ */
/****************************************
* Generated header for interface: __MIDL_itf_oledb_0242
* at Thu Nov 12 23:35:28 1998
* using MIDL 3.01.75
****************************************/
/* [local] */
//
// IID values
//
// IID_IAccessor = {0x0c733a8c,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowset = {0x0c733a7c,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetInfo = {0x0c733a55,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetLocate = {0x0c733a7d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetResynch = {0x0c733a84,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetScroll = {0x0c733a7e,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetChange = {0x0c733a05,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetUpdate = {0x0c733a6d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetIdentity = {0x0c733a09,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetNotify = {0x0c733a83,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetIndex = {0x0c733a82,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICommand = {0x0c733a63,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IMultipleResults = {0x0c733a90,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IConvertType = {0x0c733a88,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICommandPrepare = {0x0c733a26,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICommandProperties = {0x0c733a79,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICommandText = {0x0c733a27,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICommandWithParameters = {0x0c733a64,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IColumnsRowset = {0x0c733a10,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IColumnsInfo = {0x0c733a11,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBCreateCommand = {0x0c733a1d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBCreateSession = {0x0c733a5d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ISourcesRowset = {0x0c733a1e,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBProperties = {0x0c733a8a,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBInitialize = {0x0c733a8b,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBInfo = {0x0c733a89,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBDataSourceAdmin = {0x0c733a7a,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ISessionProperties = {0x0c733a85,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IIndexDefinition = {0x0c733a68,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITableDefinition = {0x0c733a86,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IOpenRowset = {0x0c733a69,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBSchemaRowset = {0x0c733a7b,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IErrorRecords = {0x0c733a67,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IErrorLookup = {0x0c733a66,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ISQLErrorInfo = {0x0c733a74,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IGetDataSource = {0x0c733a75,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITransactionLocal = {0x0c733a5f,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITransactionJoin = {0x0c733a5e,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITransactionObject = {0x0c733a60,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IChapteredRowset = {0x0c733a93,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IDBAsynchNotify = {0x0c733a96,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IDBAsynchStatus = {0x0c733a95,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IRowsetFind = {0x0c733a9d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IRowPosition = {0x0c733a94,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IRowPositionChange = {0x0997a571,0x126e,0x11d0,{0x9f,0x8a,0x00,0xa0,0xc9,0xa0,0x63,0x1e}}
//IID_IViewRowset = {0x0c733a97,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IViewChapter = {0x0c733a98,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IViewSort = {0x0c733a9a,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IViewFilter = {0x0c733a9b,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
//IID_IRowsetView = {0x0c733a99,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IMDDataset = {0xa07cccd1,0x8148,0x11d0,{0x87,0xbb,0x00,0xc0,0x4f,0xc3,0x39,0x42}}
// IID_IMDFind = {0xa07cccd2,0x8148,0x11d0,{0x87,0xbb,0x00,0xc0,0x4f,0xc3,0x39,0x42}}
// IID_IMDRangeRowset = {0x0c733aa0,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IAlterTable = {0x0c733aa5,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IAlterIndex = {0x0c733aa6,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICommandPersist = {0x0c733aa7,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetChapterMember = {0x0c733aa8,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetRefresh = {0x0c733aa9,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IParentRowset = {0x0c733aaa,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITrusteeAdmin = {0c733aa1,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITrusteeGroupAdmin = {0c733aa2,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IObjectAccessControl = {0c733aa3,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ISecurityInfo = {0c733aa4,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRow = {0c733ab4,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowChange = {0c733ab5,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowSchemaChange = {0c733aae,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IGetRow = {0c733aaf,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IScopedOperations = {0c733ab0,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IBindResource = {0c733ab1,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ICreateRow = {0c733ab2,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IDBResetProperties = {0c733ab3,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IColumnsInfo2 = {0c733ab8,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRegisterProvider = {0c733ab9,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IGetSession = {0c733aba,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IGetSourceRow = {0c733abb,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_ITableCreation = {0c733abc,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
// IID_IRowsetCurrentIndex = {0c733abd,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}}
extern const OLEDBDECLSPEC IID IID_IAccessor = {0x0c733a8c,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowset = {0x0c733a7c,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetInfo = {0x0c733a55,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetLocate = {0x0c733a7d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetResynch = {0x0c733a84,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetScroll = {0x0c733a7e,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IChapteredRowset = {0x0c733a93,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetFind = {0x0c733a9d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowPosition = {0x0c733a94,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowPositionChange = {0x0997a571,0x126e,0x11d0,{0x9f,0x8a,0x00,0xa0,0xc9,0xa0,0x63,0x1e}};
extern const OLEDBDECLSPEC IID IID_IViewRowset = {0x0c733a97,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IViewChapter = {0x0c733a98,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IViewSort = {0x0c733a9a,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IViewFilter = {0x0c733a9b,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetView = {0x0c733a99,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetExactScroll = {0x0c733a7f,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetChange = {0x0c733a05,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetUpdate = {0x0c733a6d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetIdentity = {0x0c733a09,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetNotify = {0x0c733a83,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetIndex = {0x0c733a82,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICommand = {0x0c733a63,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IMultipleResults = {0x0c733a90,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IConvertType = {0x0c733a88,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICommandPrepare = {0x0c733a26,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICommandProperties = {0x0c733a79,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICommandText = {0x0c733a27,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICommandWithParameters = {0x0c733a64,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IColumnsRowset = {0x0c733a10,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IColumnsInfo = {0x0c733a11,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBCreateCommand = {0x0c733a1d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBCreateSession = {0x0c733a5d,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ISourcesRowset = {0x0c733a1e,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBProperties = {0x0c733a8a,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBInitialize = {0x0c733a8b,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBInfo = {0x0c733a89,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBDataSourceAdmin = {0x0c733a7a,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBAsynchNotify = {0x0c733a96,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBAsynchStatus = {0x0c733a95,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ISessionProperties = {0x0c733a85,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IIndexDefinition = {0x0c733a68,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITableDefinition = {0x0c733a86,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IOpenRowset = {0x0c733a69,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBSchemaRowset = {0x0c733a7b,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IMDDataset = {0xa07cccd1,0x8148,0x11d0,{0x87,0xbb,0x00,0xc0,0x4f,0xc3,0x39,0x42}};
extern const OLEDBDECLSPEC IID IID_IMDFind = {0xa07cccd2,0x8148,0x11d0,{0x87,0xbb,0x00,0xc0,0x4f,0xc3,0x39,0x42}};
extern const OLEDBDECLSPEC IID IID_IMDRangeRowset = {0x0c733aa0,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IAlterTable = {0x0c733aa5,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IAlterIndex = {0x0c733aa6,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetChapterMember = {0x0c733aa8,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICommandPersist = {0x0c733aa7,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetRefresh = {0x0c733aa9,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IParentRowset = {0x0c733aaa,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IErrorRecords = {0x0c733a67,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IErrorLookup = {0x0c733a66,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ISQLErrorInfo = {0x0c733a74,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IGetDataSource = {0x0c733a75,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITransactionLocal = {0x0c733a5f,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITransactionJoin = {0x0c733a5e,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITransactionObject = {0x0c733a60,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITrusteeAdmin = {0x0c733aa1,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITrusteeGroupAdmin = {0x0c733aa2,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IObjectAccessControl = {0x0c733aa3,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ISecurityInfo = {0x0c733aa4,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITableCreation = {0x0c733abc,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ITableDefinitionWithConstraints = {0x0c733aab,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRow = {0x0c733ab4,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowChange = {0x0c733ab5,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowSchemaChange = {0x0c733aae,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IGetRow = {0x0c733aaf,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IBindResource = {0x0c733ab1,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IScopedOperations = {0x0c733ab0,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_ICreateRow = {0x0c733ab2,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IDBBinderProperties = {0x0c733ab3,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IColumnsInfo2 = {0x0c733ab8,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRegisterProvider = {0x0c733ab9,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IGetSession = {0x0c733aba,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IGetSourceRow = {0x0c733abb,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
extern const OLEDBDECLSPEC IID IID_IRowsetCurrentIndex = {0x0c733abd,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
#include <poppack.h> // restore original structure packing
extern RPC_IF_HANDLE __MIDL_itf_oledb_0242_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_oledb_0242_v0_0_s_ifspec;
#ifdef OLEDBPROXY
/* Additional Prototypes for ALL interfaces */
unsigned long __RPC_USER BSTR_UserSize( unsigned long __RPC_FAR *, unsigned long , BSTR __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER BSTR_UserMarshal( unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER BSTR_UserUnmarshal(unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, BSTR __RPC_FAR * );
void __RPC_USER BSTR_UserFree( unsigned long __RPC_FAR *, BSTR __RPC_FAR * );
unsigned long __RPC_USER VARIANT_UserSize( unsigned long __RPC_FAR *, unsigned long , VARIANT __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER VARIANT_UserMarshal( unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, VARIANT __RPC_FAR * );
unsigned char __RPC_FAR * __RPC_USER VARIANT_UserUnmarshal(unsigned long __RPC_FAR *, unsigned char __RPC_FAR *, VARIANT __RPC_FAR * );
void __RPC_USER VARIANT_UserFree( unsigned long __RPC_FAR *, VARIANT __RPC_FAR * );
/* [local] */ HRESULT STDMETHODCALLTYPE IAccessor_AddRefAccessor_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_AddRefAccessor_Stub(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IAccessor_CreateAccessor_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ DBACCESSORFLAGS dwAccessorFlags,
/* [in] */ ULONG cBindings,
/* [size_is][in] */ const DBBINDING __RPC_FAR rgBindings[ ],
/* [in] */ ULONG cbRowSize,
/* [out] */ HACCESSOR __RPC_FAR *phAccessor,
/* [size_is][out] */ DBBINDSTATUS __RPC_FAR rgStatus[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_CreateAccessor_Stub(
IAccessor __RPC_FAR * This,
/* [in] */ DBACCESSORFLAGS dwAccessorFlags,
/* [in] */ ULONG cBindings,
/* [size_is][unique][in] */ DBBINDING __RPC_FAR *rgBindings,
/* [in] */ ULONG cbRowSize,
/* [out] */ HACCESSOR __RPC_FAR *phAccessor,
/* [size_is][unique][out][in] */ DBBINDSTATUS __RPC_FAR *rgStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IAccessor_GetBindings_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ DBACCESSORFLAGS __RPC_FAR *pdwAccessorFlags,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_GetBindings_Stub(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [out] */ DBACCESSORFLAGS __RPC_FAR *pdwAccessorFlags,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IAccessor_ReleaseAccessor_Proxy(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IAccessor_ReleaseAccessor_Stub(
IAccessor __RPC_FAR * This,
/* [in] */ HACCESSOR hAccessor,
/* [unique][out][in] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_GetProperties_Proxy(
IRowsetInfo __RPC_FAR * This,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_GetProperties_Stub(
IRowsetInfo __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_GetReferencedRowset_Proxy(
IRowsetInfo __RPC_FAR * This,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppReferencedRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_GetReferencedRowset_Stub(
IRowsetInfo __RPC_FAR * This,
/* [in] */ ULONG iOrdinal,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppReferencedRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_GetSpecification_Proxy(
IRowsetInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetInfo_GetSpecification_Stub(
IRowsetInfo __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSpecification,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IChapteredRowset_AddRefChapter_Proxy(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IChapteredRowset_AddRefChapter_Stub(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IChapteredRowset_ReleaseChapter_Proxy(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IChapteredRowset_ReleaseChapter_Stub(
IChapteredRowset __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG __RPC_FAR *pcRefCount,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowPosition_ClearRowPosition_Proxy(
IRowPosition __RPC_FAR * This);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_ClearRowPosition_Stub(
IRowPosition __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowPosition_GetRowPosition_Proxy(
IRowPosition __RPC_FAR * This,
/* [out] */ HCHAPTER __RPC_FAR *phChapter,
/* [out] */ HROW __RPC_FAR *phRow,
/* [out] */ DBPOSITIONFLAGS __RPC_FAR *pdwPositionFlags);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_GetRowPosition_Stub(
IRowPosition __RPC_FAR * This,
/* [out] */ HCHAPTER __RPC_FAR *phChapter,
/* [out] */ HROW __RPC_FAR *phRow,
/* [out] */ DBPOSITIONFLAGS __RPC_FAR *pdwPositionFlags,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowPosition_GetRowset_Proxy(
IRowPosition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_GetRowset_Stub(
IRowPosition __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowPosition_Initialize_Proxy(
IRowPosition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_Initialize_Stub(
IRowPosition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowPosition_SetRowPosition_Proxy(
IRowPosition __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow,
/* [in] */ DBPOSITIONFLAGS dwPositionFlags);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPosition_SetRowPosition_Stub(
IRowPosition __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ HROW hRow,
/* [in] */ DBPOSITIONFLAGS dwPositionFlags,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowPositionChange_OnRowPositionChange_Proxy(
IRowPositionChange __RPC_FAR * This,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowPositionChange_OnRowPositionChange_Stub(
IRowPositionChange __RPC_FAR * This,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewRowset_GetSpecification_Proxy(
IViewRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewRowset_GetSpecification_Stub(
IViewRowset __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewRowset_OpenViewRowset_Proxy(
IViewRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewRowset_OpenViewRowset_Stub(
IViewRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewChapter_GetSpecification_Proxy(
IViewChapter __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewChapter_GetSpecification_Stub(
IViewChapter __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewChapter_OpenViewChapter_Proxy(
IViewChapter __RPC_FAR * This,
/* [in] */ HCHAPTER hSource,
/* [out] */ HCHAPTER __RPC_FAR *phViewChapter);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewChapter_OpenViewChapter_Stub(
IViewChapter __RPC_FAR * This,
/* [in] */ HCHAPTER hSource,
/* [out] */ HCHAPTER __RPC_FAR *phViewChapter,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewSort_GetSortOrder_Proxy(
IViewSort __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcValues,
/* [out] */ ULONG __RPC_FAR *__RPC_FAR prgColumns[ ],
/* [out] */ DBSORT __RPC_FAR *__RPC_FAR prgOrders[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewSort_GetSortOrder_Stub(
IViewSort __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcValues,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgColumns,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgOrders,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewSort_SetSortOrder_Proxy(
IViewSort __RPC_FAR * This,
/* [in] */ ULONG cValues,
/* [size_is][in] */ const ULONG __RPC_FAR rgColumns[ ],
/* [size_is][in] */ const DBSORT __RPC_FAR rgOrders[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewSort_SetSortOrder_Stub(
IViewSort __RPC_FAR * This,
/* [in] */ ULONG cValues,
/* [size_is][in] */ const ULONG __RPC_FAR *rgColumns,
/* [size_is][in] */ const DBSORT __RPC_FAR *rgOrders,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IViewFilter_GetFilterBindings_Proxy(
IViewFilter __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcBindings,
/* [out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IViewFilter_GetFilterBindings_Stub(
IViewFilter __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcBindings,
/* [size_is][size_is][out] */ DBBINDING __RPC_FAR *__RPC_FAR *prgBindings,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetView_CreateView_Proxy(
IRowsetView __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetView_CreateView_Stub(
IRowsetView __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetView_GetView_Proxy(
IRowsetView __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ REFIID riid,
/* [out] */ HCHAPTER __RPC_FAR *phChapterSource,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetView_GetView_Stub(
IRowsetView __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ REFIID riid,
/* [out] */ HCHAPTER __RPC_FAR *phChapterSource,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppView,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetIdentity_IsSameRow_Proxy(
IRowsetIdentity __RPC_FAR * This,
/* [in] */ HROW hThisRow,
/* [in] */ HROW hThatRow);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetIdentity_IsSameRow_Stub(
IRowsetIdentity __RPC_FAR * This,
/* [in] */ HROW hThisRow,
/* [in] */ HROW hThatRow,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_OnFieldChange_Proxy(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ HROW hRow,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ ULONG __RPC_FAR rgColumns[ ],
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_OnFieldChange_Stub(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ HROW hRow,
/* [in] */ ULONG cColumns,
/* [size_is][in] */ ULONG __RPC_FAR *rgColumns,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_OnRowChange_Proxy(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR rghRows[ ],
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_OnRowChange_Stub(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ ULONG cRows,
/* [size_is][in] */ const HROW __RPC_FAR *rghRows,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_OnRowsetChange_Proxy(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRowsetNotify_OnRowsetChange_Stub(
IRowsetNotify __RPC_FAR * This,
/* [in] */ IRowset __RPC_FAR *pRowset,
/* [in] */ DBREASON eReason,
/* [in] */ DBEVENTPHASE ePhase,
/* [in] */ BOOL fCantDeny,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommand_Cancel_Proxy(
ICommand __RPC_FAR * This);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommand_Cancel_Stub(
ICommand __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommand_Execute_Proxy(
ICommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [out][in] */ DBPARAMS __RPC_FAR *pParams,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommand_Execute_Stub(
ICommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ HACCESSOR hAccessor,
/* [in] */ ULONG cParamSets,
/* [in] */ ULONG cbData,
/* [size_is][unique][out][in] */ BYTE __RPC_FAR *pbData,
/* [unique][out][in] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommand_GetDBSession_Proxy(
ICommand __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommand_GetDBSession_Stub(
ICommand __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSession,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IMultipleResults_GetResult_Proxy(
IMultipleResults __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LONG reserved,
/* [in] */ REFIID riid,
/* [out] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IMultipleResults_GetResult_Stub(
IMultipleResults __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LONG reserved,
/* [in] */ REFIID riid,
/* [unique][out][in] */ LONG __RPC_FAR *pcRowsAffected,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IConvertType_CanConvert_Proxy(
IConvertType __RPC_FAR * This,
/* [in] */ DBTYPE wFromType,
/* [in] */ DBTYPE wToType,
/* [in] */ DBCONVERTFLAGS dwConvertFlags);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IConvertType_CanConvert_Stub(
IConvertType __RPC_FAR * This,
/* [in] */ DBTYPE wFromType,
/* [in] */ DBTYPE wToType,
/* [in] */ DBCONVERTFLAGS dwConvertFlags,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandPrepare_Prepare_Proxy(
ICommandPrepare __RPC_FAR * This,
/* [in] */ ULONG cExpectedRuns);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandPrepare_Prepare_Stub(
ICommandPrepare __RPC_FAR * This,
/* [in] */ ULONG cExpectedRuns,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandPrepare_Unprepare_Proxy(
ICommandPrepare __RPC_FAR * This);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandPrepare_Unprepare_Stub(
ICommandPrepare __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandProperties_GetProperties_Proxy(
ICommandProperties __RPC_FAR * This,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandProperties_GetProperties_Stub(
ICommandProperties __RPC_FAR * This,
/* [in] */ const ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandProperties_SetProperties_Proxy(
ICommandProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandProperties_SetProperties_Stub(
ICommandProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandText_GetCommandText_Proxy(
ICommandText __RPC_FAR * This,
/* [out][in] */ GUID __RPC_FAR *pguidDialect,
/* [out] */ LPOLESTR __RPC_FAR *ppwszCommand);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandText_GetCommandText_Stub(
ICommandText __RPC_FAR * This,
/* [unique][out][in] */ GUID __RPC_FAR *pguidDialect,
/* [out] */ LPOLESTR __RPC_FAR *ppwszCommand,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandText_SetCommandText_Proxy(
ICommandText __RPC_FAR * This,
/* [in] */ REFGUID rguidDialect,
/* [unique][in] */ LPCOLESTR pwszCommand);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandText_SetCommandText_Stub(
ICommandText __RPC_FAR * This,
/* [in] */ REFGUID rguidDialect,
/* [unique][in] */ LPCOLESTR pwszCommand,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_GetParameterInfo_Proxy(
ICommandWithParameters __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcParams,
/* [size_is][size_is][out] */ DBPARAMINFO __RPC_FAR *__RPC_FAR *prgParamInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppNamesBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_GetParameterInfo_Stub(
ICommandWithParameters __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcParams,
/* [size_is][size_is][out] */ DBPARAMINFO __RPC_FAR *__RPC_FAR *prgParamInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgNameOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbNamesBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppNamesBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_MapParameterNames_Proxy(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParamNames,
/* [size_is][in] */ const OLECHAR __RPC_FAR *__RPC_FAR rgParamNames[ ],
/* [size_is][out] */ LONG __RPC_FAR rgParamOrdinals[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_MapParameterNames_Stub(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParamNames,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgParamNames,
/* [size_is][out] */ LONG __RPC_FAR *rgParamOrdinals,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_SetParameterInfo_Proxy(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParams,
/* [size_is][unique][in] */ const ULONG __RPC_FAR rgParamOrdinals[ ],
/* [size_is][unique][in] */ const DBPARAMBINDINFO __RPC_FAR rgParamBindInfo[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICommandWithParameters_SetParameterInfo_Stub(
ICommandWithParameters __RPC_FAR * This,
/* [in] */ ULONG cParams,
/* [size_is][unique][in] */ const ULONG __RPC_FAR *rgParamOrdinals,
/* [size_is][unique][in] */ const DBPARAMBINDINFO __RPC_FAR *rgParamBindInfo,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IColumnsRowset_GetAvailableColumns_Proxy(
IColumnsRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcOptColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgOptColumns);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsRowset_GetAvailableColumns_Stub(
IColumnsRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcOptColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgOptColumns,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IColumnsRowset_GetColumnsRowset_Proxy(
IColumnsRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG cOptColumns,
/* [size_is][in] */ const DBID __RPC_FAR rgOptColumns[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppColRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsRowset_GetColumnsRowset_Stub(
IColumnsRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ ULONG cOptColumns,
/* [size_is][unique][in] */ const DBID __RPC_FAR *rgOptColumns,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppColRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IColumnsInfo_GetColumnInfo_Proxy(
IColumnsInfo __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsInfo_GetColumnInfo_Stub(
IColumnsInfo __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgNameOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgcolumnidOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IColumnsInfo_MapColumnIDs_Proxy(
IColumnsInfo __RPC_FAR * This,
/* [in] */ ULONG cColumnIDs,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDs[ ],
/* [size_is][out] */ ULONG __RPC_FAR rgColumns[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsInfo_MapColumnIDs_Stub(
IColumnsInfo __RPC_FAR * This,
/* [in] */ ULONG cColumnIDs,
/* [size_is][in] */ const DBID __RPC_FAR *rgColumnIDs,
/* [size_is][out] */ ULONG __RPC_FAR *rgColumns,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBCreateCommand_CreateCommand_Proxy(
IDBCreateCommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppCommand);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBCreateCommand_CreateCommand_Stub(
IDBCreateCommand __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppCommand,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBCreateSession_CreateSession_Proxy(
IDBCreateSession __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBCreateSession_CreateSession_Stub(
IDBCreateSession __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ISourcesRowset_GetSourcesRowset_Proxy(
ISourcesRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgProperties[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSourcesRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISourcesRowset_GetSourcesRowset_Stub(
ISourcesRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgProperties,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppSourcesRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBProperties_GetProperties_Proxy(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBProperties_GetProperties_Stub(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBProperties_GetPropertyInfo_Proxy(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBProperties_GetPropertyInfo_Stub(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out][in] */ ULONG __RPC_FAR *pcOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgDescOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbDescBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBProperties_SetProperties_Proxy(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBProperties_SetProperties_Stub(
IDBProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBInitialize_Initialize_Proxy(
IDBInitialize __RPC_FAR * This);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInitialize_Initialize_Stub(
IDBInitialize __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBInitialize_Uninitialize_Proxy(
IDBInitialize __RPC_FAR * This);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInitialize_Uninitialize_Stub(
IDBInitialize __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBInfo_GetKeywords_Proxy(
IDBInfo __RPC_FAR * This,
/* [out] */ LPOLESTR __RPC_FAR *ppwszKeywords);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInfo_GetKeywords_Stub(
IDBInfo __RPC_FAR * This,
/* [unique][out][in] */ LPOLESTR __RPC_FAR *ppwszKeywords,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBInfo_GetLiteralInfo_Proxy(
IDBInfo __RPC_FAR * This,
/* [in] */ ULONG cLiterals,
/* [size_is][in] */ const DBLITERAL __RPC_FAR rgLiterals[ ],
/* [out][in] */ ULONG __RPC_FAR *pcLiteralInfo,
/* [size_is][size_is][out] */ DBLITERALINFO __RPC_FAR *__RPC_FAR *prgLiteralInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppCharBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBInfo_GetLiteralInfo_Stub(
IDBInfo __RPC_FAR * This,
/* [in] */ ULONG cLiterals,
/* [size_is][unique][in] */ const DBLITERAL __RPC_FAR *rgLiterals,
/* [out][in] */ ULONG __RPC_FAR *pcLiteralInfo,
/* [size_is][size_is][out] */ DBLITERALINFO __RPC_FAR *__RPC_FAR *prgLiteralInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgLVOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgICOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgISCOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbCharBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppCharBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_CreateDataSource_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_CreateDataSource_Stub(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFIID riid,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppDBSession,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_DestroyDataSource_Proxy(
IDBDataSourceAdmin __RPC_FAR * This);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_DestroyDataSource_Stub(
IDBDataSourceAdmin __RPC_FAR * This,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_GetCreationProperties_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_GetCreationProperties_Stub(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertyInfoSets,
/* [size_is][size_is][out] */ DBPROPINFOSET __RPC_FAR *__RPC_FAR *prgPropertyInfoSets,
/* [out][in] */ ULONG __RPC_FAR *pcOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgDescOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbDescBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppDescBuffer,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_ModifyDataSource_Proxy(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBDataSourceAdmin_ModifyDataSource_Stub(
IDBDataSourceAdmin __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_OnLowResource_Proxy(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ DWORD dwReserved);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_OnLowResource_Stub(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ DWORD dwReserved,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_OnProgress_Proxy(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ ULONG ulProgress,
/* [in] */ ULONG ulProgressMax,
/* [in] */ DBASYNCHPHASE eAsynchPhase,
/* [in] */ LPOLESTR pwszStatusText);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_OnProgress_Stub(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ ULONG ulProgress,
/* [in] */ ULONG ulProgressMax,
/* [in] */ DBASYNCHPHASE eAsynchPhase,
/* [in] */ LPOLESTR pwszStatusText,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_OnStop_Proxy(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ HRESULT hrStatus,
/* [in] */ LPOLESTR pwszStatusText);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchNotify_OnStop_Stub(
IDBAsynchNotify __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [in] */ HRESULT hrStatus,
/* [in] */ LPOLESTR pwszStatusText,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBAsynchStatus_Abort_Proxy(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchStatus_Abort_Stub(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBAsynchStatus_GetStatus_Proxy(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ ULONG __RPC_FAR *pulProgress,
/* [out] */ ULONG __RPC_FAR *pulProgressMax,
/* [out] */ DBASYNCHPHASE __RPC_FAR *peAsynchPhase,
/* [out] */ LPOLESTR __RPC_FAR *ppwszStatusText);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBAsynchStatus_GetStatus_Stub(
IDBAsynchStatus __RPC_FAR * This,
/* [in] */ HCHAPTER hChapter,
/* [in] */ DBASYNCHOP eOperation,
/* [out] */ ULONG __RPC_FAR *pulProgress,
/* [out] */ ULONG __RPC_FAR *pulProgressMax,
/* [out] */ DBASYNCHPHASE __RPC_FAR *peAsynchPhase,
/* [out] */ LPOLESTR __RPC_FAR *ppwszStatusText,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ISessionProperties_GetProperties_Proxy(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][in] */ const DBPROPIDSET __RPC_FAR rgPropertyIDSets[ ],
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISessionProperties_GetProperties_Stub(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertyIDSets,
/* [size_is][unique][in] */ const DBPROPIDSET __RPC_FAR *rgPropertyIDSets,
/* [out][in] */ ULONG __RPC_FAR *pcPropertySets,
/* [size_is][size_is][out] */ DBPROPSET __RPC_FAR *__RPC_FAR *prgPropertySets,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ISessionProperties_SetProperties_Proxy(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISessionProperties_SetProperties_Stub(
ISessionProperties __RPC_FAR * This,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IIndexDefinition_CreateIndex_Proxy(
IIndexDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ ULONG cIndexColumnDescs,
/* [size_is][in] */ const DBINDEXCOLUMNDESC __RPC_FAR rgIndexColumnDescs[ ],
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IIndexDefinition_CreateIndex_Stub(
IIndexDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ ULONG cIndexColumnDescs,
/* [size_is][in] */ const DBINDEXCOLUMNDESC __RPC_FAR *rgIndexColumnDescs,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *ppIndexID,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IIndexDefinition_DropIndex_Proxy(
IIndexDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IIndexDefinition_DropIndex_Stub(
IIndexDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITableDefinition_CreateTable_Proxy(
ITableDefinition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR rgColumnDescs[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_CreateTable_Stub(
ITableDefinition __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [in] */ ULONG cColumnDescs,
/* [size_is][in] */ const DBCOLUMNDESC __RPC_FAR *rgColumnDescs,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *ppTableID,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITableDefinition_DropTable_Proxy(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_DropTable_Stub(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITableDefinition_AddColumn_Proxy(
ITableDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [out][in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [out] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_AddColumn_Stub(
ITableDefinition __RPC_FAR * This,
/* [in] */ DBID __RPC_FAR *pTableID,
/* [in] */ DBCOLUMNDESC __RPC_FAR *pColumnDesc,
/* [unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *ppColumnID,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITableDefinition_DropColumn_Proxy(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITableDefinition_DropColumn_Stub(
ITableDefinition __RPC_FAR * This,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pColumnID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IOpenRowset_OpenRowset_Proxy(
IOpenRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IOpenRowset_OpenRowset_Stub(
IOpenRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBSchemaRowset_GetRowset_Proxy(
IDBSchemaRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFGUID rguidSchema,
/* [in] */ ULONG cRestrictions,
/* [size_is][in] */ const VARIANT __RPC_FAR rgRestrictions[ ],
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBSchemaRowset_GetRowset_Stub(
IDBSchemaRowset __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ REFGUID rguidSchema,
/* [in] */ ULONG cRestrictions,
/* [size_is][unique][in] */ const VARIANT __RPC_FAR *rgRestrictions,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IDBSchemaRowset_GetSchemas_Proxy(
IDBSchemaRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcSchemas,
/* [size_is][size_is][out] */ GUID __RPC_FAR *__RPC_FAR *prgSchemas,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgRestrictionSupport);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IDBSchemaRowset_GetSchemas_Stub(
IDBSchemaRowset __RPC_FAR * This,
/* [out][in] */ ULONG __RPC_FAR *pcSchemas,
/* [size_is][size_is][out] */ GUID __RPC_FAR *__RPC_FAR *prgSchemas,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgRestrictionSupport,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorRecords_AddErrorRecord_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ IUnknown __RPC_FAR *punkCustomError,
/* [in] */ DWORD dwDynamicErrorID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_AddErrorRecord_Stub(
IErrorRecords __RPC_FAR * This,
/* [in] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ IUnknown __RPC_FAR *punkCustomError,
/* [in] */ DWORD dwDynamicErrorID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetBasicErrorInfo_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ ERRORINFO __RPC_FAR *pErrorInfo);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetBasicErrorInfo_Stub(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ ERRORINFO __RPC_FAR *pErrorInfo,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetCustomErrorObject_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetCustomErrorObject_Stub(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppObject,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetErrorInfo_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ LCID lcid,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfo);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetErrorInfo_Stub(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [in] */ LCID lcid,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfo,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetErrorParameters_Proxy(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ DISPPARAMS __RPC_FAR *pdispparams);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetErrorParameters_Stub(
IErrorRecords __RPC_FAR * This,
/* [in] */ ULONG ulRecordNum,
/* [out] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetRecordCount_Proxy(
IErrorRecords __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcRecords);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorRecords_GetRecordCount_Stub(
IErrorRecords __RPC_FAR * This,
/* [out] */ ULONG __RPC_FAR *pcRecords,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorLookup_GetErrorDescription_Proxy(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrSource,
/* [out] */ BSTR __RPC_FAR *pbstrDescription);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorLookup_GetErrorDescription_Stub(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ DISPPARAMS __RPC_FAR *pdispparams,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrSource,
/* [out] */ BSTR __RPC_FAR *pbstrDescription,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorLookup_GetHelpInfo_Proxy(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrHelpFile,
/* [out] */ DWORD __RPC_FAR *pdwHelpContext);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorLookup_GetHelpInfo_Stub(
IErrorLookup __RPC_FAR * This,
/* [in] */ HRESULT hrError,
/* [in] */ DWORD dwLookupID,
/* [in] */ LCID lcid,
/* [out] */ BSTR __RPC_FAR *pbstrHelpFile,
/* [out] */ DWORD __RPC_FAR *pdwHelpContext,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IErrorLookup_ReleaseErrors_Proxy(
IErrorLookup __RPC_FAR * This,
/* [in] */ const DWORD dwDynamicErrorID);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IErrorLookup_ReleaseErrors_Stub(
IErrorLookup __RPC_FAR * This,
/* [in] */ const DWORD dwDynamicErrorID,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ISQLErrorInfo_GetSQLInfo_Proxy(
ISQLErrorInfo __RPC_FAR * This,
/* [out] */ BSTR __RPC_FAR *pbstrSQLState,
/* [out] */ LONG __RPC_FAR *plNativeError);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ISQLErrorInfo_GetSQLInfo_Stub(
ISQLErrorInfo __RPC_FAR * This,
/* [out] */ BSTR __RPC_FAR *pbstrSQLState,
/* [out] */ LONG __RPC_FAR *plNativeError,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IGetDataSource_GetDataSource_Proxy(
IGetDataSource __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDataSource);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IGetDataSource_GetDataSource_Stub(
IGetDataSource __RPC_FAR * This,
/* [in] */ REFIID riid,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppDataSource,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITransactionLocal_GetOptionsObject_Proxy(
ITransactionLocal __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionLocal_GetOptionsObject_Stub(
ITransactionLocal __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITransactionLocal_StartTransaction_Proxy(
ITransactionLocal __RPC_FAR * This,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [out] */ ULONG __RPC_FAR *pulTransactionLevel);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionLocal_StartTransaction_Stub(
ITransactionLocal __RPC_FAR * This,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [unique][out][in] */ ULONG __RPC_FAR *pulTransactionLevel,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITransactionJoin_GetOptionsObject_Proxy(
ITransactionJoin __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionJoin_GetOptionsObject_Stub(
ITransactionJoin __RPC_FAR * This,
/* [out] */ ITransactionOptions __RPC_FAR *__RPC_FAR *ppOptions,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITransactionJoin_JoinTransaction_Proxy(
ITransactionJoin __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *punkTransactionCoord,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionJoin_JoinTransaction_Stub(
ITransactionJoin __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *punkTransactionCoord,
/* [in] */ ISOLEVEL isoLevel,
/* [in] */ ULONG isoFlags,
/* [in] */ ITransactionOptions __RPC_FAR *pOtherOptions,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE ITransactionObject_GetTransactionObject_Proxy(
ITransactionObject __RPC_FAR * This,
/* [in] */ ULONG ulTransactionLevel,
/* [out] */ ITransaction __RPC_FAR *__RPC_FAR *ppTransactionObject);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ITransactionObject_GetTransactionObject_Stub(
ITransactionObject __RPC_FAR * This,
/* [in] */ ULONG ulTransactionLevel,
/* [out] */ ITransaction __RPC_FAR *__RPC_FAR *ppTransactionObject,
/* [out] */ IErrorInfo __RPC_FAR *__RPC_FAR *ppErrorInfoRem);
/* [local] */ HRESULT STDMETHODCALLTYPE IScopedOperations_Copy_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszSourceURLs[ ],
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszDestURLs[ ],
/* [in] */ DWORD dwCopyFlags,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ],
/* [size_is][out] */ LPOLESTR __RPC_FAR rgpwszNewURLs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_Copy_Stub(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszSourceURLs,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszDestURLs,
/* [in] */ DWORD dwCopyFlags,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out] */ DBSTATUS __RPC_FAR *rgdwStatus,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgulNewURLOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT STDMETHODCALLTYPE IScopedOperations_Move_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszSourceURLs[ ],
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszDestURLs[ ],
/* [in] */ DWORD dwMoveFlags,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ],
/* [size_is][out] */ LPOLESTR __RPC_FAR rgpwszNewURLs[ ],
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_Move_Stub(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszSourceURLs,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszDestURLs,
/* [in] */ DWORD dwMoveFlags,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [size_is][out] */ DBSTATUS __RPC_FAR *rgdwStatus,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgulNewURLOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT STDMETHODCALLTYPE IScopedOperations_Delete_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR rgpwszURLs[ ],
/* [in] */ DWORD dwDeleteFlags,
/* [size_is][out][in] */ DBSTATUS __RPC_FAR rgdwStatus[ ]);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_Delete_Stub(
IScopedOperations __RPC_FAR * This,
/* [in] */ ULONG cRows,
/* [size_is][in] */ LPCOLESTR __RPC_FAR *rgpwszURLs,
/* [in] */ DWORD dwDeleteFlags,
/* [size_is][out] */ DBSTATUS __RPC_FAR *rgdwStatus);
/* [local] */ HRESULT STDMETHODCALLTYPE IScopedOperations_OpenRowset_Proxy(
IScopedOperations __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ],
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IScopedOperations_OpenRowset_Stub(
IScopedOperations __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [unique][in] */ DBID __RPC_FAR *pTableID,
/* [unique][in] */ DBID __RPC_FAR *pIndexID,
/* [in] */ REFIID riid,
/* [in] */ ULONG cPropertySets,
/* [size_is][unique][in] */ DBPROPSET __RPC_FAR *rgPropertySets,
/* [iid_is][unique][out][in] */ IUnknown __RPC_FAR *__RPC_FAR *ppRowset,
/* [in] */ ULONG cTotalProps,
/* [size_is][out] */ DBPROPSTATUS __RPC_FAR *rgPropStatus);
/* [local] */ HRESULT STDMETHODCALLTYPE IBindResource_Bind_Proxy(
IBindResource __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IBindResource_Bind_Stub(
IBindResource __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
/* [local] */ HRESULT STDMETHODCALLTYPE ICreateRow_CreateRow_Proxy(
ICreateRow __RPC_FAR * This,
/* [unique][in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [unique][in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out][in] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [out] */ LPOLESTR __RPC_FAR *ppwszNewURL,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
/* [call_as] */ HRESULT STDMETHODCALLTYPE ICreateRow_CreateRow_Stub(
ICreateRow __RPC_FAR * This,
/* [in] */ IUnknown __RPC_FAR *pUnkOuter,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DBBINDURLFLAG dwBindURLFlags,
/* [in] */ REFGUID rguid,
/* [in] */ REFIID riid,
/* [in] */ IAuthenticate __RPC_FAR *pAuthenticate,
/* [unique][out][in] */ DBIMPLICITSESSION __RPC_FAR *pImplSession,
/* [out] */ DBBINDURLSTATUS __RPC_FAR *pdwBindStatus,
/* [unique][out][in] */ LPOLESTR __RPC_FAR *ppwszNewURL,
/* [iid_is][out] */ IUnknown __RPC_FAR *__RPC_FAR *ppUnk);
/* [local] */ HRESULT STDMETHODCALLTYPE IColumnsInfo2_GetRestrictedColumnInfo_Proxy(
IColumnsInfo2 __RPC_FAR * This,
/* [in] */ ULONG cColumnIDMasks,
/* [size_is][in] */ const DBID __RPC_FAR rgColumnIDMasks[ ],
/* [in] */ DWORD dwFlags,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][out] */ DBID __RPC_FAR *__RPC_FAR *prgColumnIDs,
/* [size_is][size_is][out] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgColumnInfo,
/* [out] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IColumnsInfo2_GetRestrictedColumnInfo_Stub(
IColumnsInfo2 __RPC_FAR * This,
/* [in] */ ULONG cColumnIDMasks,
/* [size_is][unique][in] */ const DBID __RPC_FAR *rgColumnIDMasks,
/* [in] */ DWORD dwFlags,
/* [out][in] */ ULONG __RPC_FAR *pcColumns,
/* [size_is][size_is][unique][out][in] */ DBID __RPC_FAR *__RPC_FAR *prgColumnIDs,
/* [size_is][size_is][unique][out][in] */ DBCOLUMNINFO __RPC_FAR *__RPC_FAR *prgColumnInfo,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgNameOffsets,
/* [size_is][size_is][out] */ ULONG __RPC_FAR *__RPC_FAR *prgcolumnidOffsets,
/* [out][in] */ ULONG __RPC_FAR *pcbStringsBuffer,
/* [size_is][size_is][unique][out][in] */ OLECHAR __RPC_FAR *__RPC_FAR *ppStringsBuffer);
/* [local] */ HRESULT STDMETHODCALLTYPE IRegisterProvider_GetURLMapping_Proxy(
IRegisterProvider __RPC_FAR * This,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [out] */ CLSID __RPC_FAR *pclsidProvider);
/* [call_as] */ HRESULT STDMETHODCALLTYPE IRegisterProvider_GetURLMapping_Stub(
IRegisterProvider __RPC_FAR * This,
/* [in] */ LPCOLESTR pwszURL,
/* [in] */ DWORD dwReserved,
/* [out] */ CLSID __RPC_FAR *pclsidProvider);
#endif // OLEDBPROXY
/* end of Additional Prototypes */
/***************************************************************************
****************************************************************************
SQL CE specific GUIDS, interfaces and properties
***************************************************************************
***************************************************************************/
#else // GUIDS_ONLY
#ifndef OLEDBDECLSPEC
#define OLEDBDECLSPEC
#endif
#endif //GUIDS_ONLY
/***************************************************************************
****************************************************************************
SQL CE specific GUIDS
***************************************************************************
***************************************************************************/
// Microsoft SQL Server Lite for Windows 3.5 Provider (Microsoft.SQLSERVER.CE.OLEDB.3.5)
//
// {F49C559D-E9E5-467C-8C18-3326AAE4EBCC}
//
extern const OLEDBDECLSPEC GUID CLSID_SQLSERVERCE_3_5 = {0xf49c559d, 0xe9e5, 0x467c, {0x8c, 0x18, 0x33, 0x26, 0xaa, 0xe4, 0xeb, 0xcc}};
#define CLSID_SQLSERVERCE CLSID_SQLSERVERCE_3_5
// PUBLISHED: Provider Specific Property Sets
//
// Provider-Specific DBInit Property Set
// {2B9AB5BA-4F6C-4ddd-BF18-24DD4BD41848}
//
extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_DBINIT = {0x2b9ab5ba, 0x4f6c, 0x4ddd, {0xbf, 0x18, 0x24, 0xdd, 0x4b, 0xd4, 0x18, 0x48}};
// Provider-Specific Column Property Set
// {352CC8D5-9181-11d3-B27B-00C04F68DBFF}
//
extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_COLUMN = {0x352cc8d5, 0x9181, 0x11d3, {0xb2, 0x7b, 0x0, 0xc0, 0x4f, 0x68, 0xdb, 0xff}};
// Provider-Specific Rowset Property Set
// {5C17C602-A107-11d3-B27B-00C04F68DBFF}
//
extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_ROWSET = {0x5c17c602, 0xa107, 0x11d3, {0xb2, 0x7b, 0x0, 0xc0, 0x4f, 0x68, 0xdb, 0xff}};
// Provider-Specific Session Property Set
// {22FE7D33-5E5C-4a45-B723-8BED2374A06B}
//
extern const OLEDBDECLSPEC GUID DBPROPSET_SSCE_SESSION = {0x22fe7d33, 0x5e5c, 0x4a45, {0xb7, 0x23, 0x8b, 0xed, 0x23, 0x74, 0xa0, 0x6b}};
#ifndef GUIDS_ONLY
// PUBLISHED Provider specific properties
//
#define DBPROP_SSCE_COL_ROWGUID 0x1F9L // SSCE_COLUMN
#define DBPROP_SSCE_MAXBUFFERSIZE 0x1FAL // SSCE_DBINIT
#define DBPROP_SSCE_DBPASSWORD 0x1FBL // SSCE_DBINIT
#define DBPROP_SSCE_ENCRYPTDATABASE 0x1FCL // SSCE_DBINIT
#define DBPROP_SSCE_DEFAULT_LOCK_ESCALATION 0x1FDL // SSCE_DBINIT
#define DBPROP_SSCE_TEMPFILE_DIRECTORY 0x1FEL // SSCE_DBINIT
#define DBPROP_SSCE_DEFAULT_LOCK_TIMEOUT 0x1FFL // SSCE_DBINIT
#define DBPROP_SSCE_TRANSACTION_COMMIT_MODE 0x200L // SSCE_SESSION
#define DBPROP_SSCE_LOCK_TIMEOUT 0x201L // SSCE_SESSION
#define DBPROP_SSCE_AUTO_SHRINK_THRESHOLD 0x202L // SSCE_DBINIT
#define DBPROP_SSCE_FLUSH_INTERVAL 0x206L // SSCE_DBINIT
#define DBPROP_SSCE_MAX_DATABASE_SIZE 0x20BL // SSCE_DBINIT
#define DBPROP_SSCE_LOCK_ESCALATION 0x20CL // SSCE_SESSION
#define DBPROP_SSCE_LOCK_HINT 0x20DL // SSCE_ROWSET
#define DBPROP_SSCE_TEMPFILE_MAX_SIZE 0x20EL // SSCE_DBINIT
#define DBPROP_SSCE_ENCRYPTIONMODE 0x20FL // SSCE_DBINIT
// Enumeration values for DBPROP_SSCE_LOCK_HINT:
//
#define DBPROPVAL_SSCE_LH_ROWLOCK 0x0001L // Row-level locking
#define DBPROPVAL_SSCE_LH_PAGLOCK 0x0002L // Page-level locking
#define DBPROPVAL_SSCE_LH_TABLOCK 0x0004L // Table-level locking
#define DBPROPVAL_SSCE_LH_DBLOCK 0x0008L // Database-level locking
#define DBPROPVAL_SSCE_LH_NOLOCK 0x0010L // No lock option
#define DBPROPVAL_SSCE_LH_HOLDLOCK 0x0020L // Hold lock option
#define DBPROPVAL_SSCE_LH_UPDLOCK 0x0040L // Update lock type
#define DBPROPVAL_SSCE_LH_XLOCK 0x0080L // Exclusive lock type
// Enumeration values for DBPROP_SSCE_TRANSACTION_COMMIT_MODE:
//
#define DBPROPVAL_SSCE_TCM_DEFAULT 0x0000L // Asynchronously commit transactions to disk
#define DBPROPVAL_SSCE_TCM_FLUSH 0x0001L // Synchronously commit transactions to disk
// Enumeration values for DBPROP_SSCE_DBENCRYPTIONMODE
//
#define DBPROPVAL_SSCE_EM_INVALID 0x0000L
#define DBPROPVAL_SSCE_EM_PLATFORM_DEFAULT 0x0001L // (Default) Best algorithm available on the platform
#define DBPROPVAL_SSCE_EM_ENGINE_DEFAULT 0x0002L // AES128/SHA1
#define DBPROPVAL_SSCE_EM_PPC2003_COMPAT 0x0003L // 3DES/SHA1
// Bit mask specifying which properties in DBPROPSET_SSCE_DBINIT
// were not honored when creating / opening the data source. This
// bit mask is returned as the first parameter in the error object
// if the minor error code is SSCE_M_INITPROPCONFLICT
//
#define SSCE_DBINIT_CONFLICT_MAXBUFFERSIZE (0x00000001)
#define SSCE_DBINIT_CONFLICT_AUTO_SHRINK_THRESHOLD (0x00000004)
#define SSCE_DBINIT_CONFLICT_FLUSH_INTERVAL (0x00000008)
#define SSCE_DBINIT_CONFLICT_MAX_DATABASE_SIZE (0x00000020)
#define SSCE_DBINIT_CONFLICT_TEMPFILE_DIRECTORY (0x00000040)
#define SSCE_DBINIT_CONFLICT_DEFAULTESCALATION (0x00000080)
#define SSCE_DBINIT_CONFLICT_DEFAULTTIMEOUT (0x00000100)
#define SSCE_DBINIT_CONFLICT_MAX_TMPDB_SIZE (0x00000200)
// PUBLISHED: Provider Specific Interfaces
//
// IID_ISSCECompact
//
// NOTE: removed as per raid 9395
//
#if 0
extern const OLEDBDECLSPEC GUID IID_ISSCECompact = {0x35437031,0x85a0,0x11d3,{0x88,0xc4,0x00,0xc0,0x4f,0xd9,0x37,0xf0}};
class ISSCECompact : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE Compact(
/* [in] */ ULONG cPropertySets,
/* [size_is][out][in] */ DBPROPSET __RPC_FAR rgPropertySets[ ]) = 0;
};
#endif
// PUBLISHED: OLEDB 2.6 Specific Properties
//
#define DBPROP_COL_SEED 0x11AL
#define DBPROP_COL_INCREMENT 0x11BL
#define DBPROP_IRowsetBookmark 0x124L
// PUBLISHED: OLEDB 2.6 Defined Rowset Interfaces
//
// Interface: IRowsetBookmark
//
extern const OLEDBDECLSPEC IID IID_IRowsetBookmark = {0x0c733ac2,0x2a1c,0x11ce,{0xad,0xe5,0x00,0xaa,0x00,0x44,0x77,0x3d}};
class IRowsetBookmark : public IUnknown
{
public:
virtual /* [local] */ HRESULT STDMETHODCALLTYPE PositionOnBookmark(
/* [in] */ HCHAPTER hChapter,
/* [in] */ ULONG cbBookmark,
/* [size_is][in] */ const BYTE __RPC_FAR *pBookmark) = 0;
};
// Interface: IRowsetPosition
//
extern const OLEDBDECLSPEC IID IID_IRowsetPosition = {0xc19f4b47,0xab5e,0x49a9,{0x9f,0x2e,0xab,0x7a,0xb5,0xc5,0x59,0x14}};
class IRowsetPosition : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetRecordCount(
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG * pcRows) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurrentPosition(
/* [in] */ HCHAPTER hChapter,
/* [out] */ ULONG * pulPosition) = 0;
};
/*********************************************************************/
#ifdef __cplusplus
}
#endif
#endif // GUIDS_ONLY
#endif // of ! __SQLCE_OLEDB_H__
<file_sep>/7-Zip/CPP/7zip/Archive/XarHandler.cpp
// XarHandler.cpp
#include "StdAfx.h"
#include "../../../C/CpuArch.h"
#include "Common/ComTry.h"
#include "Common/MyXml.h"
#include "Common/StringToInt.h"
#include "Common/UTFConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamObjects.h"
#include "../Common/StreamUtils.h"
#include "../Compress/BZip2Decoder.h"
#include "../Compress/CopyCoder.h"
#include "../Compress/ZlibDecoder.h"
#include "Common/OutStreamWithSha1.h"
#define XAR_SHOW_RAW
#define Get16(p) GetBe16(p)
#define Get32(p) GetBe32(p)
#define Get64(p) GetBe64(p)
namespace NArchive {
namespace NXar {
struct CFile
{
AString Name;
AString Method;
UInt64 Size;
UInt64 PackSize;
UInt64 Offset;
// UInt32 mode;
UInt64 CTime;
UInt64 MTime;
UInt64 ATime;
bool IsDir;
bool HasData;
bool Sha1IsDefined;
Byte Sha1[20];
// bool packSha1IsDefined;
// Byte packSha1[20];
int Parent;
CFile(): IsDir(false), HasData(false), Sha1IsDefined(false),
/* packSha1IsDefined(false), */
Parent(-1), Size(0), PackSize(0), CTime(0), MTime(0), ATime(0) {}
};
class CHandler:
public IInArchive,
public CMyUnknownImp
{
UInt64 _dataStartPos;
CMyComPtr<IInStream> _inStream;
AString _xml;
CObjectVector<CFile> _files;
HRESULT Open2(IInStream *stream);
HRESULT Extract(IInStream *stream);
public:
MY_UNKNOWN_IMP1(IInArchive)
INTERFACE_IInArchive(;)
};
const UInt32 kXmlSizeMax = ((UInt32)1 << 30) - (1 << 14);
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidATime, VT_FILETIME},
{ NULL, kpidMethod, VT_BSTR}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps_NO
static bool ParseNumber(const char *s, int size, UInt32 &res)
{
const char *end;
res = (UInt32)ConvertStringToUInt64(s, &end);
return (end - s == size);
}
static bool ParseUInt64(const CXmlItem &item, const char *name, UInt64 &res)
{
AString s = item.GetSubStringForTag(name);
const char *end;
res = ConvertStringToUInt64(s, &end);
return (end - (const char *)s == s.Length());
}
static UInt64 ParseTime(const CXmlItem &item, const char *name)
{
AString s = item.GetSubStringForTag(name);
if (s.Length() < 20)
return 0;
const char *p = s;
if (p[ 4] != '-' || p[ 7] != '-' || p[10] != 'T' ||
p[13] != ':' || p[16] != ':' || p[19] != 'Z')
return 0;
UInt32 year, month, day, hour, min, sec;
if (!ParseNumber(p, 4, year )) return 0;
if (!ParseNumber(p + 5, 2, month)) return 0;
if (!ParseNumber(p + 8, 2, day )) return 0;
if (!ParseNumber(p + 11, 2, hour )) return 0;
if (!ParseNumber(p + 14, 2, min )) return 0;
if (!ParseNumber(p + 17, 2, sec )) return 0;
UInt64 numSecs;
if (!NWindows::NTime::GetSecondsSince1601(year, month, day, hour, min, sec, numSecs))
return 0;
return numSecs * 10000000;
}
static bool HexToByte(char c, Byte &res)
{
if (c >= '0' && c <= '9') res = c - '0';
else if (c >= 'A' && c <= 'F') res = c - 'A' + 10;
else if (c >= 'a' && c <= 'f') res = c - 'a' + 10;
else return false;
return true;
}
#define METHOD_NAME_ZLIB "zlib"
static bool ParseSha1(const CXmlItem &item, const char *name, Byte *digest)
{
int index = item.FindSubTag(name);
if (index < 0)
return false;
const CXmlItem &checkItem = item.SubItems[index];
AString style = checkItem.GetPropertyValue("style");
if (style == "SHA1")
{
AString s = checkItem.GetSubString();
if (s.Length() != 40)
return false;
for (int i = 0; i < s.Length(); i += 2)
{
Byte b0, b1;
if (!HexToByte(s[i], b0) || !HexToByte(s[i + 1], b1))
return false;
digest[i / 2] = (b0 << 4) | b1;
}
return true;
}
return false;
}
static bool AddItem(const CXmlItem &item, CObjectVector<CFile> &files, int parent)
{
if (!item.IsTag)
return true;
if (item.Name == "file")
{
CFile file;
file.Parent = parent;
parent = files.Size();
file.Name = item.GetSubStringForTag("name");
AString type = item.GetSubStringForTag("type");
if (type == "directory")
file.IsDir = true;
else if (type == "file")
file.IsDir = false;
else
return false;
int dataIndex = item.FindSubTag("data");
if (dataIndex >= 0 && !file.IsDir)
{
file.HasData = true;
const CXmlItem &dataItem = item.SubItems[dataIndex];
if (!ParseUInt64(dataItem, "size", file.Size))
return false;
if (!ParseUInt64(dataItem, "length", file.PackSize))
return false;
if (!ParseUInt64(dataItem, "offset", file.Offset))
return false;
file.Sha1IsDefined = ParseSha1(dataItem, "extracted-checksum", file.Sha1);
// file.packSha1IsDefined = ParseSha1(dataItem, "archived-checksum", file.packSha1);
int encodingIndex = dataItem.FindSubTag("encoding");
if (encodingIndex >= 0)
{
const CXmlItem &encodingItem = dataItem.SubItems[encodingIndex];
if (encodingItem.IsTag)
{
AString s = encodingItem.GetPropertyValue("style");
if (s.Length() >= 0)
{
AString appl = "application/";
if (s.Left(appl.Length()) == appl)
{
s = s.Mid(appl.Length());
AString xx = "x-";
if (s.Left(xx.Length()) == xx)
{
s = s.Mid(xx.Length());
if (s == "gzip")
s = METHOD_NAME_ZLIB;
}
}
file.Method = s;
}
}
}
}
file.CTime = ParseTime(item, "ctime");
file.MTime = ParseTime(item, "mtime");
file.ATime = ParseTime(item, "atime");
files.Add(file);
}
for (int i = 0; i < item.SubItems.Size(); i++)
if (!AddItem(item.SubItems[i], files, parent))
return false;
return true;
}
HRESULT CHandler::Open2(IInStream *stream)
{
UInt64 archiveStartPos;
RINOK(stream->Seek(0, STREAM_SEEK_SET, &archiveStartPos));
const UInt32 kHeaderSize = 0x1C;
Byte buf[kHeaderSize];
RINOK(ReadStream_FALSE(stream, buf, kHeaderSize));
UInt32 size = Get16(buf + 4);
// UInt32 ver = Get16(buf + 6); // == 0
if (Get32(buf) != 0x78617221 || size != kHeaderSize)
return S_FALSE;
UInt64 packSize = Get64(buf + 8);
UInt64 unpackSize = Get64(buf + 0x10);
// UInt32 checkSumAlogo = Get32(buf + 0x18);
if (unpackSize >= kXmlSizeMax)
return S_FALSE;
_dataStartPos = archiveStartPos + kHeaderSize + packSize;
char *ss = _xml.GetBuffer((int)unpackSize + 1);
NCompress::NZlib::CDecoder *zlibCoderSpec = new NCompress::NZlib::CDecoder();
CMyComPtr<ICompressCoder> zlibCoder = zlibCoderSpec;
CLimitedSequentialInStream *inStreamLimSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStreamLim(inStreamLimSpec);
inStreamLimSpec->SetStream(stream);
inStreamLimSpec->Init(packSize);
CSequentialOutStreamImp2 *outStreamLimSpec = new CSequentialOutStreamImp2;
CMyComPtr<ISequentialOutStream> outStreamLim(outStreamLimSpec);
outStreamLimSpec->Init((Byte *)ss, (size_t)unpackSize);
RINOK(zlibCoder->Code(inStreamLim, outStreamLim, NULL, NULL, NULL));
if (outStreamLimSpec->GetPos() != (size_t)unpackSize)
return S_FALSE;
ss[(size_t)unpackSize] = 0;
_xml.ReleaseBuffer();
CXml xml;
if (!xml.Parse(_xml))
return S_FALSE;
if (!xml.Root.IsTagged("xar") || xml.Root.SubItems.Size() != 1)
return S_FALSE;
const CXmlItem &toc = xml.Root.SubItems[0];
if (!toc.IsTagged("toc"))
return S_FALSE;
if (!AddItem(toc, _files, -1))
return S_FALSE;
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *stream,
const UInt64 * /* maxCheckStartPosition */,
IArchiveOpenCallback * /* openArchiveCallback */)
{
COM_TRY_BEGIN
{
Close();
if (Open2(stream) != S_OK)
return S_FALSE;
_inStream = stream;
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_inStream.Release();
_files.Clear();
_xml.Empty();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _files.Size()
#ifdef XAR_SHOW_RAW
+ 1
#endif
;
return S_OK;
}
static void TimeToProp(UInt64 t, NWindows::NCOM::CPropVariant &prop)
{
if (t != 0)
{
FILETIME ft;
ft.dwLowDateTime = (UInt32)(t);
ft.dwHighDateTime = (UInt32)(t >> 32);
prop = ft;
}
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
#ifdef XAR_SHOW_RAW
if ((int)index == _files.Size())
{
switch(propID)
{
case kpidPath: prop = L"[TOC].xml"; break;
case kpidSize:
case kpidPackSize: prop = (UInt64)_xml.Length(); break;
}
}
else
#endif
{
const CFile &item = _files[index];
switch(propID)
{
case kpidMethod:
{
UString name;
if (!item.Method.IsEmpty() && ConvertUTF8ToUnicode(item.Method, name))
prop = name;
break;
}
case kpidPath:
{
AString path;
int cur = index;
do
{
const CFile &item = _files[cur];
AString s = item.Name;
if (s.IsEmpty())
s = "unknown";
if (path.IsEmpty())
path = s;
else
path = s + CHAR_PATH_SEPARATOR + path;
cur = item.Parent;
}
while (cur >= 0);
UString name;
if (ConvertUTF8ToUnicode(path, name))
prop = name;
break;
}
case kpidIsDir: prop = item.IsDir; break;
case kpidSize: if (!item.IsDir) prop = item.Size; break;
case kpidPackSize: if (!item.IsDir) prop = item.PackSize; break;
case kpidMTime: TimeToProp(item.MTime, prop); break;
case kpidCTime: TimeToProp(item.CTime, prop); break;
case kpidATime: TimeToProp(item.ATime, prop); break;
}
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _files.Size();
if (numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
{
int index = (int)(allFilesMode ? i : indices[i]);
#ifdef XAR_SHOW_RAW
if (index == _files.Size())
totalSize += _xml.Length();
else
#endif
totalSize += _files[index].Size;
}
extractCallback->SetTotal(totalSize);
UInt64 currentPackTotal = 0;
UInt64 currentUnpTotal = 0;
UInt64 currentPackSize = 0;
UInt64 currentUnpSize = 0;
const UInt32 kZeroBufSize = (1 << 14);
CByteBuffer zeroBuf;
zeroBuf.SetCapacity(kZeroBufSize);
memset(zeroBuf, 0, kZeroBufSize);
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
NCompress::NZlib::CDecoder *zlibCoderSpec = new NCompress::NZlib::CDecoder();
CMyComPtr<ICompressCoder> zlibCoder = zlibCoderSpec;
NCompress::NBZip2::CDecoder *bzip2CoderSpec = new NCompress::NBZip2::CDecoder();
CMyComPtr<ICompressCoder> bzip2Coder = bzip2CoderSpec;
NCompress::NDeflate::NDecoder::CCOMCoder *deflateCoderSpec = new NCompress::NDeflate::NDecoder::CCOMCoder();
CMyComPtr<ICompressCoder> deflateCoder = deflateCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CLimitedSequentialInStream *inStreamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(inStreamSpec);
inStreamSpec->SetStream(_inStream);
CLimitedSequentialOutStream *outStreamLimSpec = new CLimitedSequentialOutStream;
CMyComPtr<ISequentialOutStream> outStream(outStreamLimSpec);
COutStreamWithSha1 *outStreamSha1Spec = new COutStreamWithSha1;
{
CMyComPtr<ISequentialOutStream> outStreamSha1(outStreamSha1Spec);
outStreamLimSpec->SetStream(outStreamSha1);
}
for (i = 0; i < numItems; i++, currentPackTotal += currentPackSize, currentUnpTotal += currentUnpSize)
{
lps->InSize = currentPackTotal;
lps->OutSize = currentUnpTotal;
currentPackSize = 0;
currentUnpSize = 0;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> realOutStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
Int32 index = allFilesMode ? i : indices[i];
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
if (index < _files.Size())
{
const CFile &item = _files[index];
if (item.IsDir)
{
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
}
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
outStreamSha1Spec->SetStream(realOutStream);
realOutStream.Release();
Int32 opRes = NExtract::NOperationResult::kOK;
#ifdef XAR_SHOW_RAW
if (index == _files.Size())
{
outStreamSha1Spec->Init(false);
outStreamLimSpec->Init(_xml.Length());
RINOK(WriteStream(outStream, (const char *)_xml, _xml.Length()));
currentPackSize = currentUnpSize = _xml.Length();
}
else
#endif
{
const CFile &item = _files[index];
if (item.HasData)
{
currentPackSize = item.PackSize;
currentUnpSize = item.Size;
RINOK(_inStream->Seek(_dataStartPos + item.Offset, STREAM_SEEK_SET, NULL));
inStreamSpec->Init(item.PackSize);
outStreamSha1Spec->Init(item.Sha1IsDefined);
outStreamLimSpec->Init(item.Size);
HRESULT res = S_OK;
ICompressCoder *coder = NULL;
if (item.Method.IsEmpty() || item.Method == "octet-stream")
if (item.PackSize == item.Size)
coder = copyCoder;
else
opRes = NExtract::NOperationResult::kUnSupportedMethod;
else if (item.Method == METHOD_NAME_ZLIB)
coder = zlibCoder;
else if (item.Method == "bzip2")
coder = bzip2Coder;
else
opRes = NExtract::NOperationResult::kUnSupportedMethod;
if (coder)
res = coder->Code(inStream, outStream, NULL, NULL, progress);
if (res != S_OK)
{
if (!outStreamLimSpec->IsFinishedOK())
opRes = NExtract::NOperationResult::kDataError;
else if (res != S_FALSE)
return res;
if (opRes == NExtract::NOperationResult::kOK)
opRes = NExtract::NOperationResult::kDataError;
}
if (opRes == NExtract::NOperationResult::kOK)
{
if (outStreamLimSpec->IsFinishedOK() &&
outStreamSha1Spec->GetSize() == item.Size)
{
if (!outStreamLimSpec->IsFinishedOK())
{
opRes = NExtract::NOperationResult::kDataError;
}
else if (item.Sha1IsDefined)
{
Byte digest[NCrypto::NSha1::kDigestSize];
outStreamSha1Spec->Final(digest);
if (memcmp(digest, item.Sha1, NCrypto::NSha1::kDigestSize) != 0)
opRes = NExtract::NOperationResult::kCRCError;
}
}
else
opRes = NExtract::NOperationResult::kDataError;
}
}
}
outStreamSha1Spec->ReleaseStream();
RINOK(extractCallback->SetOperationResult(opRes));
}
return S_OK;
COM_TRY_END
}
static IInArchive *CreateArc() { return new NArchive::NXar::CHandler; }
static CArcInfo g_ArcInfo =
{ L"Xar", L"xar", 0, 0xE1, { 'x', 'a', 'r', '!', 0, 0x1C }, 6, false, CreateArc, 0 };
REGISTER_ARC(Xar)
}}
<file_sep>/FingerSuite/Common/atlcplapplet.h
#ifndef __ATLCPLAPPLET_H__
#define __ATLCPLAPPLET_H__
/////////////////////////////////////////////////////////////////////////////
// atlcplapplet.h - Control Panel applet
//
// Written by <NAME> (<EMAIL>)
// Copyright (c) 2007 <NAME>.
//
// This code may be used in compiled form in any way you desire. This
// source file may be redistributed by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever. It's free, so don't hassle me about it.
//
// Beware of bugs.
//
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error atlcplapplet.h requires atlapp.h to be included first
#endif
#include <cpl.h>
typedef struct tagATLCPLAPPLETREG
{
int iIndex;
BOOL bOnlyCurrentUser;
DWORD dwCategory;
DWORD dwRunLevel;
UINT uTaskRegID;
} ATLCPLAPPLETREG;
#define DECLARE_APPLET_CATEGORY(x) enum { APPLET_CATEGORY = x };
#define DECLARE_APPLET_RUNLEVEL(x) enum { APPLET_RUNLEVEL = x };
#define DECLARE_APPLET_RESOURCEID(x) enum { APPLET_TASK_REGISTRYID = x };
typedef struct tagATLCPLAPPLETINFO
{
LPCTSTR pstrCanonicalName;
UINT uNameRes;
UINT uInfoRes;
UINT uTaskRes;
UINT uKeywordsRes;
UINT uIconRes;
BOOL bDynamic;
DWORD dwFlags;
ULONG_PTR lData;
DWORD dwHelpContext;
HRESULT (*pfnUpdateRegistry)(int iIndex, BOOL bRegister);
BOOL (*pfnCreateInstance)(HWND hWnd, LONG_PTR lData, LPCTSTR pstrData);
VOID (*pfnGetAppletInfo)(int iLevel, tagATLCPLAPPLETINFO* pInfo);
} ATLCPLAPPLETINFO;
extern ATLCPLAPPLETINFO _pAtlApplets[];
#define BEGIN_CPLAPPLET_MAP() \
ATLCPLAPPLETINFO _pAtlApplets[] = {
#define CPLAPPLET_ENTRY(applclass, cname, name) \
{ _T(cname), IDS_##name, IDS_Description_##name, IDS_Task_##name, IDS_Keywords_##name, IDI_##name, FALSE, 0, 0L, 0, &applclass::UpdateRegistry, &applclass::CreateInstance, &applclass::GetAppletInfo },
#define CPLAPPLET_ENTRY_EX(applclass, cname, name, info, task, keywords, icon, flags, data, helpctx) \
{ _T(cname), name, info, task, keywords, icon, TRUE, flags, data, helpctx, &applclass::UpdateRegistry, &applclass::CreateInstance, &applclass::GetAppletInfo },
#define CPLAPPLET_ENTRY_CLASS(applclass) \
{ NULL, CPL_DYNAMIC_RES, CPL_DYNAMIC_RES, 0, 0, CPL_DYNAMIC_RES, TRUE, 0, 0L, 0, &applclass::UpdateRegistry, &applclass::CreateInstance, &applclass::GetAppletInfo },
#define END_CPLAPPLET_MAP() \
{ 0 } };
typedef enum CPLAPPLETINFO
{
CPLINFO_NAME = 1,
CPLINFO_INFO,
CPLINFO_ICON,
CPLINFO_DATA,
CPLINFO_HELPCONTEXT,
};
template< class T >
class CCPlAppletBase
{
public:
enum { APPLET_CATEGORY = 0x05 };
enum { APPLET_RUNLEVEL = 0x00 };
enum { APPLET_TASK_REGISTRYID = 0 };
static HRESULT UpdateRegistry(int iIndex, BOOL bRegister)
{
ATLCPLAPPLETREG RegInfo = { iIndex, FALSE, T::APPLET_CATEGORY, T::APPLET_RUNLEVEL, T::APPLET_TASK_REGISTRYID };
return _Applets.UpdateRegistry(bRegister, &RegInfo);
}
static BOOL CreateInstance(HWND hWnd, LONG_PTR lData, LPCTSTR pstrData)
{
T* pObject = new T();
if( pObject == NULL ) return FALSE;
BOOL bRes = pObject->ShowApplet(hWnd, lData, pstrData);
delete pObject;
return bRes;
}
static VOID GetAppletInfo(int /*iLevel*/, ATLCPLAPPLETINFO* /*pInfo*/)
{
}
};
class CCPlAppletModule
{
public:
HWND m_hwndCPl;
CCPlAppletModule() : m_hwndCPl(NULL)
{
}
LONG CPlApplet(HWND hwndCPl, UINT msg, LPARAM lParam1, LPARAM lParam2)
{
m_hwndCPl = hwndCPl;
switch( msg ) {
case CPL_INIT:
CPlApplet_Init();
return 1;
case CPL_EXIT:
CPlApplet_Exit();
return 0;
case CPL_GETCOUNT:
return CPlApplet_GetCount();
case CPL_DBLCLK:
CPlApplet_DblClick((int) lParam1, hwndCPl);
return 0;
#ifndef _WIN32_WCE
case CPL_INQUIRE:
CPlApplet_Inquire((int) lParam1, (CPLINFO*) lParam2);
return 0;
#endif // !_WIN32_WCE
case CPL_NEWINQUIRE:
CPlApplet_NewInquire((int) lParam1, (NEWCPLINFO*) lParam2);
return 0;
#ifndef _WIN32_WCE
#if (WINVER >= 0x0400)
case CPL_STARTWPARMSA:
{
#ifdef _UNICODE
WCHAR wszCommand[100] = { 0 };
::MultiByteToWideChar(CP_ACP, 0, (LPCSTR) lParam2, -1, wszCommand, (sizeof(wszCommand) / sizeof(WCHAR)) -1);
LPCWSTR pstrCommand = wszCommand;
#else
LPCSTR pstrCommand = (LPCSTR) lParam2;
#endif // _UNICODE
return (LONG) CPlApplet_StartWithParams((int) lParam1, hwndCPl, pstrCommand);
}
case CPL_STARTWPARMSW:
{
#ifdef _UNICODE
LPCWSTR pstrCommand = (LPCWSTR) lParam2;
#else
CHAR szCommand[200] = { 0 };
::WideCharToMultiByte(CP_ACP, 0, (LPCWSTR) lParam2, -1, szCommand, sizeof(szCommand) - 1, NULL, NULL);
LPCSTR pstrCommand = szCommand;
#endif // _UNICODE
return (LONG) CPlApplet_StartWithParams((int) lParam1, hwndCPl, pstrCommand);
}
#endif // (WINVER >= 0x0400)
#endif // !_WIN32_WCE
case CPL_STOP:
CPlApplet_Stop((int) lParam1);
return 0;
}
return 0;
}
HRESULT RegisterApplets()
{
HRESULT Hr = S_OK;
#ifndef _WIN32_WCE
int iIndex = 0;
for( const ATLCPLAPPLETINFO* pObjects = _pAtlApplets; (*pObjects).pfnCreateInstance != NULL; pObjects++ ) {
if( FAILED( Hr = pObjects->pfnUpdateRegistry(iIndex++, TRUE) ) ) return Hr;
}
#endif // !_WIN32_WCE
return Hr;
}
HRESULT UnregisterApplets()
{
HRESULT Hr = S_OK, HrRes = S_OK;
#ifndef _WIN32_WCE
int iIndex = 0;
for( const ATLCPLAPPLETINFO* pObjects = _pAtlApplets; (*pObjects).pfnCreateInstance != NULL; pObjects++ ) {
if( FAILED( Hr = pObjects->pfnUpdateRegistry(iIndex++, FALSE) ) ) HrRes = Hr;
}
#endif // !_WIN32_WCE
return HrRes;
}
HWND GetOwnerHWND()
{
return m_hwndCPl;
}
BOOL ChangeAppletInfo(int iIndex, CPLAPPLETINFO Type, UINT uResID)
{
ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount());
if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return FALSE;
switch( Type ) {
case CPLINFO_NAME: _pAtlApplets[iIndex].uNameRes = uResID; break;
case CPLINFO_INFO: _pAtlApplets[iIndex].uInfoRes = uResID; break;
case CPLINFO_ICON: _pAtlApplets[iIndex].uIconRes = uResID; break;
case CPLINFO_DATA: _pAtlApplets[iIndex].lData = (LONG_PTR) uResID; break;
case CPLINFO_HELPCONTEXT: _pAtlApplets[iIndex].dwHelpContext = uResID; break;
default: return FALSE;
}
_pAtlApplets[iIndex].bDynamic = TRUE;
return TRUE;
}
HRESULT UpdateRegistry(BOOL bRegister, ATLCPLAPPLETREG* pRegInfo)
{
#ifndef _WIN32_WCE
OSVERSIONINFO osvi = { 0 };;
osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
::GetVersionEx(&osvi);
bool bIsVista = (osvi.dwMajorVersion >= 6);
bool bIsWin98 = ((osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS && osvi.dwMajorVersion >= 5) || (osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS && (osvi.dwMinorVersion >= 90 || osvi.dwMajorVersion > 4)));
bool bIsWinXP = ((osvi.dwPlatformId != VER_PLATFORM_WIN32_WINDOWS) && ((osvi.dwMajorVersion > 5) || ((osvi.dwMajorVersion == 5) && (osvi.dwMinorVersion >= 1))));
TCHAR szDllFile[MAX_PATH] = { 0 };
::GetModuleFileName(ModuleHelper::GetModuleInstance(), szDllFile, MAX_PATH);
ATLCPLAPPLETINFO Info = _pAtlApplets[pRegInfo->iIndex];
_pAtlApplets[pRegInfo->iIndex].pfnGetAppletInfo(1, &Info);
// Create a friendly name for the dll filename. No spaces and funny characters.
LPCTSTR pSep = _FindLastOf(szDllFile, '\\');
if( pSep == NULL ) return E_FAIL;
TCHAR szDllName[MAX_PATH] = { 0 };
::lstrcpy(szDllName, pSep + 1);
TCHAR szFriendlyName[MAX_PATH] = { 0 };
::lstrcpy(szFriendlyName, pSep + 1);
for( LPTSTR p = szFriendlyName; *p != '\0'; p = ::CharNext(p) ) {
if( *p == '.' ) { *p = '\0'; break; }
if( !IsCharAlphaNumeric(*p) ) *p = '_';
}
HRESULT Hr = S_OK;
if( bIsVista )
{
HKEY hKeyRoot = HKEY_LOCAL_MACHINE;
if( pRegInfo->bOnlyCurrentUser ) hKeyRoot = HKEY_CURRENT_USER;
CRegKey reg;
LONG lRes = reg.Create(hKeyRoot, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Cpls"));
if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes);
if( bRegister ) {
::RegSetValueEx(reg, szFriendlyName, NULL, REG_EXPAND_SZ, (CONST BYTE*) szDllFile, (lstrlen(szDllFile) + 1) * sizeof(TCHAR));
if( pRegInfo->dwRunLevel > 0 ) {
CRegKey regSub;
if( regSub.Create(reg, szDllName) == ERROR_SUCCESS ) {
::RegSetValueEx(regSub, _T("RunLevel"), NULL, REG_DWORD, (CONST BYTE*) &pRegInfo->dwRunLevel, sizeof(DWORD));
regSub.Close();
}
}
}
else {
reg.DeleteValue(szFriendlyName);
reg.DeleteSubKey(szDllName);
}
reg.Close();
// Register canonical name
lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.ApplicationName"), KEY_ALL_ACCESS);
if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes);
if( bRegister ) {
::RegSetValueEx(reg, szDllFile, NULL, REG_SZ, (CONST BYTE*) Info.pstrCanonicalName, (lstrlen(Info.pstrCanonicalName) + 1) * sizeof(TCHAR));
}
else {
reg.DeleteValue(szDllFile);
}
reg.Close();
TCHAR szGUID[50] = { 0 };
DWORD dwCategory = pRegInfo->dwCategory;
TCHAR szTaskFileUrl[MAX_PATH + 20] = { 0 };
if( pRegInfo->uTaskRegID == 0 )
{
GUID AppGUID, TaskGUID;
::CoCreateGuid(&AppGUID);
::CoCreateGuid(&TaskGUID);
WCHAR wszGUID[50], wszTaskGUID[50];
::StringFromGUID2(AppGUID, wszGUID, 50);
::StringFromGUID2(TaskGUID, wszTaskGUID, 50);
WCHAR wszBuffer[1025] = { 0 };
::wsprintfW(wszBuffer,
L"\xfeff<?xml version=\"1.0\" encoding=\"UTF-16\" ?>\n"
L"<applications xmlns=\"http://schemas.microsoft.com/windows/cpltasks/v1\" xmlns:sh=\"http://schemas.microsoft.com/windows/tasks/v1\">"
L"<application id=\"%s\">"
L"<sh:task id=\"%s\" needsElevation=\"%s\">"
#ifdef _UNICODE
L"<sh:name>@%s,-%ld</sh:name>"
L"<sh:keywords>@%s,-%ld</sh:keywords>"
L"<sh:command>%%systemroot%%\\system32\\control.exe /name %s</sh:command>"
#else
L"<sh:name>@%hs,-%ld</sh:name>"
L"<sh:keywords>@%hs,-%ld</sh:keywords>"
L"<sh:command>%%systemroot%%\\system32\\control.exe /name %hs</sh:command>"
#endif // _UNICODE
L"</sh:task>"
L"<category id=\"%ld\">"
L"<sh:task idref=\"%s\"/>"
L"</category>"
L"</application>"
L"</applications>",
wszGUID,
wszTaskGUID,
pRegInfo->dwRunLevel == 0 ? L"false" : L"true",
szDllName, Info.uTaskRes,
szDllName, Info.uKeywordsRes,
Info.pstrCanonicalName,
pRegInfo->dwCategory,
wszTaskGUID);
::wsprintf(szGUID, _T("%ws"), wszGUID);
::lstrcpy(szTaskFileUrl, szDllFile);
::wsprintf(_FindLastOf(szTaskFileUrl, '.'), _T("_cpl%d.xml"), pRegInfo->iIndex + 1);
if( bRegister ) {
HANDLE hFile = ::CreateFile(szTaskFileUrl, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if( hFile == INVALID_HANDLE_VALUE ) return HRESULT_FROM_WIN32(::GetLastError());
DWORD dwWritten = 0;
::WriteFile(hFile, wszBuffer, lstrlenW(wszBuffer) * sizeof(WCHAR), &dwWritten, NULL);
::CloseHandle(hFile);
}
else {
::DeleteFile(szTaskFileUrl);
}
}
else
{
// Load the XML resource.
// Here we assume it is UTF-8 encoded (or latin-1) and embedded in the "XML" resource
// type section.
HRSRC hResource = ::FindResource(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(pRegInfo->uTaskRegID), _T("XML"));
if( hResource == NULL ) return TYPE_E_FIELDNOTFOUND;
HGLOBAL hGlobal = ::LoadResource(ModuleHelper::GetResourceInstance(), hResource);
if( hGlobal == NULL ) return E_OUTOFMEMORY;
DWORD dwSize = ::SizeofResource(ModuleHelper::GetResourceInstance(), hResource);
LPVOID pVoid = ::LockResource(hGlobal);
LPSTR pstr = (LPSTR) malloc(dwSize + 1);
memcpy(pstr, pVoid, dwSize);
FreeResource(hGlobal);
pstr[dwSize] = '\0';
LPSTR pstrCategory = strstr(pstr, "<category id=\"");
if( pstrCategory != NULL ) dwCategory = (DWORD) atol(pstrCategory + 14);
LPSTR pstrGUID = strstr(pstr, "<application id=\"");
if( pstrGUID == NULL ) return TYPE_E_ELEMENTNOTFOUND;
BYTE bGUID[50] = { 0 };
memcpy(bGUID, pstrGUID + 17, 38);
::wsprintf(szGUID, _T("%hs"), bGUID);
::wsprintf(szTaskFileUrl, _T("%s,-%ld"), szDllFile, pRegInfo->uTaskRegID);
free(pstr);
}
// Set the ApplicationName (canonical name)
lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.Software.AppId"), KEY_ALL_ACCESS);
if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes);
if( bRegister ) {
::RegSetValueEx(reg, szDllFile, NULL, REG_SZ, (CONST BYTE*) szGUID, (lstrlen(szGUID) + 1) * sizeof(TCHAR));
}
else {
reg.DeleteValue(szDllFile);
}
reg.Close();
// Set the TaskFileUrl
lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.Software.TasksFileUrl"), KEY_ALL_ACCESS);
if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes);
if( bRegister ) {
::RegSetValueEx(reg, szDllFile, NULL, REG_SZ, (CONST BYTE*) szTaskFileUrl, (lstrlen(szTaskFileUrl) + 1) * sizeof(TCHAR));
}
else {
reg.DeleteValue(szDllFile);
}
reg.Close();
// Set the Category
lRes = reg.Open(HKEY_LOCAL_MACHINE, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\System.ControlPanel.Category"), KEY_ALL_ACCESS);
if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes);
if( bRegister ) {
::RegSetValueEx(reg, szDllFile, NULL, REG_DWORD, (CONST BYTE*) &dwCategory, sizeof(DWORD));
}
else {
reg.DeleteValue(szDllFile);
}
reg.Close();
}
else if( bIsWin98 )
{
HKEY hKeyRoot = HKEY_LOCAL_MACHINE;
if( pRegInfo->bOnlyCurrentUser ) hKeyRoot = HKEY_CURRENT_USER;
CRegKey reg;
LONG lRes = reg.Create(hKeyRoot, _T("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Cpls"));
if( lRes != ERROR_SUCCESS ) return HRESULT_FROM_WIN32(lRes);
if( bRegister ) {
::RegSetValueEx(reg, szFriendlyName, NULL, REG_EXPAND_SZ, (CONST BYTE*) szDllFile, (lstrlen(szDllFile) + 1) * sizeof(TCHAR));
}
else {
reg.DeleteValue(szFriendlyName);
}
reg.Close();
// Set the Category on Windows XP
if( bIsWinXP ) {
lRes = reg.Create(HKEY_LOCAL_MACHINE, _T("Software\\Microsoft\\Windows\\CurrentVersion\\Control Panel\\Extended Properties\\{305CA226-D286-468e-B848-2B2E8E697B74} 2"));
if( lRes == ERROR_SUCCESS ) {
if( bRegister ) {
::RegSetValueEx(reg, szDllFile, NULL, REG_DWORD, (CONST BYTE*) &pRegInfo->dwCategory, sizeof(DWORD));
}
else {
reg.DeleteValue(szDllFile);
}
}
}
}
else
{
BOOL bRes = ::WritePrivateProfileString(_T("MMCPL"), szFriendlyName, (bRegister ? szDllFile : NULL), _T("control.ini"));
if( !bRes ) Hr = HRESULT_FROM_WIN32(::GetLastError());
}
return Hr;
#else
return S_OK;
#endif // !_WIN32_WCE
}
void CPlApplet_Init()
{
}
void CPlApplet_Exit()
{
}
void CPlApplet_Stop(int iIndex)
{
ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount());
if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return;
}
void CPlApplet_DblClick(int iIndex, HWND hWnd)
{
ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount());
if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return;
LONG_PTR lData = _pAtlApplets[iIndex].lData;
_pAtlApplets[iIndex].pfnCreateInstance(hWnd, lData, _T(""));
}
#ifndef _WIN32_WCE
BOOL CPlApplet_StartWithParams(int iIndex, HWND hWnd, LPCTSTR pstrText)
{
ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount());
if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return FALSE;
LONG_PTR lData = _pAtlApplets[iIndex].lData;
return _pAtlApplets[iIndex].pfnCreateInstance(hWnd, lData, pstrText);
}
#endif // !_WIN32_WCE
LONG CPlApplet_GetCount()
{
LONG nCount = 0;
const ATLCPLAPPLETINFO* pObjects = _pAtlApplets;
while( (*pObjects).pfnCreateInstance != NULL ) pObjects++, nCount++;
return nCount;
}
#ifndef _WIN32_WCE
void CPlApplet_Inquire(int iIndex, CPLINFO* pInfo)
{
ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount());
if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return;
_pAtlApplets[iIndex].pfnGetAppletInfo(0, &_pAtlApplets[iIndex]);
pInfo->idIcon = _pAtlApplets[iIndex].uIconRes;
pInfo->idInfo = _pAtlApplets[iIndex].uInfoRes;
pInfo->idName = _pAtlApplets[iIndex].uNameRes;
pInfo->lData = _pAtlApplets[iIndex].lData;
}
#endif // !_WIN32_WCE
void CPlApplet_NewInquire(int iIndex, NEWCPLINFO* pInfo)
{
ATLASSERT(iIndex>=0 && iIndex<CPlApplet_GetCount());
if( iIndex < 0 || iIndex >= CPlApplet_GetCount() ) return;
_pAtlApplets[iIndex].pfnGetAppletInfo(1, &_pAtlApplets[iIndex]);
::ZeroMemory(pInfo, sizeof(NEWCPLINFO));
pInfo->dwSize = sizeof(NEWCPLINFO);
::LoadString(ModuleHelper::GetResourceInstance(), _pAtlApplets[iIndex].uNameRes, pInfo->szName, sizeof(pInfo->szName) / sizeof(TCHAR));
::LoadString(ModuleHelper::GetResourceInstance(), _pAtlApplets[iIndex].uInfoRes, pInfo->szInfo, sizeof(pInfo->szInfo) / sizeof(TCHAR));
pInfo->hIcon = ::LoadIcon(ModuleHelper::GetResourceInstance(), MAKEINTRESOURCE(_pAtlApplets[iIndex].uIconRes));
pInfo->dwFlags = _pAtlApplets[iIndex].dwFlags;
pInfo->dwHelpContext = _pAtlApplets[iIndex].dwHelpContext;
pInfo->lData = _pAtlApplets[iIndex].lData;
}
LPTSTR _FindLastOf(LPTSTR pstr, TCHAR ch) const
{
LPTSTR pSep = NULL;
for( LPTSTR p = pstr; *p != '\0'; p = ::CharNext(p) ) {
if( *p == ch ) pSep = p;
}
return pSep;
}
};
extern CCPlAppletModule _Applets;
#endif __ATLCPLAPPLET_H__
<file_sep>/FingerSuite/FingerSuiteCPL/FingerMenuCPLDlg.h
// FingerMenuCONFIGView.h : interface of the CFingerMenuCONFIGView class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "..\Common\Utils.h"
#include <Tlhelp32.h>
#define IDT_TMR_CTRL 10001
#define TMR_CTRL_INTERVAL 1000
class CColorViewImpl : public CWindowImpl<CColorViewImpl, CStatic>
{
public:
CColorViewImpl ()
{
m_color = RGB(255, 255, 255);
}
void SetColor(COLORREF color)
{
m_color = color;
InvalidateRect(NULL);
UpdateWindow();
}
BEGIN_MSG_MAP(CColorViewImpl)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
END_MSG_MAP()
LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
RECT rc; GetClientRect(&rc);
CPaintDC dc(m_hWnd);
dc.FillSolidRect(&rc, m_color);
return 0;
}
public:
COLORREF m_color;
};
/********************************************************
PAGE1
********************************************************/
class CFingerMenuCPLDlg1 : public CPropertyPageImpl<CFingerMenuCPLDlg1>,
public CWinDataExchange<CFingerMenuCPLDlg1>,
public CUpdateUI<CFingerMenuCPLDlg1>
{
public:
enum { IDD = IDD_PAGE1 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg1)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg1>)
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg1)
DDX_CHECK(IDC_AUTOSTART_MENU, m_bAutostartMenu)
DDX_CHECK(IDC_AUTOSTART_MSGBOX, m_bAutostartMsgbox)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg1)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
UIAddChildWindowContainer(m_hWnd);
// get startup folder
WCHAR szValue[MAX_PATH];
if (SHGetSpecialFolderPath(m_hWnd, szValue, CSIDL_STARTUP, FALSE))
{
// if (RegReadString(HKEY_LOCAL_MACHINE, L"System\\Explorer\\Shell Folders", L"StartUp", szValue))
// {
m_szStartupFolder.Format(L"%s", szValue);
}
else
{
OutputDebugString(ErrorString(GetLastError()));
m_szStartupFolder = L"\\Windows\\StartUp";
}
ZeroMemory(szValue, sizeof(szValue));
if (SHGetSpecialFolderPath(m_hWnd, szValue, CSIDL_PROGRAM_FILES, FALSE))
{
//if (RegReadString(HKEY_LOCAL_MACHINE, L"System\\Explorer\\Shell Folders", L"Program Files", szValue))
//{
m_szProgramFilesFolder.Format(L"%s", szValue);
}
else
{
OutputDebugString(ErrorString(GetLastError()));
m_szProgramFilesFolder = L"\\Program Files";
}
if (!(m_bWithFingerMenu))
{
CWindow wnd1 = GetDlgItem(IDC_AUTOSTART_MENU);
wnd1.EnableWindow(FALSE);
CWindow wnd2 = GetDlgItem(IDC_LBL_AUTOSTART_MENU);
wnd2.EnableWindow(FALSE);
}
LoadConfiguration();
DoDataExchange(FALSE);
return TRUE;
}
public:
BOOL m_bWithFingerMenu;
private:
BOOL m_bAutostartMenu;
BOOL m_bAutostartMsgbox;
CString m_szStartupFolder;
CString m_szProgramFilesFolder;
void LoadConfiguration()
{
CFindFile finder;
if (m_bWithFingerMenu)
m_bAutostartMenu = finder.FindFile(m_szStartupFolder + L"\\FingerMenu.lnk");
m_bAutostartMsgbox = finder.FindFile(m_szStartupFolder + L"\\FingerMsgbox.lnk");
}
void SaveConfiguration()
{
if (m_bWithFingerMenu)
{
if (m_bAutostartMenu)
{
HANDLE hLink = ::CreateFile(m_szStartupFolder + L"\\FingerMenu.lnk",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hLink != INVALID_HANDLE_VALUE)
{
CString szPath;
WCHAR szInstallDir[MAX_PATH];
if (RegistryGetString(HKEY_LOCAL_MACHINE, L"Software\\FingerMenu", L"InstallDir", szInstallDir, MAX_PATH) == S_OK)
{
szPath.Format(L"%s\\FingerMenu.exe", szInstallDir);
}
else
{
szPath = m_szProgramFilesFolder + L"\\FingerMenu\\FingerMenu.exe";
}
//CHAR szLink[] = "42#\"\\Program Files\\FingerMenu\\FingerMenu.exe\"";
CString szLink; szLink.Format(L"%d#\"%s\"", szPath.GetLength() + 2, szPath);
CHAR* tmp = new CHAR[ szLink.GetLength() + 1 ];
ZeroMemory(tmp, szLink.GetLength());
for (int i = 0; i < szLink.GetLength(); i++)
tmp[i] = (CHAR)szLink[i];
DWORD dwNumberOfBytesWritten;
::WriteFile(hLink, tmp, szLink.GetLength(), &dwNumberOfBytesWritten, NULL);
CloseHandle(hLink);
}
}
else
{
::DeleteFile(m_szStartupFolder + L"\\FingerMenu.lnk");
}
}
if (m_bAutostartMsgbox)
{
HANDLE hLink = ::CreateFile(m_szStartupFolder + L"\\FingerMsgbox.lnk",
GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (hLink != INVALID_HANDLE_VALUE)
{
CString szPath;
WCHAR szInstallDir[MAX_PATH];
if (RegistryGetString(HKEY_LOCAL_MACHINE, L"Software\\FingerMsgbox", L"InstallDir", szInstallDir, MAX_PATH) == S_OK)
{
szPath.Format(L"%s\\FingerMsgbox.exe", szInstallDir);
}
else
{
szPath = m_szProgramFilesFolder + L"\\FingerMsgbox\\FingerMsgbox.exe";
}
CString szLink; szLink.Format(L"%d#\"%s\"", szPath.GetLength() + 2, szPath);
CHAR* tmp = new CHAR[ szLink.GetLength() + 1 ];
ZeroMemory(tmp, szLink.GetLength());
for (int i = 0; i < szLink.GetLength(); i++)
tmp[i] = (CHAR)szLink[i];
DWORD dwNumberOfBytesWritten;
::WriteFile(hLink, tmp, szLink.GetLength(), &dwNumberOfBytesWritten, NULL);
CloseHandle(hLink);
}
}
else
{
::DeleteFile(m_szStartupFolder + L"\\FingerMsgbox.lnk");
}
}
};
/********************************************************
PAGE2
********************************************************/
class CFingerMenuCPLDlg2 : public CPropertyPageImpl<CFingerMenuCPLDlg2>,
public CWinDataExchange<CFingerMenuCPLDlg2>,
public CUpdateUI<CFingerMenuCPLDlg2>
{
public:
enum { IDD = IDD_PAGE2 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg2)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_HANDLER(IDC_BTN_BKGCOLORTRANSP, BN_CLICKED, OnBnClickedBtnBkgColorTransp)
NOTIFY_HANDLER_EX(IDC_SPIN_TRANSLEVEL, UDN_DELTAPOS, OnSpinTransLevelDeltaPos)
NOTIFY_HANDLER_EX(IDC_SPIN_MAXCOUNT, UDN_DELTAPOS, OnSpinMaxCount)
NOTIFY_HANDLER_EX(IDC_SPIN_MAXVELOCITY, UDN_DELTAPOS, OnSpinMaxVelocity)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg2> )
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg2)
DDX_UINT(IDC_TRANSLEVEL, m_dwTransparencyLevel)
DDX_UINT(IDC_MAXCOUNT, m_dwMaxVisibleItemCount)
DDX_UINT(IDC_MAXVELOCITY, m_dwMaxVelocity)
DDX_CHECK(IDC_ENABLE_SIP, m_bEnableSIP)
DDX_CHECK(IDC_ENABLE_TRANSPARENCY, m_bDisableTransparency)
DDX_CHECK(IDC_DISABLE_BTNS, m_bDisableButtons)
DDX_CHECK(IDC_ENABLE_ANIMATION, m_bEnableAnimation)
DDX_CONTROL(IDC_CL_BKGCOLORTRANSP, m_ccBkgColorTransp)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg2)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//CMessageLoop* pLoop = _Module.GetMessageLoop();
//ATLASSERT(pLoop != NULL);
//pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
LoadConfiguration();
DoDataExchange(FALSE);
return TRUE;
}
LRESULT OnSpinTransLevelDeltaPos ( NMHDR* phdr )
{
NMUPDOWN* pm = (NMUPDOWN*)phdr;
m_dwTransparencyLevel -= pm->iDelta;
DoDataExchange(FALSE, IDC_TRANSLEVEL);
return 0;
}
LRESULT OnSpinMaxCount ( NMHDR* phdr )
{
NMUPDOWN* pm = (NMUPDOWN*)phdr;
m_dwMaxVisibleItemCount -= pm->iDelta;
DoDataExchange(FALSE, IDC_MAXCOUNT);
return 0;
}
LRESULT OnSpinMaxVelocity ( NMHDR* phdr )
{
NMUPDOWN* pm = (NMUPDOWN*)phdr;
m_dwMaxVelocity -= pm->iDelta;
DoDataExchange(FALSE, IDC_MAXVELOCITY);
return 0;
}
LRESULT OnBnClickedBtnBkgColorTransp(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CColorDialog colorDlg;
if (colorDlg.DoModal() == IDOK) // The user selected the "OK" button
{
m_ccBkgColorTransp.SetColor( colorDlg.GetColor() );
}
return 0;
}
public:
DWORD m_dwTransparencyLevel;
BOOL m_bEnableSIP;
DWORD m_dwMaxVisibleItemCount;
DWORD m_dwMaxVelocity;
BOOL m_bDisableTransparency;
BOOL m_bDisableButtons;
BOOL m_bEnableAnimation;
CColorViewImpl m_ccBkgColorTransp;
private:
void LoadConfiguration()
{
WCHAR keyName[] = L"Software\\FingerMenu";
// load transparency level
m_dwTransparencyLevel = 128;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"TransparencyLevel", m_dwTransparencyLevel)))
wprintf(L"Unable to read TransparencyLevel from registry: %s\n", ErrorString(GetLastError()));
m_bEnableSIP = TRUE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"EnableSIP", m_bEnableSIP)))
wprintf(L"Unable to read EnableSIP from registry: %s\n", ErrorString(GetLastError()));
m_dwMaxVisibleItemCount = 0;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"MaxMenuItemCount", m_dwMaxVisibleItemCount)))
wprintf(L"Unable to read MaxMenuItemCount from registry: %s\n", ErrorString(GetLastError()));
m_dwMaxVelocity = 15;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"MaxVelocity", m_dwMaxVelocity)))
wprintf(L"Unable to read MaxVelocity from registry: %s\n", ErrorString(GetLastError()));
m_bDisableTransparency = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"DisableTransparency", m_bDisableTransparency)))
wprintf(L"Unable to read DisableTransparency from registry: %s\n", ErrorString(GetLastError()));
m_bDisableButtons = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"NeverShowButtons", m_bDisableButtons)))
wprintf(L"Unable to read NeverShowButtons from registry: %s\n", ErrorString(GetLastError()));
m_bEnableAnimation = TRUE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"EnableAnimation", m_bEnableAnimation)))
wprintf(L"Unable to read EnableAnimation from registry: %s\n", ErrorString(GetLastError()));
RegReadColor(HKEY_LOCAL_MACHINE, keyName, L"NoTranspBkgColor", m_ccBkgColorTransp.m_color);
}
public:
void SaveConfiguration()
{
WCHAR szKeyName[] = L"Software\\FingerMenu";
RegWriteDWORD(HKEY_LOCAL_MACHINE, szKeyName, L"TransparencyLevel", m_dwTransparencyLevel);
RegWriteDWORD(HKEY_LOCAL_MACHINE, szKeyName, L"MaxMenuItemCount", m_dwMaxVisibleItemCount);
RegWriteDWORD(HKEY_LOCAL_MACHINE, szKeyName, L"MaxVelocity", m_dwMaxVelocity);
RegWriteBOOL(HKEY_LOCAL_MACHINE, szKeyName, L"EnableSIP", m_bEnableSIP);
RegWriteBOOL(HKEY_LOCAL_MACHINE, szKeyName, L"DisableTransparency", m_bDisableTransparency);
RegWriteBOOL(HKEY_LOCAL_MACHINE, szKeyName, L"NeverShowButtons", m_bDisableButtons);
RegWriteColor(HKEY_LOCAL_MACHINE, szKeyName, L"NoTranspBkgColor", m_ccBkgColorTransp.m_color);
RegWriteBOOL(HKEY_LOCAL_MACHINE, szKeyName, L"EnableAnimation", m_bEnableAnimation);
}
};
/********************************************************
PAGE3
********************************************************/
class CFingerMenuCPLDlg3 : public CPropertyPageImpl<CFingerMenuCPLDlg3>,
public CWinDataExchange<CFingerMenuCPLDlg3>,
public CUpdateUI<CFingerMenuCPLDlg3>
{
public:
enum { IDD = IDD_PAGE3 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg3)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_HANDLER(IDC_BTN_ADDPROGRAM, BN_CLICKED, OnBnClickedBtnAddProgram)
COMMAND_HANDLER(IDC_BTN_REFRESH, BN_CLICKED, OnBnClickedBtnRefresh)
COMMAND_HANDLER(IDC_BTN_REMOVEPROGRAMS, BN_CLICKED, OnBnClickedBtnRemove)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg3> )
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg3)
DDX_CONTROL_HANDLE(IDC_CB_PROCESSES, m_cbProcesses)
DDX_CONTROL_HANDLE(IDC_LB_PROCESSES, m_lbProcesses)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//CMessageLoop* pLoop = _Module.GetMessageLoop();
//ATLASSERT(pLoop != NULL);
//pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
//
DoDataExchange(FALSE);
LoadConfiguration();
RefreshProcessList();
return TRUE;
}
LRESULT OnBnClickedBtnAddProgram(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int i = m_cbProcesses.GetCurSel();
if (i >= 0)
{
CString proc; m_cbProcesses.GetLBText(i, proc);
int k = m_lbProcesses.FindString(0, proc);
if (k < 0)
m_lbProcesses.AddString(proc);
}
else
{
WCHAR proc[80]; ZeroMemory(proc, 80);
m_cbProcesses.GetWindowText(proc, 80);
if (proc[0] != '\0')
{
int k = m_lbProcesses.FindString(0, proc);
if (k < 0)
m_lbProcesses.AddString(proc);
}
}
return 0;
}
LRESULT OnBnClickedBtnRefresh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
RefreshProcessList();
return 0;
}
LRESULT OnBnClickedBtnRemove(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int i = m_lbProcesses.GetCurSel();
if (i >= 0)
m_lbProcesses.DeleteString(i);
return 0;
}
private:
void RefreshProcessList()
{
m_cbProcesses.ResetContent();
m_cbProcesses.Clear();
// set compiler flag /EHa
HANDLE snapShot = INVALID_HANDLE_VALUE;
try
{
snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPNOHEAPS, 0);
if (snapShot != INVALID_HANDLE_VALUE)
{
// Build new list
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
BOOL ret = Process32First(snapShot, &processEntry);
while (ret == TRUE)
{
if (
(lstrcmpi(processEntry.szExeFile, L"gwes.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"nk.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"connmgr.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"device.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"filesys.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"services.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"shell32.exe") != 0)
)
{
m_cbProcesses.AddString(processEntry.szExeFile);
}
ret = Process32Next(snapShot, &processEntry);
}
CloseToolhelp32Snapshot(snapShot);
}
} catch (...)
{
// do nothing
if (snapShot != INVALID_HANDLE_VALUE)
{
CloseToolhelp32Snapshot(snapShot);
}
}
}
public:
CSimpleArray<CString> m_szProcesses;
CComboBox m_cbProcesses;
CListBox m_lbProcesses;
private:
void LoadConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arExcludedApp;
LoadExclusionList(arExcludedApp, L"Software\\FingerMenu");
m_lbProcesses.ResetContent();
for (int i = 0; i < arExcludedApp.GetSize(); i ++)
{
m_lbProcesses.AddString(arExcludedApp[i]);
}
}
public:
void SaveConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arrExcludedApps;
for (int i = 0; i < m_lbProcesses.GetCount(); i++)
{
CString proc; m_lbProcesses.GetText(i, proc);
arrExcludedApps.Add(proc);
}
SaveExclusionList(arrExcludedApps, L"Software\\FingerMenu");
}
};
/********************************************************
PAGE4
********************************************************/
class CFingerMenuCPLDlg4 : public CPropertyPageImpl<CFingerMenuCPLDlg4>,
public CWinDataExchange<CFingerMenuCPLDlg4>,
public CUpdateUI<CFingerMenuCPLDlg4>
{
public:
enum { IDD = IDD_PAGE4 };
CComboBox m_cbSkinFingerMenu;
CComboBox m_cbSkinFingerMsgbox;
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg4)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg4>)
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg4)
DDX_CONTROL_HANDLE(IDC_CB_SKIN_FINGERMENU, m_cbSkinFingerMenu)
DDX_CONTROL_HANDLE(IDC_CB_SKIN_FINGERMSGBOX, m_cbSkinFingerMsgbox)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg4)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
UIAddChildWindowContainer(m_hWnd);
DoDataExchange(FALSE);
if (!(m_bWithFingerMenu))
{
CWindow wnd1 = GetDlgItem(IDC_CB_SKIN_FINGERMENU);
wnd1.EnableWindow(FALSE);
CWindow wnd2 = GetDlgItem(IDC_LBL_CB_SKIN_FINGERMENU);
wnd2.EnableWindow(FALSE);
}
LoadConfiguration();
return TRUE;
}
public:
BOOL m_bWithFingerMenu;
private:
void LoadConfiguration()
{
CString szProgramFilesFolder;
WCHAR szValue[MAX_PATH];
if (RegReadString(HKEY_LOCAL_MACHINE, L"System\\Explorer\\Shell Folders", L"Program Files", szValue))
{
szProgramFilesFolder.Format(L"%s", szValue);
}
// menu
WCHAR szKeyName[] = L"Software\\FingerMenu";
WCHAR skin[50];
BOOL setDefault = RegReadString(HKEY_LOCAL_MACHINE, szKeyName, L"Skin", skin);
m_cbSkinFingerMenu.ResetContent();
CFindFile finder;
BOOL bWorking = finder.FindFile(szProgramFilesFolder + L"\\FingerMenu\\skins\\*");
BOOL bAdd = bWorking;
int i = 0;
while (bWorking)
{
if (bAdd)
{
m_cbSkinFingerMenu.AddString(finder.GetFileName());
if ((setDefault) && (lstrcmpi(skin, finder.GetFileName()) == 0))
m_cbSkinFingerMenu.SetCurSel(i);
i++;
}
bWorking = finder.FindNextFile();
if (bWorking)
{
if ( finder.IsDirectory() && (!(finder.IsDots())) )
{
bAdd = TRUE;
}
else
{
bAdd = FALSE;
}
}
}
// msgbox
WCHAR szKeyName2[] = L"Software\\FingerMsgbox";
setDefault = RegReadString(HKEY_LOCAL_MACHINE, szKeyName2, L"Skin", skin);
m_cbSkinFingerMsgbox.ResetContent();
bWorking = finder.FindFile(szProgramFilesFolder + L"\\FingerMsgbox\\skins\\*");
bAdd = bWorking;
i = 0;
while (bWorking)
{
if (bAdd)
{
m_cbSkinFingerMsgbox.AddString(finder.GetFileName());
if ((setDefault) && (lstrcmpi(skin, finder.GetFileName()) == 0))
m_cbSkinFingerMsgbox.SetCurSel(i);
i++;
}
bWorking = finder.FindNextFile();
if (bWorking)
{
if ( finder.IsDirectory() && (!(finder.IsDots())) )
{
bAdd = TRUE;
}
else
{
bAdd = FALSE;
}
}
}
}
public:
void SaveConfiguration()
{
if (m_bWithFingerMenu)
{
WCHAR szKeyName[] = L"Software\\FingerMenu";
int i = m_cbSkinFingerMenu.GetCurSel();
CString skin;
if (i >= 0)
m_cbSkinFingerMenu.GetLBText(i, skin);
else
skin = L"default";
RegWriteString(HKEY_LOCAL_MACHINE, szKeyName, L"Skin", skin, skin.GetLength());
}
{
WCHAR szKeyName[] = L"Software\\FingerMsgbox";
int i = m_cbSkinFingerMsgbox.GetCurSel();
CString skin;
if (i >= 0)
m_cbSkinFingerMsgbox.GetLBText(i, skin);
else
skin = L"default";
RegWriteString(HKEY_LOCAL_MACHINE, szKeyName, L"Skin", skin, skin.GetLength());
}
}
};
/********************************************************
PAGE5
********************************************************/
class CFingerMenuCPLDlg5 : public CPropertyPageImpl<CFingerMenuCPLDlg5>,
public CWinDataExchange<CFingerMenuCPLDlg5>,
public CUpdateUI<CFingerMenuCPLDlg5>
{
public:
enum { IDD = IDD_PAGE5 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg5)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_HANDLER(IDC_BTN_BKGCOLORTRANSP, BN_CLICKED, OnBnClickedBtnBkgColorTransp)
NOTIFY_HANDLER_EX(IDC_SPIN_TRANSLEVEL, UDN_DELTAPOS, OnSpinTransLevelDeltaPos)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg5> )
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg5)
DDX_UINT(IDC_TRANSLEVEL, m_dwTransparencyLevel)
DDX_CHECK(IDC_ENABLE_TRANSPARENCY, m_bDisableTransparency)
DDX_CONTROL(IDC_CL_BKGCOLORTRANSP, m_ccBkgColorTransp)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg5)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//CMessageLoop* pLoop = _Module.GetMessageLoop();
//ATLASSERT(pLoop != NULL);
//pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
LoadConfiguration();
DoDataExchange(FALSE);
return TRUE;
}
LRESULT OnSpinTransLevelDeltaPos ( NMHDR* phdr )
{
NMUPDOWN* pm = (NMUPDOWN*)phdr;
m_dwTransparencyLevel -= pm->iDelta;
DoDataExchange(FALSE, IDC_TRANSLEVEL);
return 0;
}
LRESULT OnBnClickedBtnBkgColorTransp(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
CColorDialog colorDlg;
if (colorDlg.DoModal() == IDOK) // The user selected the "OK" button
{
m_ccBkgColorTransp.SetColor( colorDlg.GetColor() );
}
return 0;
}
public:
DWORD m_dwTransparencyLevel;
BOOL m_bDisableTransparency;
CColorViewImpl m_ccBkgColorTransp;
private:
void LoadConfiguration()
{
WCHAR keyName[] = L"Software\\FingerMsgbox";
// load transparency level
m_dwTransparencyLevel = 128;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"TransparencyLevel", m_dwTransparencyLevel)))
wprintf(L"Unable to read TransparencyLevel from registry: %s\n", ErrorString(GetLastError()));
m_bDisableTransparency = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"DisableTransparency", m_bDisableTransparency)))
wprintf(L"Unable to read DisableTransparency from registry: %s\n", ErrorString(GetLastError()));
RegReadColor(HKEY_LOCAL_MACHINE, keyName, L"NoTranspBkgColor", m_ccBkgColorTransp.m_color);
}
public:
void SaveConfiguration()
{
WCHAR szKeyName[] = L"Software\\FingerMsgbox";
RegWriteDWORD(HKEY_LOCAL_MACHINE, szKeyName, L"TransparencyLevel", m_dwTransparencyLevel);
RegWriteBOOL(HKEY_LOCAL_MACHINE, szKeyName, L"DisableTransparency", m_bDisableTransparency);
RegWriteColor(HKEY_LOCAL_MACHINE, szKeyName, L"NoTranspBkgColor", m_ccBkgColorTransp.m_color);
}
};
/********************************************************
PAGE6
********************************************************/
class CFingerMenuCPLDlg6 : public CPropertyPageImpl<CFingerMenuCPLDlg6>,
public CWinDataExchange<CFingerMenuCPLDlg6>,
public CUpdateUI<CFingerMenuCPLDlg6>
{
public:
enum { IDD = IDD_PAGE3 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg6)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_HANDLER(IDC_BTN_ADDPROGRAM, BN_CLICKED, OnBnClickedBtnAddProgram)
COMMAND_HANDLER(IDC_BTN_REFRESH, BN_CLICKED, OnBnClickedBtnRefresh)
COMMAND_HANDLER(IDC_BTN_REMOVEPROGRAMS, BN_CLICKED, OnBnClickedBtnRemove)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg6> )
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg6)
DDX_CONTROL_HANDLE(IDC_CB_PROCESSES, m_cbProcesses)
DDX_CONTROL_HANDLE(IDC_LB_PROCESSES, m_lbProcesses)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg6)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//CMessageLoop* pLoop = _Module.GetMessageLoop();
//ATLASSERT(pLoop != NULL);
//pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
//
DoDataExchange(FALSE);
LoadConfiguration();
RefreshProcessList();
return TRUE;
}
LRESULT OnBnClickedBtnAddProgram(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int i = m_cbProcesses.GetCurSel();
if (i >= 0)
{
CString proc; m_cbProcesses.GetLBText(i, proc);
int k = m_lbProcesses.FindString(0, proc);
if (k < 0)
m_lbProcesses.AddString(proc);
}
else
{
WCHAR proc[80]; ZeroMemory(proc, 80);
m_cbProcesses.GetWindowText(proc, 80);
if (proc[0] != '\0')
{
int k = m_lbProcesses.FindString(0, proc);
if (k < 0)
m_lbProcesses.AddString(proc);
}
}
return 0;
}
LRESULT OnBnClickedBtnRefresh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
RefreshProcessList();
return 0;
}
LRESULT OnBnClickedBtnRemove(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int i = m_lbProcesses.GetCurSel();
if (i >= 0)
m_lbProcesses.DeleteString(i);
return 0;
}
private:
void RefreshProcessList()
{
m_cbProcesses.ResetContent();
m_cbProcesses.Clear();
// set compiler flag /EHa
HANDLE snapShot = INVALID_HANDLE_VALUE;
try
{
snapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS | TH32CS_SNAPNOHEAPS, 0);
if (snapShot != INVALID_HANDLE_VALUE)
{
// Build new list
PROCESSENTRY32 processEntry;
processEntry.dwSize = sizeof(PROCESSENTRY32);
BOOL ret = Process32First(snapShot, &processEntry);
while (ret == TRUE)
{
if (
(lstrcmpi(processEntry.szExeFile, L"gwes.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"nk.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"connmgr.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"device.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"filesys.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"services.exe") != 0) &&
(lstrcmpi(processEntry.szExeFile, L"shell32.exe") != 0)
)
{
m_cbProcesses.AddString(processEntry.szExeFile);
}
ret = Process32Next(snapShot, &processEntry);
}
CloseToolhelp32Snapshot(snapShot);
}
} catch (...)
{
// do nothing
if (snapShot != INVALID_HANDLE_VALUE)
{
CloseToolhelp32Snapshot(snapShot);
}
}
}
public:
CSimpleArray<CString> m_szProcesses;
CComboBox m_cbProcesses;
CListBox m_lbProcesses;
private:
void LoadConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arExcludedApp;
LoadExclusionList(arExcludedApp, L"Software\\FingerMsgbox");
m_lbProcesses.ResetContent();
for (int i = 0; i < arExcludedApp.GetSize(); i ++)
{
m_lbProcesses.AddString(arExcludedApp[i]);
}
}
public:
void SaveConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arrExcludedApps;
for (int i = 0; i < m_lbProcesses.GetCount(); i++)
{
CString proc; m_lbProcesses.GetText(i, proc);
arrExcludedApps.Add(proc);
}
SaveExclusionList(arrExcludedApps, L"Software\\FingerMsgbox");
}
};
/********************************************************
PAGE7
********************************************************/
class CFingerMenuCPLDlg7 : public CPropertyPageImpl<CFingerMenuCPLDlg7>,
public CWinDataExchange<CFingerMenuCPLDlg7>,
public CUpdateUI<CFingerMenuCPLDlg7>
{
public:
enum { IDD = IDD_PAGE7 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg7)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_HANDLER(IDC_BTN_REMOVEPROGRAMS, BN_CLICKED, OnBnClickedBtnRemove)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg7> )
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg7)
DDX_CONTROL_HANDLE(IDC_LB_PROCESSES, m_lbProcesses)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg7)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//CMessageLoop* pLoop = _Module.GetMessageLoop();
//ATLASSERT(pLoop != NULL);
//pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
//
DoDataExchange(FALSE);
LoadConfiguration();
return TRUE;
}
LRESULT OnBnClickedBtnRemove(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int i = m_lbProcesses.GetCurSel();
if (i >= 0)
m_lbProcesses.DeleteString(i);
return 0;
}
public:
CSimpleArray<CString> m_szProcesses;
CListBox m_lbProcesses;
private:
void LoadConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arExcludedWnds;
LoadWndExclusionList(arExcludedWnds, L"Software\\FingerMenu");
m_lbProcesses.ResetContent();
for (int i = 0; i < arExcludedWnds.GetSize(); i ++)
{
m_lbProcesses.AddString(arExcludedWnds[i]);
}
}
public:
void SaveConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arExcludedWnds;
for (int i = 0; i < m_lbProcesses.GetCount(); i++)
{
CString proc; m_lbProcesses.GetText(i, proc);
arExcludedWnds.Add(proc);
}
SaveWndExclusionList(arExcludedWnds, L"Software\\FingerMenu");
}
};
/********************************************************
PAGE8
********************************************************/
class CFingerMenuCPLDlg8 : public CPropertyPageImpl<CFingerMenuCPLDlg8>,
public CWinDataExchange<CFingerMenuCPLDlg8>,
public CUpdateUI<CFingerMenuCPLDlg8>
{
public:
enum { IDD = IDD_PAGE7 };
BOOL PreTranslateMessage(MSG* pMsg)
{
return CWindow::IsDialogMessage(pMsg);
}
BOOL OnIdle()
{
UIUpdateChildWindows();
return FALSE;
}
void DoPaint(CDCHandle dc) {}
BEGIN_MSG_MAP_EX(CFingerMenuCPLDlg8)
MESSAGE_HANDLER(WM_INITDIALOG, OnInitDialog)
COMMAND_HANDLER(IDC_BTN_REMOVEPROGRAMS, BN_CLICKED, OnBnClickedBtnRemove)
CHAIN_MSG_MAP(CPropertyPageImpl<CFingerMenuCPLDlg8> )
END_MSG_MAP()
BEGIN_DDX_MAP(CFingerMenuCPLDlg8)
DDX_CONTROL_HANDLE(IDC_LB_PROCESSES, m_lbProcesses)
END_DDX_MAP()
BEGIN_UPDATE_UI_MAP(CFingerMenuCPLDlg8)
END_UPDATE_UI_MAP()
int OnApply()
{
DoDataExchange(TRUE);
SaveConfiguration();
return PSNRET_NOERROR;
}
LRESULT OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//CMessageLoop* pLoop = _Module.GetMessageLoop();
//ATLASSERT(pLoop != NULL);
//pLoop->AddIdleHandler(this);
UIAddChildWindowContainer(m_hWnd);
//
DoDataExchange(FALSE);
LoadConfiguration();
return TRUE;
}
LRESULT OnBnClickedBtnRemove(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
int i = m_lbProcesses.GetCurSel();
if (i >= 0)
m_lbProcesses.DeleteString(i);
return 0;
}
public:
CSimpleArray<CString> m_szProcesses;
CListBox m_lbProcesses;
private:
void LoadConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arExcludedWnds;
LoadWndExclusionList(arExcludedWnds, L"Software\\FingerMsgbox");
m_lbProcesses.ResetContent();
for (int i = 0; i < arExcludedWnds.GetSize(); i ++)
{
m_lbProcesses.AddString(arExcludedWnds[i]);
}
}
public:
void SaveConfiguration()
{
CSimpleArray<CString, CStringEqualHelper<CString>> arExcludedWnds;
for (int i = 0; i < m_lbProcesses.GetCount(); i++)
{
CString proc; m_lbProcesses.GetText(i, proc);
arExcludedWnds.Add(proc);
}
SaveWndExclusionList(arExcludedWnds, L"Software\\FingerMsgbox");
}
};<file_sep>/FBReader/zlibrary/ui/src/win32/dialogs/ZLWin32SelectionDialog.h
/*
* Copyright (C) 2007-2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#ifndef __ZLWIN32SELECTIONDIALOG_H__
#define __ZLWIN32SELECTIONDIALOG_H__
#include <vector>
#include <map>
#include <windows.h>
#include "../../../../core/src/desktop/dialogs/ZLDesktopSelectionDialog.h"
#include "../w32widgets/W32DialogPanel.h"
#include "../w32widgets/W32TreeView.h"
#include "../w32widgets/W32Control.h"
class ZLWin32ApplicationWindow;
class ZLWin32SelectionDialog : public ZLDesktopSelectionDialog, public W32Listener {
public:
ZLWin32SelectionDialog(ZLWin32ApplicationWindow &window, const std::string &caption, ZLTreeHandler &handler);
~ZLWin32SelectionDialog();
bool run();
//void activatedSlot();
protected:
void setSize(int width, int height);
int width() const;
int height() const;
void exitDialog();
void updateStateLine();
void updateList();
void selectItem(int index);
private:
void onEvent(const std::string &event, W32EventSender &sender);
private:
HICON getIcon(const ZLTreeNodePtr node);
private:
ZLWin32ApplicationWindow &myWindow;
W32StandaloneDialogPanel myPanel;
W32TreeView *myTreeView;
W32LineEditor *myLineEditor;
W32PushButton *myOkButton;
std::map<std::string,HICON> myIcons;
short myWidth;
short myHeight;
};
#endif /* __ZLWIN32SELECTIONDIALOG_H__ */
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdDecode.h
// PpmdDecode.h
// 2009-05-30 : <NAME> : Public domain
// This code is based on <NAME>'s PPMdH code (public domain)
#ifndef __COMPRESS_PPMD_DECODE_H
#define __COMPRESS_PPMD_DECODE_H
#include "PpmdContext.h"
namespace NCompress {
namespace NPpmd {
class CRangeDecoderVirt
{
public:
virtual UInt32 GetThreshold(UInt32 total) = 0;
virtual void Decode(UInt32 start, UInt32 size) = 0;
virtual UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) = 0;
};
typedef NRangeCoder::CDecoder CRangeDecoderMy;
class CRangeDecoder:public CRangeDecoderVirt, public CRangeDecoderMy
{
UInt32 GetThreshold(UInt32 total) { return CRangeDecoderMy::GetThreshold(total); }
void Decode(UInt32 start, UInt32 size) { CRangeDecoderMy::Decode(start, size); }
UInt32 DecodeBit(UInt32 size0, UInt32 numTotalBits) { return CRangeDecoderMy::DecodeBit(size0, numTotalBits); }
};
struct CDecodeInfo: public CInfo
{
void DecodeBinSymbol(CRangeDecoderVirt *rangeDecoder)
{
PPM_CONTEXT::STATE& rs = MinContext->oneState();
UInt16& bs = GetBinSumm(rs, GetContextNoCheck(MinContext->Suffix)->NumStats);
if (rangeDecoder->DecodeBit(bs, TOT_BITS) == 0)
{
FoundState = &rs;
rs.Freq = (Byte)(rs.Freq + (rs.Freq < 128 ? 1: 0));
bs = (UInt16)(bs + INTERVAL - GET_MEAN(bs, PERIOD_BITS, 2));
PrevSuccess = 1;
RunLength++;
}
else
{
bs = (UInt16)(bs - GET_MEAN(bs, PERIOD_BITS, 2));
InitEsc = ExpEscape[bs >> 10];
NumMasked = 1;
CharMask[rs.Symbol] = EscCount;
PrevSuccess = 0;
FoundState = NULL;
}
}
void DecodeSymbol1(CRangeDecoderVirt *rangeDecoder)
{
PPM_CONTEXT::STATE* p = GetStateNoCheck(MinContext->Stats);
int i, count, hiCnt;
if ((count = rangeDecoder->GetThreshold(MinContext->SummFreq)) < (hiCnt = p->Freq))
{
PrevSuccess = (2 * hiCnt > MinContext->SummFreq);
RunLength += PrevSuccess;
rangeDecoder->Decode(0, p->Freq); // MinContext->SummFreq);
(FoundState = p)->Freq = (Byte)(hiCnt += 4);
MinContext->SummFreq += 4;
if (hiCnt > MAX_FREQ)
rescale();
return;
}
PrevSuccess = 0;
i = MinContext->NumStats - 1;
while ((hiCnt += (++p)->Freq) <= count)
if (--i == 0)
{
HiBitsFlag = HB2Flag[FoundState->Symbol];
rangeDecoder->Decode(hiCnt, MinContext->SummFreq - hiCnt); // , MinContext->SummFreq);
CharMask[p->Symbol] = EscCount;
i = (NumMasked = MinContext->NumStats)-1;
FoundState = NULL;
do { CharMask[(--p)->Symbol] = EscCount; } while ( --i );
return;
}
rangeDecoder->Decode(hiCnt - p->Freq, p->Freq); // , MinContext->SummFreq);
update1(p);
}
void DecodeSymbol2(CRangeDecoderVirt *rangeDecoder)
{
int count, hiCnt, i = MinContext->NumStats - NumMasked;
UInt32 freqSum;
SEE2_CONTEXT* psee2c = makeEscFreq2(i, freqSum);
PPM_CONTEXT::STATE* ps[256], ** pps = ps, * p = GetStateNoCheck(MinContext->Stats)-1;
hiCnt = 0;
do
{
do { p++; } while (CharMask[p->Symbol] == EscCount);
hiCnt += p->Freq;
*pps++ = p;
}
while ( --i );
freqSum += hiCnt;
count = rangeDecoder->GetThreshold(freqSum);
p = *(pps = ps);
if (count < hiCnt)
{
hiCnt = 0;
while ((hiCnt += p->Freq) <= count)
p=*++pps;
rangeDecoder->Decode(hiCnt - p->Freq, p->Freq); // , freqSum);
psee2c->update();
update2(p);
}
else
{
rangeDecoder->Decode(hiCnt, freqSum - hiCnt); // , freqSum);
i = MinContext->NumStats - NumMasked;
pps--;
do { CharMask[(*++pps)->Symbol] = EscCount; } while ( --i );
psee2c->Summ = (UInt16)(psee2c->Summ + freqSum);
NumMasked = MinContext->NumStats;
}
}
int DecodeSymbol(CRangeDecoderVirt *rangeDecoder)
{
if (MinContext->NumStats != 1)
DecodeSymbol1(rangeDecoder);
else
DecodeBinSymbol(rangeDecoder);
while ( !FoundState )
{
do
{
OrderFall++;
MinContext = GetContext(MinContext->Suffix);
if (MinContext == 0)
return -1;
}
while (MinContext->NumStats == NumMasked);
DecodeSymbol2(rangeDecoder);
}
Byte symbol = FoundState->Symbol;
NextContext();
return symbol;
}
};
}}
#endif
<file_sep>/SQLCEHelper/Include/oledbcli.h
// OLE DB Client class library
//
// Copyright (C) 2008,2009 by <NAME>
//
#ifndef __OLEDBCLI_H__
#define __OLEDBCLI_H__
#include "sqlce_oledb.h"
#include "sqlce_ex.h"
#include "BlobStream.h"
namespace OLEDBCLI
{
class CSession;
class CRowset;
class CSchema;
// CDbMemory
//
// Static class to manage OLE DB memory
//
class CDbMemory
{
public:
static void Free(DBPROP* pProp);
static void Free(DBPROPSET* pPropSet);
static void Free(DBID &dbid);
static void Free(DBINDEXCOLUMNDESC* pKeyColumnDesc, ULONG nKeys);
};
// CDbProp
//
// Wraps the DBPROP structure
//
class CDbProp : public tagDBPROP
{
private:
void Copy(const DBPROP &prop);
public:
CDbProp();
CDbProp(const DBPROP &prop);
~CDbProp();
void Clear();
CDbProp& operator = (const CDbProp& rhs);
HRESULT CopyTo(DBPROP *pProp) const;
};
// CDbPropSet
//
// A set of CDbProp objects
//
class CDbPropSet : public tagDBPROPSET
{
public:
CDbPropSet(GUID guid);
~CDbPropSet();
void Clear ();
bool AddProperty(const CDbProp &prop);
bool AddProperty(DBPROPID id, int propVal);
bool AddProperty(DBPROPID id, bool propVal);
bool AddProperty(DBPROPID id, LPCTSTR propVal);
};
// CDbException
//
// OLE DB exception
//
class CDbException
{
protected:
HRESULT m_hr;
IErrorRecords* m_pErrorRecords;
public:
CDbException(HRESULT hr);
virtual ~CDbException();
ULONG GetErrorCount ();
HRESULT GetBasicErrorInfo (ULONG nError, ERRORINFO* pErrorInfo);
HRESULT GetErrorParameters (ULONG nError, DISPPARAMS* pDispParams);
HRESULT GetErrorSource (ULONG nError, BSTR* pBstrSource, LCID lcid = LOCALE_SYSTEM_DEFAULT);
HRESULT GetErrorSource (ULONG nError, CString& strSource, LCID lcid = LOCALE_SYSTEM_DEFAULT);
HRESULT GetErrorDescription (ULONG nError, BSTR* pBstrDescription, LCID lcid = LOCALE_SYSTEM_DEFAULT);
HRESULT GetErrorDescription (ULONG nError, CString& strDescription, LCID lcid = LOCALE_SYSTEM_DEFAULT);
};
// CBindingArray
//
// A "managed" DBBINDING array. Note the special requirement when cleaning up.
//
class CBindingArray
{
private:
DBBINDING* m_pBinding;
ULONG m_nItems;
public:
CBindingArray() : m_pBinding(NULL), m_nItems(0) { }
~CBindingArray()
{
Clear();
}
void Clear()
{
ULONG i;
DBBINDING* p;
for(i = 0, p = m_pBinding; i < m_nItems; ++i, ++p)
{
if(p->pObject != NULL) // DBOBJECT allocated?
delete p->pObject; // Delete it...
}
delete [] m_pBinding;
m_pBinding = NULL;
m_nItems = 0;
}
bool Allocate(ULONG nItems)
{
Clear();
m_pBinding = new DBBINDING[nItems];
if(m_pBinding != NULL)
{
memset(m_pBinding, 0, nItems * sizeof(DBBINDING));
m_nItems = nItems;
return true;
}
return false;
}
DBBINDING* operator[] (ULONG i)
{
ATLASSERT(i < m_nItems);
return m_pBinding + i;
}
};
// BOUNDCOLUMN
//
// Stores information about a bound column
//
struct BOUNDCOLUMN
{
LPOLESTR pwszName; // Column name
ULONG iOrdinal; // Column ordinal
ULONG obValue; // Binding value offset
ULONG obLength; // Binding length offset
ULONG obStatus; // Binding status offset
int iAccessor; // Accessor handle index
DBCOLUMNFLAGS dwFlags; // Column flags
ULONG ulColumnSize; // Column size
DBTYPE wType; // Column type (DBTYPE_*)
BYTE bPrecision; // Column precision
BYTE bScale; // Column scale
};
// CDbValueRef
//
// Value reference
//
class CDbValueRef
{
protected:
ULONG* m_pLength;
DBSTATUS* m_pStatus;
DBTYPE m_wType;
ULONG m_nMaxSize;
BYTE* m_pValue;
bool m_bIsLong;
public:
CDbValueRef();
CDbValueRef(BOUNDCOLUMN* pBoundColumn, BYTE* pData);
CDbValueRef(DBTYPE wType, ULONG* pLength, DBSTATUS* pStatus, BYTE* pValue);
void FreeStorage ();
ULONG GetLength () { return *m_pLength; }
ULONG GetMaxLength() { return m_nMaxSize; }
DBSTATUS GetStatus () { return *m_pStatus; }
DBTYPE GetType () { return m_wType; }
bool IsLong () { return m_bIsLong; }
void SetStatus (DBSTATUS status) { *m_pStatus = status; }
void SetLength (ULONG nLength) { *m_pLength = nLength; }
bool GetValue (bool& bVal);
bool SetValue (bool bVal);
bool GetValue (BYTE& bVal);
bool SetValue (BYTE bVal) { return SetValue(int(bVal)); }
bool GetValue (int& nVal);
bool SetValue (int nVal);
bool GetValue (short& nVal);
bool SetValue (short nVal) { return SetValue(int(nVal)); }
bool GetValue (__int64& nVal);
bool SetValue (__int64 nVal);
bool GetValue (double& dblVal);
bool SetValue (double dblVal);
bool GetValue (float& fltVal);
bool SetValue (float fltVal);
bool GetValue (CString& strVal);
bool SetValue (LPCTSTR pszVal);
bool SetValue (CString& strVal) { return SetValue((LPCTSTR)strVal); }
bool GetValue (BYTE* pVal);
bool SetValue (BYTE* pVal, ULONG nLength);
bool GetValue (GUID& guid);
bool SetValue (GUID& guid);
bool GetValue (CY& cyVal);
bool SetValue (CY cyVal);
bool GetValue (DBTIMESTAMP& dtVal);
bool SetValue (DBTIMESTAMP& dtVal);
bool GetValue (DB_NUMERIC& numVal);
bool SetValue (DB_NUMERIC& numVal);
bool SetValue (CBlobStream& blob);
bool GetValue (CBlobStream& blob);
};
// CDbValue
//
// Value
//
class CDbValue : public CDbValueRef
{
private:
union val
{
BYTE bVal;
int intVal;
__int64 lngVal;
short shortVal;
double dblVal;
float fltVal;
CY cyVal;
GUID guidVal;
VARIANT_BOOL boolVal;
DBTIMESTAMP dtVal;
DB_NUMERIC numVal;
BYTE* pVal;
TCHAR* pszVal;
} m_val; // Value
ULONG m_nLength; // Length
DBSTATUS m_status; // Status
void InternalCopy (const CDbValue& dbVal);
public:
CDbValue();
CDbValue(const CDbValue &dbVal);
CDbValue(DBTYPE type, ULONG nSize, DBSTATUS status, const void* pData);
~CDbValue();
void Initialize (DBTYPE type, ULONG nLength, ULONG nMaxLength, bool bIsLong);
void SetStatus (DBSTATUS status) { m_status = status; }
void Clear ();
void* GetDataPtr ();
void SetValue (DBTYPE type, ULONG nLength, DBSTATUS status, const void* pData);
HRESULT SetValue (DBTYPE type, ULONG nLength, DBSTATUS status, ISequentialStream* pStream);
bool SetValue (LPCTSTR pszVal);
bool SetValue (BYTE* pVal, ULONG nSize);
CDbValue& operator = (const CDbValue& dbVal);
};
// CDataSource
//
// Models an OLE DB Data Source object
//
class CDataSource
{
protected:
IDBInitialize* m_pInitialize;
public:
CDataSource();
virtual ~CDataSource();
HRESULT Open (const CLSID& clsid, ULONG cPropSets, DBPROPSET rgPropSets[]);
HRESULT Create (const CLSID& clsid, ULONG cPropSets, DBPROPSET rgPropSets[], CSession *pSession = NULL);
HRESULT Close ();
operator IDBInitialize*() const { return m_pInitialize; }
};
// CSession
//
// Models an OLE DB Session object
//
class CSession
{
protected:
ISessionProperties* m_pSessionProps;
public:
CSession();
virtual ~CSession();
operator IUnknown*() const { return m_pSessionProps; }
HRESULT Open (ISessionProperties* pSessionProperties);
HRESULT Open (const CDataSource& dataSource);
void Close ();
HRESULT SetProperties (ULONG cPropSets, DBPROPSET rgPropSets[]);
};
// CForeignKeyPair
//
// A pair of columns matched in a FOREIGN KEY
//
class CForeignKeyPair
{
private:
CString m_strRefName,
m_strKeyName;
public:
CForeignKeyPair(LPCTSTR pszRefName, LPCTSTR pszKeyName)
: m_strRefName(pszRefName),
m_strKeyName(pszKeyName)
{
}
LPCTSTR GetRefName () { return m_strRefName; }
LPCTSTR GetKeyName () { return m_strKeyName; }
};
typedef CAtlArray<CForeignKeyPair*> CForeignKeyPairArray;
// CForeignKey
//
// A foreign-key definition
//
class CForeignKey
{
private:
CString m_strName,
m_strRefTable;
CForeignKeyPairArray m_pairs;
DBMATCHTYPE m_match;
DBUPDELRULE m_deleteRule,
m_updateRule;
DBDEFERRABILITY m_deferrability;
void Clear();
public:
CForeignKey(DBCONSTRAINTDESC* pConstraintDesc);
~CForeignKey();
LPCTSTR GetName () { return m_strName; }
LPCTSTR GetRefTableName () { return m_strRefTable; }
DBMATCHTYPE GetMatchType () { return m_match; }
DBUPDELRULE GetDeleteRule () { return m_deleteRule; }
DBUPDELRULE GetUpdateRule () { return m_updateRule; }
DBDEFERRABILITY GetDeferrability() { return m_deferrability; }
bool AddPair (LPCTSTR pszRefName, LPCTSTR pszKeyName);
int GetPairCount () { return m_pairs.GetCount(); }
CForeignKeyPair* GetPair (int iIndex) { return m_pairs[iIndex]; }
};
typedef CAtlArray<CForeignKey*> CForeignKeyArray;
// CIndexColumn
//
// Contains an index column
//
class CIndexColumn
{
private:
CString m_strName;
short m_nCollation;
ULONG m_nOrdinal;
public:
CIndexColumn() : m_nCollation(DB_COLLATION_ASC), m_nOrdinal(0) { }
CIndexColumn(LPCTSTR pszColumnName, short nCollation, ULONG nOrdinal)
: m_strName (pszColumnName),
m_nCollation(nCollation),
m_nOrdinal (nOrdinal)
{
}
LPCTSTR GetName () { return m_strName; }
short GetCollation() { return m_nCollation; }
ULONG GetOrdinal () { return m_nOrdinal; }
};
typedef CAtlArray<CIndexColumn*> CIndexColumnArray;
// CIndex
//
// Contains information about a table index
//
class CIndex
{
private:
CString m_strName;
bool m_bUnique,
m_bPrimary,
m_bConstraint;
CIndexColumnArray m_columns;
public:
CIndex();
CIndex(LPCTSTR pszIndexName, bool bUnique, bool bPrimary);
CIndex(DBCONSTRAINTDESC* pConstraintDesc);
~CIndex();
void SetName (LPCTSTR pszName) { m_strName = pszName; }
LPCTSTR GetName () const { return m_strName; }
int GetColumnCount () { return int(m_columns.GetCount()); }
CIndexColumn* GetColumn (int iColumn) { return m_columns[iColumn]; }
void AddColumn (LPCTSTR pszColumnName, short nCollation, ULONG nOrdinal);
int FindColumn (LPCTSTR pszColumnName);
bool IsUnique () const { return m_bUnique; }
bool IsPrimaryKey () const { return m_bPrimary; }
bool IsConstraint () const { return m_bConstraint; }
};
typedef CAtlArray<CIndex*> CIndexArray;
// CColumn
//
// Contains column schema information
//
class CColumn
{
private:
CString m_strName, // Name
m_strDefault; // Default value
DBTYPE m_wType; // Type
ULONG m_ulOrdinal, // Ordinal within table
m_ulSize; // Size
INT m_nSeed, // Identity seed
m_nIncrement; // Identity increment
DBCOLUMNFLAGS m_dwFlags; // Flags
BYTE m_bPrecision, // Precision
m_bScale; // Scale
bool m_bRowGuid, // Is this a ROWGUIDCOL?
m_bIdentity; // Is this an IDENTITY column?
void ParseProperties(DBCOLUMNDESC* pColumnDesc);
public:
CColumn();
CColumn(DBCOLUMNDESC* pColumnDesc, ULONG iOrdinal);
~CColumn();
LPCTSTR GetName () { return m_strName; }
LPCTSTR GetDefault () { return m_strDefault; }
DBTYPE GetDbType () { return m_wType; }
ULONG GetSize () { return m_ulSize; }
ULONG GetOrdinal () { return m_ulOrdinal; }
BYTE GetPrecision () { return m_bPrecision; }
BYTE GetScale () { return m_bScale; }
DBCOLUMNFLAGS GetFlags () { return m_dwFlags; }
bool IsNullable () { return (m_dwFlags & DBCOLUMNFLAGS_ISNULLABLE) != 0; }
bool IsLong () { return (m_dwFlags & DBCOLUMNFLAGS_ISLONG) != 0; }
bool IsRowVersion () { return (m_dwFlags & DBCOLUMNFLAGS_ISROWVER) != 0; }
bool IsFixedLength () { return (m_dwFlags & DBCOLUMNFLAGS_ISFIXEDLENGTH) != 0; }
bool IsRowGuid () { return m_bRowGuid; }
bool IsIdentity () { return m_bIdentity; }
};
typedef CAtlArray<CColumn*> CColumnArray;
// CTableDefinition
//
// Helper class that retrieves the table schema definitions
//
class CTableDefinition
{
protected:
ULONG m_nColumns, // Number of columns
m_nPropSets, // Number of property sets
m_nConstraints; // Number of constraints
DBCOLUMNDESC* m_pColumns; // Column array
DBCONSTRAINTDESC* m_pConstraints; // Constraint array
OLECHAR* m_pStrings; // Strings
DBPROPSET* m_pPropSets; // Property set array
void Clear();
public:
CTableDefinition();
~CTableDefinition();
bool FillColumnArray (CColumnArray& columns);
bool FillForeignKeyArray (CForeignKeyArray& foreignKeys);
bool FillUniqueArray (CIndexArray& uniques);
CIndex* GetPrimaryKey ();
HRESULT GetDefinition(CSession& session, LPCTSTR pszTableName);
};
// CTable
//
// Opens a table cursor and renames an existing table.
//
class CTable
{
protected:
CSession& m_session;
CString m_strName;
public:
CTable(CSession& session, LPCTSTR pszTableName);
virtual ~CTable();
LPCTSTR GetName () { return m_strName; }
HRESULT Rename (LPCTSTR pszNewName);
HRESULT Open (ULONG cPropSets, DBPROPSET rgPropSets[], LPCTSTR pszIndexName, CRowset& rowset);
};
// CTableSchema
//
// Contains table schema information
//
class CTableSchema
{
private:
CSchema* m_pSchema; // Containing CSchema, if any.
CString m_strName;
CColumnArray m_columns;
CIndexArray m_indexes,
m_uniques;
CForeignKeyArray m_foreignKeys;
bool m_bLoaded;
HRESULT LoadIndexes (CSession& session);
bool Copy (const CTableSchema& tableSchema);
public:
CTableSchema();
CTableSchema(LPCTSTR pszTableName, CSchema* pSchema = NULL);
CTableSchema(const CTableSchema& tableSchema);
~CTableSchema();
CTableSchema& operator =(const CTableSchema& tableSchema);
HRESULT Load ();
HRESULT Load (CSession& session, LPCTSTR pszTableName);
void Clear ();
LPCTSTR GetName () const { return m_strName; }
int GetColumnCount () const { return int(m_columns.GetCount()); }
int GetIndexCount () const { return int(m_indexes.GetCount()); }
int GetUniqueCount () const { return int(m_uniques.GetCount()); }
int GetForeignKeyCount () const { return int(m_foreignKeys.GetCount()); }
bool IsLoaded () const { return m_bLoaded; }
int FindColumn (LPCTSTR pszName);
int FindIndex (LPCTSTR pszName);
int FindUnique (LPCTSTR pszName);
int FindForeignKey (LPCTSTR pszName);
CColumn* GetColumn (int iItem) { return m_columns[iItem]; }
CIndex* GetIndex (int iItem) { return m_indexes[iItem]; }
CIndex* GetUnique (int iItem) { return m_uniques[iItem]; }
CIndex* GetPrimaryKey ();
CForeignKey* GetForeignKey (int iItem) { return m_foreignKeys[iItem]; }
CSchema* GetSchema () const { return m_pSchema; }
};
typedef CAtlArray<CTableSchema*> CTableSchemaArray;
// CSchema
//
// Contains the database schema information
//
class CSchema
{
protected:
CTableSchemaArray m_tables;
CSession& m_session;
public:
CSchema(CSession& m_session);
virtual ~CSchema();
HRESULT Load ();
void Clear ();
CTableSchema* GetTableSchema (int iTable) { return m_tables[iTable]; }
int GetTableCount () { return int(m_tables.GetCount()); }
CSession& GetSession () { return m_session; }
};
// CCommand
//
// OLE DB Command class
//
class CCommand
{
protected:
ICommandText* m_pCommand; // OLE DB Command interface pointer
ULONG m_nParams; // Number of parameters
LPOLESTR m_pszParamNames; // Parameter names
BOUNDCOLUMN* m_pBoundParam; // Bound parameter
BYTE* m_pBuffer; // Parameter data buffer
ULONG m_nRowSize; // Parameter data buffer size
DBBINDSTATUS* m_pBindStatus; // Binding status (useful for debugging)
HACCESSOR m_hParamAccessor; // Unique accessor handle used to bind parameters
CDbValue* m_pParam;
DBPARAMINFO* m_pParamInfo;
void SetAllParameters();
HRESULT CreateParameters(DBPARAMINFO* pParamInfo);
bool RebindParameters();
void ClearParameters ();
void ClearBinding ();
HRESULT BindParameters ();
ULONG FindParameter (ULONG iOrdinal);
public:
CCommand(CSession& session);
virtual ~CCommand();
ULONG GetParamCount() { return m_nParams; }
HRESULT SetText (LPCTSTR pszText);
HRESULT Prepare (ULONG cExpectedRuns = 0);
HRESULT Unprepare ();
HRESULT Execute (LONG* pcRowsAffected = NULL);
HRESULT Execute (CRowset& rowset, LONG* pcRowsAffected = NULL);
template <typename T>
bool SetParam(ULONG iOrdinal, T value)
{
ULONG iParam = FindParameter(iOrdinal);
if(iParam == (ULONG)-1)
return false;
return m_pParam[iParam].SetValue(value);
}
bool SetParam(ULONG iOrdinal, BYTE* pValue, ULONG nSize)
{
ULONG iParam = FindParameter(iOrdinal);
if(iParam == (ULONG)-1)
return false;
return m_pParam[iParam].SetValue(pValue, nSize);
}
bool GetStatus(ULONG iOrdinal, DBSTATUS& status)
{
ULONG iParam = FindParameter(iOrdinal);
if(iParam == (ULONG)-1)
return false;
status = m_pParam[iParam].GetStatus();
return true;
}
};
// CShemaRowset
//
// Base schema rowset
//
class CSchemaRowset
{
protected:
IDBSchemaRowset* m_pSchemaRowset;
public:
CSchemaRowset(CSession& session);
virtual ~CSchemaRowset();
HRESULT Open(REFGUID rguidSchema, ULONG cRestrictions, const VARIANT rgRestrictions[], CRowset &rowset);
};
// CTablesRowset
//
// Tables schema rowset
//
class CTablesRowset : public CSchemaRowset
{
public:
CTablesRowset(CSession& session) : CSchemaRowset(session) { }
HRESULT Open(LPCTSTR pszCatalog, LPCTSTR pszSchema, LPCTSTR pszTable, LPCTSTR pszType, CRowset& rowset);
};
// CColumnsRowset
//
// Columns rowset
//
class CColumnsRowset : public CSchemaRowset
{
public:
CColumnsRowset(CSession& session) : CSchemaRowset(session) { }
HRESULT Open(LPCTSTR pszTableCatalog, LPCTSTR pszTableSchema, LPCTSTR pszTableName, LPCTSTR pszColumnName, CRowset& rowset);
};
// CViewsRowset
//
// Views schema rowset
//
class CViewsRowset : public CSchemaRowset
{
public:
CViewsRowset(CSession& session) : CSchemaRowset(session) { }
HRESULT Open(LPCTSTR pszCatalog, LPCTSTR pszSchema, LPCTSTR pszTable, CRowset& rowset);
};
class CIndexesRowset : public CSchemaRowset
{
public:
CIndexesRowset(CSession& session) : CSchemaRowset(session) { }
HRESULT Open(LPCTSTR pszCatalog, LPCTSTR pszTableSchema, LPCTSTR pszIndexName, LPCTSTR pszType, LPCTSTR pszTableName, CRowset& rowset);
};
// CRowset
//
// Implements a generic rowset
//
class CRowset
{
protected:
IRowset* m_pRowset;
IRowsetChange* m_pRowsetChange;
IRowsetUpdate* m_pRowsetUpdate;
IRowsetIndex* m_pRowsetIndex;
IAccessor* m_pColAccessor;
IAccessor* m_pKeyAccessor;
HROW m_hRow; // Current row handle
ULONG m_nColumns, // Number of data columns
m_nKeyColumns, // Number of key columns
m_nAccessors, // Number of accessor handles
m_nRowSize, // Data buffer size
m_nKeySize; // Key data buffer size
BOUNDCOLUMN* m_pBoundColumn;
BOUNDCOLUMN* m_pBoundKey;
OLECHAR* m_pColumnNames;
HACCESSOR* m_phAccessor; // Accessor handle array for column values
HACCESSOR m_hKeyAccessor; // Accessor handle for key values
BYTE* m_pBuffer; // Data buffer
BYTE* m_pKeyBuffer; // Key data buffer
DBBINDSTATUS* m_pBindStatus; // Binding status (useful for debugging)
bool m_bCustomBound; // Columns were custom bound
CDbValueRef* m_pValueRef;
CDbValueRef* m_pKeyRef;
ULONG GetBlobCount(DBCOLUMNINFO* pColumnInfo, ULONG nColumns);
DBCOLUMNINFO* GetTableColumnInfo (LPCTSTR pszColumnName, DBCOLUMNINFO* pColumnInfo);
HRESULT BindKeyColumns (DBCOLUMNINFO* pColumnInfo);
public:
CRowset();
virtual ~CRowset();
HRESULT Open (IRowset* pRowset);
void Close ();
bool IsOpen () { return m_pColAccessor != NULL; }
HRESULT ReleaseRow ();
HRESULT GetRowCount (ULONG* pcRows);
HRESULT MoveRelative (LONG nOffset);
HRESULT MoveFirst ();
HRESULT MoveNext () { return MoveRelative(1); }
HRESULT MovePrev () { return MoveRelative(-1); }
HRESULT MoveToBookmark (ULONG cbBookmark, const BYTE* pBookmark);
HRESULT Insert ();
HRESULT Delete ();
HRESULT SetData ();
HRESULT Update ();
HRESULT Undo ();
HRESULT SeekRow (int cKeyValues, DBSEEK dwSeekOptions = DBSEEK_FIRSTEQ);
HRESULT Seek (int cKeyValues, DBSEEK dwSeekOptions = DBSEEK_FIRSTEQ);
template <typename T>
bool GetValue(ULONG iOrdinal, T& value)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
if(iColumn == (ULONG)-1)
return false;
CDbValueRef& valRef = m_pValueRef[iColumn];
// Is this a BLOB?
if(valRef.IsLong())
{
int iAccessor = m_pBoundColumn[iColumn].iAccessor; // Get the accessor handle index
HRESULT hr = m_pRowset->GetData(m_hRow, m_phAccessor[iAccessor], m_pBuffer); // Get the BLOB data
if(FAILED(hr))
return false;
}
return valRef.GetValue(value);
}
template <typename T>
bool SetValue(ULONG iOrdinal, T value)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
if(iColumn == (ULONG)-1)
return false;
return m_pValueRef[iColumn].SetValue(value);
}
bool SetValue(ULONG iOrdinal, BYTE* pValue, ULONG nSize)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
if(iColumn == (ULONG)-1)
return false;
return m_pValueRef[iColumn].SetValue(pValue, nSize);
}
template <typename T>
bool SetKeyValue(ULONG iOrdinal, T value)
{
ATLASSERT(iOrdinal > 0 && iOrdinal <= m_nKeyColumns);
return m_pKeyRef[iOrdinal-1].SetValue(value);
}
// Column accessors via column index (low-level access)
ULONG _GetLength(ULONG iColumn) { return *(ULONG*)(m_pBuffer + m_pBoundColumn[iColumn].obLength); }
DBSTATUS _GetStatus(ULONG iColumn) { return *(DBSTATUS*)(m_pBuffer + m_pBoundColumn[iColumn].obStatus); }
BYTE* _GetValPtr(ULONG iColumn) { return m_pBuffer + m_pBoundColumn[iColumn].obValue; }
void _SetLength(ULONG iColumn, ULONG nLength)
{
*(ULONG*)(m_pBuffer + m_pBoundColumn[iColumn].obLength) = nLength;
}
void _SetStatus(ULONG iColumn, DBSTATUS status)
{
*(DBSTATUS*)(m_pBuffer + m_pBoundColumn[iColumn].obStatus) = status;
}
ULONG GetColumnCount() { return m_nColumns; }
ULONG GetRowSize () { return m_nRowSize; }
BYTE* GetRowBuffer() { return m_pBuffer; }
BOUNDCOLUMN* GetColumnInfo(ULONG iColumn) { return m_pBoundColumn + iColumn; }
DBSTATUS GetStatus(ULONG iOrdinal);
ULONG GetLength(ULONG iOrdinal);
BYTE* GetValPtr(ULONG iOrdinal);
void SetStatus(ULONG iOrdinal, DBSTATUS status);
void SetLength(ULONG iOrdinal, ULONG nLength);
bool HasBookmark ();
ULONG GetColumnIndex (ULONG iOrdinal);
// ULONG GetColumnIndex (LPCTSTR pszColumnName);
};
//---------------------------------------------------------------------
//
// Inline methods
//
//---------------------------------------------------------------------
inline DBSTATUS CRowset::GetStatus(ULONG iOrdinal)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
return *(DBSTATUS*)(m_pBuffer + m_pBoundColumn[iColumn].obStatus);
}
inline ULONG CRowset::GetLength(ULONG iOrdinal)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
return *(ULONG*)(m_pBuffer + m_pBoundColumn[iColumn].obLength);
}
inline BYTE* CRowset::GetValPtr(ULONG iOrdinal)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
return (BYTE*)(m_pBuffer + m_pBoundColumn[iColumn].obValue);
}
inline void CRowset::SetStatus(ULONG iOrdinal, DBSTATUS status)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
DBSTATUS* pStatus = (DBSTATUS*)(m_pBuffer + m_pBoundColumn[iColumn].obStatus);
*pStatus = status;
}
inline void CRowset::SetLength(ULONG iOrdinal, ULONG nLength)
{
ULONG iColumn = GetColumnIndex(iOrdinal);
ULONG* pLength = (ULONG*)(m_pBuffer + m_pBoundColumn[iColumn].obLength);
*pLength = nLength;
}
// Returns true if the rowset has a bound bookmark.
inline bool CRowset::HasBookmark()
{
ATLASSERT(m_pBoundColumn != NULL);
return m_pBoundColumn[0].iOrdinal == 0;
}
}; // namespace OLEDBCLI
#endif // __OLEDBCLI_H__
<file_sep>/SQLCEHelper/Source/DbProp.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
CDbProp::CDbProp()
{
dwPropertyID = 0;
dwOptions = 0;
dwStatus = 0;
memset(&colid, 0, sizeof(colid));
VariantInit(&vValue);
}
CDbProp::CDbProp(const DBPROP &prop)
{
Copy(prop);
}
CDbProp::~CDbProp()
{
Clear();
}
void CDbProp::Copy(const DBPROP &prop)
{
dwPropertyID = prop.dwPropertyID;
dwOptions = prop.dwOptions;
dwStatus = prop.dwStatus;
memcpy(&colid, &prop.colid, sizeof(DBID));
VariantCopy(&vValue, const_cast<VARIANT*>(&prop.vValue));
}
void CDbProp::Clear()
{
dwPropertyID = 0;
dwOptions = 0;
dwStatus = 0;
memset(&colid, 0, sizeof(colid));
VariantClear(&vValue);
}
CDbProp& CDbProp::operator = (const CDbProp& rhs)
{
if(this != &rhs)
Copy(rhs);
return *this;
}
HRESULT CDbProp::CopyTo(DBPROP *pProp) const
{
ATLASSERT(pProp != NULL);
HRESULT hr;
pProp->dwPropertyID = dwPropertyID;
pProp->dwOptions = dwOptions;
pProp->dwStatus = dwStatus;
memcpy(&pProp->colid, &colid, sizeof(DBID));
VariantInit(&pProp->vValue);
hr = VariantCopy(&pProp->vValue, (VARIANT*)&vValue);
return hr;
}
<file_sep>/7-Zip/CPP/7zip/Archive/Com/ComIn.cpp
// Archive/ComIn.cpp
#include "StdAfx.h"
#include "../../../../C/Alloc.h"
#include "../../../../C/CpuArch.h"
#include "Common/IntToString.h"
#include "Common/MyCom.h"
#include "../../Common/StreamUtils.h"
#include "ComIn.h"
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
namespace NArchive{
namespace NCom{
static const UInt32 kSignatureSize = 8;
static const Byte kSignature[kSignatureSize] = { 0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1 };
void CUInt32Buf::Free()
{
MyFree(_buf);
_buf = 0;
}
bool CUInt32Buf::Allocate(UInt32 numItems)
{
Free();
if (numItems == 0)
return true;
size_t newSize = (size_t)numItems * sizeof(UInt32);
if (newSize / sizeof(UInt32) != numItems)
return false;
_buf = (UInt32 *)MyAlloc(newSize);
return (_buf != 0);
}
static HRESULT ReadSector(IInStream *inStream, Byte *buf, int sectorSizeBits, UInt32 sid)
{
RINOK(inStream->Seek((((UInt64)sid + 1) << sectorSizeBits), STREAM_SEEK_SET, NULL));
return ReadStream_FALSE(inStream, buf, (UInt32)1 << sectorSizeBits);
}
static HRESULT ReadIDs(IInStream *inStream, Byte *buf, int sectorSizeBits, UInt32 sid, UInt32 *dest)
{
RINOK(ReadSector(inStream, buf, sectorSizeBits, sid));
UInt32 sectorSize = (UInt32)1 << sectorSizeBits;
for (UInt32 t = 0; t < sectorSize; t += 4)
*dest++ = Get32(buf + t);
return S_OK;
}
static void GetFileTimeFromMem(const Byte *p, FILETIME *ft)
{
ft->dwLowDateTime = Get32(p);
ft->dwHighDateTime = Get32(p + 4);
}
void CItem::Parse(const Byte *p, bool mode64bit)
{
memcpy(Name, p, kNameSizeMax);
// NameSize = Get16(p + 64);
Type = p[66];
LeftDid = Get32(p + 68);
RightDid = Get32(p + 72);
SonDid = Get32(p + 76);
// Flags = Get32(p + 96);
GetFileTimeFromMem(p + 100, &CTime);
GetFileTimeFromMem(p + 108, &MTime);
Sid = Get32(p + 116);
Size = Get32(p + 120);
if (mode64bit)
Size |= ((UInt64)Get32(p + 124) << 32);
}
void CDatabase::Clear()
{
Fat.Free();
MiniSids.Free();
Mat.Free();
Items.Clear();
Refs.Clear();
}
static const UInt32 kNoDid = 0xFFFFFFFF;
HRESULT CDatabase::AddNode(int parent, UInt32 did)
{
if (did == kNoDid)
return S_OK;
if (did >= (UInt32)Items.Size())
return S_FALSE;
const CItem &item = Items[did];
if (item.IsEmpty())
return S_FALSE;
CRef ref;
ref.Parent = parent;
ref.Did = did;
int index = Refs.Add(ref);
if (Refs.Size() > Items.Size())
return S_FALSE;
RINOK(AddNode(parent, item.LeftDid));
RINOK(AddNode(parent, item.RightDid));
if (item.IsDir())
{
RINOK(AddNode(index, item.SonDid));
}
return S_OK;
}
static const char kCharOpenBracket = '[';
static const char kCharCloseBracket = ']';
static UString CompoundNameToFileName(const UString &s)
{
UString res;
for (int i = 0; i < s.Length(); i++)
{
wchar_t c = s[i];
if (c < 0x20)
{
res += kCharOpenBracket;
wchar_t buf[32];
ConvertUInt32ToString(c, buf);
res += buf;
res += kCharCloseBracket;
}
else
res += c;
}
return res;
}
static char g_MsiChars[] =
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz._";
static const wchar_t *kMsi_ID = L""; // L"{msi}";
static const int kMsiNumBits = 6;
static const UInt32 kMsiNumChars = 1 << kMsiNumBits;
static const UInt32 kMsiCharMask = kMsiNumChars - 1;
static const UInt32 kMsiStartUnicodeChar = 0x3800;
static const UInt32 kMsiUnicodeRange = kMsiNumChars * (kMsiNumChars + 1);
bool CompoundMsiNameToFileName(const UString &name, UString &resultName)
{
resultName.Empty();
for (int i = 0; i < name.Length(); i++)
{
wchar_t c = name[i];
if (c < kMsiStartUnicodeChar || c > kMsiStartUnicodeChar + kMsiUnicodeRange)
return false;
if (i == 0)
resultName += kMsi_ID;
c -= kMsiStartUnicodeChar;
UInt32 c0 = c & kMsiCharMask;
UInt32 c1 = c >> kMsiNumBits;
if (c1 <= kMsiNumChars)
{
resultName += (wchar_t)g_MsiChars[c0];
if (c1 == kMsiNumChars)
break;
resultName += (wchar_t)g_MsiChars[c1];
}
else
resultName += L'!';
}
return true;
}
static UString ConvertName(const Byte *p)
{
UString s;
for (int i = 0; i < kNameSizeMax; i += 2)
{
wchar_t c = (p[i] | (wchar_t)p[i + 1] << 8);
if (c == 0)
break;
s += c;
}
UString msiName;
if (CompoundMsiNameToFileName(s, msiName))
return msiName;
return CompoundNameToFileName(s);
}
UString CDatabase::GetItemPath(UInt32 index) const
{
UString s;
while (index != kNoDid)
{
const CRef &ref = Refs[index];
const CItem &item = Items[ref.Did];
if (!s.IsEmpty())
s = (UString)WCHAR_PATH_SEPARATOR + s;
s = ConvertName(item.Name) + s;
index = ref.Parent;
}
return s;
}
HRESULT CDatabase::Open(IInStream *inStream)
{
static const UInt32 kHeaderSize = 512;
Byte p[kHeaderSize];
RINOK(ReadStream_FALSE(inStream, p, kHeaderSize));
if (memcmp(p, kSignature, kSignatureSize) != 0)
return S_FALSE;
if (Get16(p + 0x1A) > 4) // majorVer
return S_FALSE;
if (Get16(p + 0x1C) != 0xFFFE)
return S_FALSE;
int sectorSizeBits = Get16(p + 0x1E);
bool mode64bit = (sectorSizeBits >= 12);
int miniSectorSizeBits = Get16(p + 0x20);
SectorSizeBits = sectorSizeBits;
MiniSectorSizeBits = miniSectorSizeBits;
if (sectorSizeBits > 28 || miniSectorSizeBits > 28 ||
sectorSizeBits < 7 || miniSectorSizeBits < 2 || miniSectorSizeBits > sectorSizeBits)
return S_FALSE;
UInt32 numSectorsForFAT = Get32(p + 0x2C);
LongStreamMinSize = Get32(p + 0x38);
UInt32 sectSize = (UInt32)1 << (int)sectorSizeBits;
CByteBuffer sect;
sect.SetCapacity(sectSize);
int ssb2 = (int)(sectorSizeBits - 2);
UInt32 numSidsInSec = (UInt32)1 << ssb2;
UInt32 numFatItems = numSectorsForFAT << ssb2;
if ((numFatItems >> ssb2) != numSectorsForFAT)
return S_FALSE;
FatSize = numFatItems;
{
CUInt32Buf bat;
UInt32 numSectorsForBat = Get32(p + 0x48);
const UInt32 kNumHeaderBatItems = 109;
UInt32 numBatItems = kNumHeaderBatItems + (numSectorsForBat << ssb2);
if (numBatItems < kNumHeaderBatItems || ((numBatItems - kNumHeaderBatItems) >> ssb2) != numSectorsForBat)
return S_FALSE;
if (!bat.Allocate(numBatItems))
return S_FALSE;
UInt32 i;
for (i = 0; i < kNumHeaderBatItems; i++)
bat[i] = Get32(p + 0x4c + i * 4);
UInt32 sid = Get32(p + 0x44);
for (UInt32 s = 0; s < numSectorsForBat; s++)
{
RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, bat + i));
i += numSidsInSec - 1;
sid = bat[i];
}
numBatItems = i;
if (!Fat.Allocate(numFatItems))
return S_FALSE;
UInt32 j = 0;
for (i = 0; i < numFatItems; j++, i += numSidsInSec)
{
if (j >= numBatItems)
return S_FALSE;
RINOK(ReadIDs(inStream, sect, sectorSizeBits, bat[j], Fat + i));
}
}
UInt32 numMatItems;
{
UInt32 numSectorsForMat = Get32(p + 0x40);
numMatItems = (UInt32)numSectorsForMat << ssb2;
if ((numMatItems >> ssb2) != numSectorsForMat)
return S_FALSE;
if (!Mat.Allocate(numMatItems))
return S_FALSE;
UInt32 i;
UInt32 sid = Get32(p + 0x3C);
for (i = 0; i < numMatItems; i += numSidsInSec)
{
RINOK(ReadIDs(inStream, sect, sectorSizeBits, sid, Mat + i));
if (sid >= numFatItems)
return S_FALSE;
sid = Fat[sid];
}
if (sid != NFatID::kEndOfChain)
return S_FALSE;
}
{
UInt32 sid = Get32(p + 0x30);
for (;;)
{
if (sid >= numFatItems)
return S_FALSE;
RINOK(ReadSector(inStream, sect, sectorSizeBits, sid));
for (UInt32 i = 0; i < sectSize; i += 128)
{
CItem item;
item.Parse(sect + i, mode64bit);
Items.Add(item);
}
sid = Fat[sid];
if (sid == NFatID::kEndOfChain)
break;
}
}
CItem root = Items[0];
{
UInt32 numSectorsInMiniStream;
{
UInt64 numSatSects64 = (root.Size + sectSize - 1) >> sectorSizeBits;
if (numSatSects64 > NFatID::kMaxValue)
return S_FALSE;
numSectorsInMiniStream = (UInt32)numSatSects64;
}
NumSectorsInMiniStream = numSectorsInMiniStream;
if (!MiniSids.Allocate(numSectorsInMiniStream))
return S_FALSE;
{
UInt64 matSize64 = (root.Size + ((UInt64)1 << miniSectorSizeBits) - 1) >> miniSectorSizeBits;
if (matSize64 > NFatID::kMaxValue)
return S_FALSE;
MatSize = (UInt32)matSize64;
if (numMatItems < MatSize)
return S_FALSE;
}
UInt32 sid = root.Sid;
for (UInt32 i = 0; ; i++)
{
if (sid == NFatID::kEndOfChain)
{
if (i != numSectorsInMiniStream)
return S_FALSE;
break;
}
if (i >= numSectorsInMiniStream)
return S_FALSE;
MiniSids[i] = sid;
if (sid >= numFatItems)
return S_FALSE;
sid = Fat[sid];
}
}
return AddNode(-1, root.SonDid);
}
}}
<file_sep>/SQLCEHelper/Source/DbException.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
CDbException::CDbException(HRESULT hr)
: m_hr (hr),
m_pErrorRecords (NULL)
{
CComPtr<IErrorInfo> spErrorInfo = NULL;
hr = GetErrorInfo(0, &spErrorInfo);
if(SUCCEEDED(hr))
spErrorInfo->QueryInterface(IID_IErrorRecords, (void**)&m_pErrorRecords);
}
CDbException::~CDbException()
{
if(m_pErrorRecords != NULL)
{
m_pErrorRecords->Release();
m_pErrorRecords = NULL;
}
}
ULONG CDbException::GetErrorCount()
{
HRESULT hr = S_OK;
ULONG nCount = 0;
if(m_pErrorRecords != NULL)
hr = m_pErrorRecords->GetRecordCount(&nCount);
return SUCCEEDED(hr) ? nCount : 0;
}
HRESULT CDbException::GetBasicErrorInfo(ULONG nError, ERRORINFO* pErrorInfo)
{
HRESULT hr = E_NOINTERFACE;
if(m_pErrorRecords != NULL)
hr = m_pErrorRecords->GetBasicErrorInfo(nError, pErrorInfo);
return hr;
}
HRESULT CDbException::GetErrorParameters(ULONG nError, DISPPARAMS* pDispParams)
{
HRESULT hr = E_NOINTERFACE;
if(m_pErrorRecords != NULL)
hr = m_pErrorRecords->GetErrorParameters(nError, pDispParams);
return hr;
}
HRESULT CDbException::GetErrorSource(ULONG nError, BSTR* pBstrSource, LCID lcid)
{
HRESULT hr = E_NOINTERFACE;
if(m_pErrorRecords != NULL)
{
CComPtr<IErrorInfo> spErrorInfo;
hr = m_pErrorRecords->GetErrorInfo(nError, lcid, &spErrorInfo);
if(SUCCEEDED(hr))
hr = spErrorInfo->GetSource(pBstrSource);
}
return hr;
}
HRESULT CDbException::GetErrorSource(ULONG nError, CString& strSource, LCID lcid)
{
HRESULT hr;
BSTR bstr;
hr = GetErrorSource(nError, &bstr, lcid);
if(SUCCEEDED(hr))
{
strSource = bstr;
SysFreeString(bstr);
}
return hr;
}
HRESULT CDbException::GetErrorDescription(ULONG nError, BSTR* pBstrDescription, LCID lcid)
{
HRESULT hr = E_NOINTERFACE;
if(m_pErrorRecords != NULL)
{
CComPtr<IErrorInfo> spErrorInfo;
hr = m_pErrorRecords->GetErrorInfo(nError, lcid, &spErrorInfo);
if(SUCCEEDED(hr))
hr = spErrorInfo->GetDescription(pBstrDescription);
}
return hr;
}
HRESULT CDbException::GetErrorDescription(ULONG nError, CString& strDescription, LCID lcid)
{
HRESULT hr;
BSTR bstr;
hr = GetErrorDescription(nError, &bstr, lcid);
if(SUCCEEDED(hr))
{
strDescription = bstr;
SysFreeString(bstr);
}
return hr;
}
<file_sep>/FingerSuite/Common/log/logger.h
#ifndef LOGGER_H
#define LOGGER_H
#pragma once
//#include <windows.h>
#ifndef __ATLMISC_H__
#error logger.h requires atlmisc.h to be included first
#endif
//#ifdef __cplusplus
//extern "C" {
//#endif
//#define NOLOG
#ifndef NOLOG
//#define LOG LogEventDebug
#define LOG LogEventFile
#else
#define LOG //
#endif
#define _INTERNAL_LOG_NAME L"\\Storage Card\\fingersuite.log"
inline void WriteFileWChar(HANDLE hFile, TCHAR* buf)
{
char cbuf[1025];
DWORD w = wcslen(buf);
w = WideCharToMultiByte(CP_ACP, 0, buf, w, cbuf, sizeof(cbuf), NULL, NULL);
WriteFile(hFile, cbuf, w, (LPDWORD)&w, NULL);
}
inline void LogEventDebug(LPCTSTR str, ...)
{
if (str == NULL) return;
TCHAR buf[1100];
va_list argptr;
va_start(argptr, str);
HRESULT ecode;
if (FAILED(ecode=StringCchVPrintf(buf, 1100, str, argptr)))
StringCchPrintf(buf, 1100, L"StringCchVPrintf error: %d\n", ecode);
va_end(argptr);
OutputDebugString(buf);
}
inline void LogEventFile(LPCTSTR str, ...)
{
static TCHAR* hLogFileName = 0;
static HANDLE hLogFile = 0;
if (str == NULL) return;
if (!hLogFileName)
{
TCHAR buf[MAX_PATH+1];
wcscpy(buf, L"");
wcscat(buf, _INTERNAL_LOG_NAME);
hLogFileName = (TCHAR*)malloc(sizeof(TCHAR)*wcslen(buf)+1);
wcscpy(hLogFileName, buf);
hLogFile = CreateFile(hLogFileName, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
SetFilePointer(hLogFile, 0, NULL, FILE_END);
LOG(L"New log begins...\n");
}
if (!hLogFile && hLogFileName)
{
hLogFile = CreateFile(hLogFileName, GENERIC_WRITE | GENERIC_READ, 0, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
SetFilePointer(hLogFile, 0, NULL, FILE_END);
}
if (hLogFile)
{
TCHAR buf[1025];
SYSTEMTIME stime;
GetLocalTime(&stime);
wsprintf(buf, L"%02d-%02d-%02d %02d:%02d:%02d ",
stime.wYear, stime.wMonth, stime.wDay, stime.wHour, stime.wMinute, stime.wSecond);
WriteFileWChar(hLogFile, buf);
va_list argptr;
va_start(argptr, str);
HRESULT ecode;
if (FAILED(ecode=StringCchVPrintf(buf, 1100, str, argptr)))
StringCchPrintf(buf, 1100, L"StringCchVPrintf error: %d\n", ecode);
va_end(argptr);
WriteFileWChar(hLogFile, buf);
#ifdef LOG_EXCLUSIVE
FlushFileBuffers(hLogFile);
#else
CloseHandle(hLogFile);
hLogFile = 0;
#endif
OutputDebugString(buf); // log to screen
}
}
inline void LogEventNull(LPCTSTR str, ...)
{
}
/////////////////////////////////////////////////
inline CString MifMaskString(DWORD f)
{
CSimpleArray<CString> l;
if (f&MIIM_CHECKMARKS) l.Add(L"MIIM_CHECKMARKS");
if (f&MIIM_DATA ) l.Add(L"MIIM_DATA");
if (f&MIIM_ID ) l.Add(L"MIIM_ID");
if (f&MIIM_STATE ) l.Add(L"MIIM_STATE");
if (f&MIIM_SUBMENU ) l.Add(L"MIIM_SUBMENU");
if (f&MIIM_TYPE ) l.Add(L"MIIM_TYPE");
if (f&MIIM_FULLSTR ) l.Add(L"MIIM_FULLSTR");
DWORD all = MIIM_CHECKMARKS|MIIM_DATA|MIIM_ID|MIIM_STATE|MIIM_SUBMENU|MIIM_TYPE|MIIM_FULLSTR;
if (f&~all) {
CString a; a.Format(L"MASK_%08lx", f&~all);
l.Add(a);
}
CString b;
for (int i = 0; i < l.GetSize(); i++)
b += l[i] + L",";
return b;
}
inline CString MifTypeString(DWORD f)
{
CSimpleArray<CString> l;
if (f&MFT_MENUBARBREAK ) l.Add(L"MFT_MENUBARBREAK");
if (f&MFT_MENUBREAK ) l.Add(L"MFT_MENUBREAK");
if (f&MFT_OWNERDRAW ) l.Add(L"MFT_OWNERDRAW");
if (f&MFT_RADIOCHECK ) l.Add(L"MFT_RADIOCHECK");
if (f&MFT_SEPARATOR ) l.Add(L"MFT_SEPARATOR");
if (f == MFT_STRING ) l.Add(L"MFT_STRING"); // MFT_STRING = 0
DWORD all = MFT_MENUBARBREAK|MFT_MENUBREAK|MFT_OWNERDRAW|MFT_RADIOCHECK|MFT_SEPARATOR|MFT_STRING;
if (f&~all) {
CString a; a.Format(L"TYPE_%08lx", f&~all);
l.Add(a);
}
CString b;
for (int i = 0; i < l.GetSize(); i++)
b += l[i] + L",";
return b;
}
inline CString MifStateString(DWORD f)
{
CSimpleArray<CString> l;
if (f&MFS_CHECKED ) l.Add(L"MFS_CHECKED");
if (f&MFS_ENABLED ) l.Add(L"MFS_ENABLED");
if (f&MFS_HILITE ) l.Add(L"MFS_HILITE");
if (f&MFS_UNCHECKED ) l.Add(L"MFS_UNCHECKED");
if (f&MFS_UNHILITE ) l.Add(L"MFS_UNHILITE");
DWORD all = MFS_CHECKED|MFS_ENABLED|MFS_HILITE|MFS_UNCHECKED|MFS_UNHILITE;
if (f&~all) {
CString a; a.Format(L"TYPE_%08lx", f&~all);
l.Add(a);
}
CString b;
for (int i = 0; i < l.GetSize(); i++)
b += l[i] + L",";
return b;
}
inline void DUMP_MENUITEMINFO(MENUITEMINFO* mif)
{
//LOG(L"\n\n");
if (mif->cbSize != sizeof(MENUITEMINFO))
LOG(L"NOTE: structsize = 0x%x ( expected 0x%x )\n", mif->cbSize, sizeof(MENUITEMINFO));
LOG(L"fMask : %s\n", MifMaskString(mif->fMask));
LOG(L"fType : %s\n", MifTypeString(mif->fType));
LOG(L"fState : %s\n", MifStateString(mif->fState));
LOG(L"dwID : %d (Ox%08lx)\n", mif->wID, mif->wID);
LOG(L"hSubMenu : Ox%08lx\n", mif->hSubMenu);
LOG(L"hbmpChecked : Ox%08lx\n", mif->hbmpChecked);
LOG(L"hbmpUnchecked : Ox%08lx\n", mif->hbmpUnchecked);
LOG(L"dwItemData : %d (Ox%08lx)\n", mif->dwItemData, mif->dwItemData);
//if (mif->fType == MFT_STRING)
LOG(L"dwTypeData : %s\n", mif->dwTypeData);
//else
LOG(L"dwTypeData : %d (Ox%08lx)\n", mif->dwTypeData, mif->dwTypeData);
LOG(L"cch : %d\n", mif->cch);
}
inline CString NmFlagsString(DWORD f)
{
CString b = "";
if (f == SHNN_LINKSEL ) b = L"SHNN_LINKSEL";
if (f == SHNN_DISMISS ) b = L"SHNN_DISMISS";
if (f == SHNN_SHOW ) b = L"SHNN_SHOW";
if (f == SHNN_NAVPREV ) b = L"SHNN_NAVPREV";
if (f == SHNN_NAVNEXT ) b = L"SHNN_NAVNEXT";
if (f == SHNN_ACTIVATE ) b = L"SHNN_ACTIVATE";
if (f == SHNN_ICONCLICKED ) b = L"SHNN_ICONCLICKED";
if (f == SHNN_HOTKEY ) b = L"SHNN_HOTKEY";
return b;
}
inline void DUMP_NMSHN(NMSHN* nm)
{
LOG(L"\n\n");
LOG(L"hdr.dwID : %08lx\n", nm->hdr.idFrom);
LOG(L"hdr.hwndFrom : %08lx\n", nm->hdr.hwndFrom);
LOG(L"hdr.code : %s\n", NmFlagsString(nm->hdr.code));
LOG(L"lParam : %08lx\n", nm->lParam);
if (nm->hdr.code == SHNN_LINKSEL)
{
LOG(L"dwReturn : %08lx\n", nm->dwReturn);
LOG(L"pszLink : %ls\n", nm->pszLink);
}
if (nm->hdr.code == SHNN_DISMISS)
LOG(L"fTimeout : %s\n", (nm->fTimeout == FALSE) ? L"FALSE" : L"TRUE");
if (nm->hdr.code == SHNN_SHOW)
LOG(L"pt : (%d,%d)\n", nm->pt.x, nm->pt.y);
LOG(L"\n\n");
}
inline CString ShnFlagsString(DWORD f)
{
CSimpleArray<CString> l;
if (f&SHNF_STRAIGHTTOTRAY) l.Add(L"SHNF_STRAIGHTTOTRAY");
if (f&SHNF_CRITICAL ) l.Add(L"SHNF_CRITICAL");
if (f&SHNF_FORCEMESSAGE ) l.Add(L"SHNF_FORCEMESSAGE");
if (f&SHNF_DISPLAYON ) l.Add(L"SHNF_DISPLAYON");
if (f&SHNF_SILENT ) l.Add(L"SHNF_SILENT");
if (f&SHNF_HASMENU ) l.Add(L"SHNF_HASMENU");
if (f&SHNF_TITLETIME ) l.Add(L"SHNF_TITLETIME");
if (f&SHNF_SPINNERS ) l.Add(L"SHNF_SPINNERS");
if (f&SHNF_ALERTONUPDATE ) l.Add(L"SHNF_ALERTONUPDATE");
if (f&SHNF_WANTVKTTALK ) l.Add(L"SHNF_WANTVKTTALK");
DWORD all=SHNF_STRAIGHTTOTRAY|SHNF_CRITICAL|SHNF_FORCEMESSAGE|SHNF_DISPLAYON|SHNF_SILENT|SHNF_HASMENU|SHNF_TITLETIME|SHNF_SPINNERS|SHNF_ALERTONUPDATE|SHNF_WANTVKTTALK;
if (f&~all) {
CString a; a.Format(L"SHNFLAG_%08lx", f&~all);
l.Add(a);
}
CString b;
for (int i = 0; i < l.GetSize(); i++)
b += l[i] + L",";
return b;
}
inline CString SkFlagsString(DWORD f)
{
CSimpleArray<CString> l;
if (f & NOTIF_SOFTKEY_FLAGS_DISMISS) l.Add(L"NOTIF_SOFTKEY_FLAGS_DISMISS");
if (f & NOTIF_SOFTKEY_FLAGS_HIDE) l.Add(L"NOTIF_SOFTKEY_FLAGS_HIDE");
if (f & NOTIF_SOFTKEY_FLAGS_STAYOPEN) l.Add(L"NOTIF_SOFTKEY_FLAGS_STAYOPEN");
if (f & NOTIF_SOFTKEY_FLAGS_SUBMIT_FORM) l.Add(L"NOTIF_SOFTKEY_FLAGS_SUBMIT_FORM");
if (f & NOTIF_SOFTKEY_FLAGS_DISABLED) l.Add(L"NOTIF_SOFTKEY_FLAGS_DISABLED");
CString b;
for (int i = 0; i < l.GetSize(); i++)
b += l[i] + L",";
return b;
}
inline void DUMP_SHN(SHNOTIFICATIONDATA* shn)
{
LOG(L"\n\n");
if (shn->cbStruct!=sizeof(*shn))
LOG(L"NOTE: structsize = 0x%x ( expected 0x%x )\n", shn->cbStruct, sizeof(*shn));
LOG(L"dwId : %08lx\n", shn->dwID);
LOG(L"npPriority: %s\n", shn->npPriority==SHNP_INFORM ? L"INFORM" : shn->npPriority==SHNP_ICONIC ? L"ICONIC" : L"<unknown>");
LOG(L"csDuration: %d\n", shn->csDuration);
LOG(L"hicon : %08lx\n", shn->hicon);
LOG(L"grfFlags : %s\n", ShnFlagsString(shn->grfFlags));
LOG(L"clsid : %08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x\n",
shn->clsid.Data1, shn->clsid.Data2, shn->clsid.Data3,
shn->clsid.Data4[0], shn->clsid.Data4[1], shn->clsid.Data4[2], shn->clsid.Data4[3], shn->clsid.Data4[4], shn->clsid.Data4[5], shn->clsid.Data4[6], shn->clsid.Data4[7]);
LOG(L"hwndSink : %08lx\n", shn->hwndSink);
LOG(L"pszHTML : %s\n", shn->pszHTML);
LOG(L"pszTitle : %s\n", shn->pszTitle);
LOG(L"lParam : %08lx\n", shn->lParam);
if (shn->grfFlags & SHNF_HASMENU) {
LOG(L"skm : \n");
LOG(L" hMenu : %08lx\n", shn->skm.hMenu);
LOG(L" cskc : %d\n", shn->skm.cskc);
for (DWORD i=0 ; i<shn->skm.cskc ; i++)
LOG(L" prgskc[%2d] : %d %s\n", i, shn->skm.prgskc[i].wpCmd, SkFlagsString(shn->skm.prgskc[i].grfFlags));
int i = 0;
MENUITEMINFO mii;
WCHAR szLabel[256];
while (1)
{
ZeroMemory(&mii, sizeof(MENUITEMINFO));
mii.cbSize = sizeof(MENUITEMINFO);
mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE | MIIM_FULLSTR;
mii.dwTypeData = (LPTSTR)szLabel;
mii.cch = 256;
if (GetMenuItemInfo(shn->skm.hMenu, i, TRUE, &mii))
{
LOG(L"----- menuiteminfo------\n");
DUMP_MENUITEMINFO(&mii);
LOG(L"------------------------\n");
if (mii.hSubMenu)
{
int j = 0;
MENUITEMINFO mii2;
WCHAR szLabel2[256];
while (1)
{
ZeroMemory(&mii2, sizeof(MENUITEMINFO));
mii2.cbSize = sizeof(MENUITEMINFO);
mii2.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE | MIIM_FULLSTR;
mii2.dwTypeData = (LPTSTR)szLabel2;
mii2.cch = 256;
if (GetMenuItemInfo(mii.hSubMenu, j, TRUE, &mii2))
{
LOG(L"----- sub menuiteminfo------\n");
DUMP_MENUITEMINFO(&mii2);
LOG(L"----------------------------\n");
}
else
break;
j++;
}
}
}
else
break;
i++;
}
}
else
{
for (int i=0 ; i<2 ; i++) {
LOG(L"rgskn%d : \n", i);
LOG(L" pszTitle : %s\n", shn->rgskn[i].pszTitle);
LOG(L" wpCmd : %d\n", shn->rgskn[i].skc.wpCmd);
LOG(L" grfFlags : %s\n", SkFlagsString(shn->rgskn[i].skc.grfFlags));
}
}
LOG(L"pszTodaySK: %ls\n", shn->pszTodaySK);
LOG(L"pszTodayExec: %ls\n", shn->pszTodayExec);
}
//#ifdef __cplusplus
//}
//#endif
#endif // LOGGER_H<file_sep>/FingerSuite/Common/atlceplus.h
#ifndef __ATLCEPLUS_H__
#define __ATLCEPLUS_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error atlceplus.h requires atlapp.h to be included first
#endif
/////////////////////////////////////////////////////////////////////////////
// Classes in this file
//
// CCompression
// CFindFile
// CFindProjectFile
// CFindFlashCard
//
/////////////////////////////////////////////////////////////////////////////
// CCompression - undocumented COREDLL compression methods
class CCompression
{
public:
DWORD Compress(LPBYTE bufin, DWORD lenin, LPBYTE bufout, DWORD lenout)
{
typedef DWORD (WINAPI *PFNBINARYCOMPRESS)(LPBYTE, DWORD, LPBYTE, DWORD);
PFNBINARYCOMPRESS lpf =
(PFNBINARYCOMPRESS) ::GetProcAddress(::GetModuleHandle(_T("COREDLL.DLL")), _T("BinaryCompress"));
if( lpf == NULL ) return 0;
return lpf(bufin, lenin, bufout, lenout);
}
DWORD Decompress(LPBYTE bufin, DWORD lenin, LPBYTE bufout, DWORD lenout, DWORD skip = 0)
{
typedef DWORD (WINAPI *PFNBINARYDECOMPRESS)(LPBYTE, DWORD, LPBYTE, DWORD, DWORD);
PFNBINARYDECOMPRESS lpf =
(PFNBINARYDECOMPRESS) ::GetProcAddress(::GetModuleHandle(_T("COREDLL.DLL")), _T("BinaryDecompress"));
if( lpf == NULL ) return 0;
return lpf(bufin, lenin, bufout, lenout, skip);
}
};
/////////////////////////////////////////////////////////////////////////////
// CFindFile - file search helper class
#include <projects.h>
#pragma comment(lib, "note_prj.lib")
class ATL_NO_VTABLE CFindFileBase
{
public:
// Data members
WIN32_FIND_DATA m_fd;
TCHAR m_lpszRoot[MAX_PATH];
TCHAR m_chDirSeparator;
HANDLE m_hFind;
BOOL m_bFound;
// Constructor/destructor
CFindFileBase() : m_hFind(NULL), m_chDirSeparator('\\'), m_bFound(FALSE)
{
}
~CFindFileBase()
{
Close();
}
// Operations
void Close()
{
m_bFound = FALSE;
if( m_hFind != NULL && m_hFind != INVALID_HANDLE_VALUE ) {
::FindClose(m_hFind);
m_hFind = NULL;
}
}
// Attributes
ULONGLONG GetFileSize() const
{
ATLASSERT(m_hFind!=NULL);
ULARGE_INTEGER nFileSize;
if( m_bFound ) {
nFileSize.LowPart = m_fd.nFileSizeLow;
nFileSize.HighPart = m_fd.nFileSizeHigh;
}
else {
nFileSize.QuadPart = 0;
}
return nFileSize.QuadPart;
}
BOOL GetFileName(LPTSTR lpstrFileName, int cchLength) const
{
ATLASSERT(m_hFind!=NULL);
if( (int) lstrlen(m_fd.cFileName) >= cchLength ) return FALSE;
return (m_bFound && (::lstrcpy(lpstrFileName, m_fd.cFileName) != NULL));
}
BOOL GetFilePath(LPTSTR lpstrFilePath, int cchLength) const
{
ATLASSERT(m_hFind!=NULL);
int nLen = lstrlen(m_lpszRoot);
ATLASSERT(nLen > 0);
if( nLen == 0 ) return FALSE;
bool bAddSep = (m_lpszRoot[nLen - 1] != '\\' && m_lpszRoot[nLen - 1] != '/');
if( ((int) lstrlen(m_lpszRoot) + (bAddSep ? 1 : 0)) >= cchLength ) return FALSE;
BOOL bRet = (::lstrcpy(lpstrFilePath, m_lpszRoot) != NULL);
if( bRet ) {
TCHAR szSeparator[2] = { m_chDirSeparator, 0 };
bRet = (::lstrcat(lpstrFilePath, szSeparator) != NULL);
if( bRet ) bRet = (::lstrcat(lpstrFilePath, m_fd.cFileName) != NULL);
}
return bRet;
}
BOOL GetRoot(LPTSTR lpstrRoot, int cchLength) const
{
ATLASSERT(m_hFind!=NULL);
if( (int) lstrlen(m_lpszRoot) >= cchLength ) return FALSE;
return (::lstrcpy(lpstrRoot, m_lpszRoot) != NULL);
}
#if defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
CString GetFileName() const
{
ATLASSERT(m_hFind!=NULL);
CString ret;
if( m_bFound ) ret = m_fd.cFileName;
return ret;
}
CString GetFilePath() const
{
ATLASSERT(m_hFind!=NULL);
CString strResult = m_lpszRoot;
if( strResult[strResult.GetLength() - 1] != '\\' &&
strResult[strResult.GetLength() - 1] != '/' )
strResult += m_chDirSeparator;
strResult += GetFileName();
return strResult;
}
CString GetRoot() const
{
ATLASSERT(m_hFind!=NULL);
return m_lpszRoot;
}
#endif //defined(_WTL_USE_CSTRING) || defined(__ATLSTR_H__)
BOOL GetLastWriteTime(FILETIME* pTimeStamp) const
{
ATLASSERT(m_hFind!=NULL);
ATLASSERT(pTimeStamp != NULL);
if( m_bFound && pTimeStamp != NULL ) {
*pTimeStamp = m_fd.ftLastWriteTime;
return TRUE;
}
return FALSE;
}
BOOL GetLastAccessTime(FILETIME* pTimeStamp) const
{
ATLASSERT(m_hFind!=NULL);
ATLASSERT(pTimeStamp != NULL);
if( m_bFound && pTimeStamp != NULL ) {
*pTimeStamp = m_fd.ftLastAccessTime;
return TRUE;
}
return FALSE;
}
BOOL GetCreationTime(FILETIME* pTimeStamp) const
{
ATLASSERT(m_hFind!=NULL);
if( m_bFound && pTimeStamp != NULL ) {
*pTimeStamp = m_fd.ftCreationTime;
return TRUE;
}
return FALSE;
}
BOOL MatchesMask(DWORD dwMask) const
{
ATLASSERT(m_hFind!=NULL);
if( m_bFound ) return ((m_fd.dwFileAttributes & dwMask) != 0);
return FALSE;
}
BOOL IsDots() const
{
ATLASSERT(m_hFind!=NULL);
// return TRUE if the file name is "." or ".." and
// the file is a directory
BOOL bResult = FALSE;
if( m_bFound && IsDirectory() ) {
if( m_fd.cFileName[0] == '.'
&& (m_fd.cFileName[1] == '\0'
|| (m_fd.cFileName[1] == '.' && m_fd.cFileName[2] == '\0')) )
{
bResult = TRUE;
}
}
return bResult;
}
BOOL IsReadOnly() const
{
return MatchesMask(FILE_ATTRIBUTE_READONLY);
}
BOOL IsDirectory() const
{
return MatchesMask(FILE_ATTRIBUTE_DIRECTORY);
}
BOOL IsCompressed() const
{
return MatchesMask(FILE_ATTRIBUTE_COMPRESSED);
}
BOOL IsSystem() const
{
return MatchesMask(FILE_ATTRIBUTE_SYSTEM);
}
BOOL IsHidden() const
{
return MatchesMask(FILE_ATTRIBUTE_HIDDEN);
}
BOOL IsTemporary() const
{
return MatchesMask(FILE_ATTRIBUTE_TEMPORARY);
}
BOOL IsNormal() const
{
return MatchesMask(FILE_ATTRIBUTE_NORMAL);
}
BOOL IsArchived() const
{
return MatchesMask(FILE_ATTRIBUTE_ARCHIVE);
}
};
class CFindFile : public CFindFileBase
{
public:
// Operations
BOOL FindFile(LPCTSTR pstrPattern = NULL)
{
Close();
if( pstrPattern == NULL ) pstrPattern = _T("*.*");
::lstrcpy(m_fd.cFileName, pstrPattern);
m_hFind = ::FindFirstFile(pstrPattern, &m_fd);
if( m_hFind == INVALID_HANDLE_VALUE ) return FALSE;
::ZeroMemory(m_lpszRoot, sizeof(m_lpszRoot));
m_lpszRoot[0] = m_chDirSeparator;
LPCTSTR pstr = NULL;
LPCTSTR p = pstrPattern;
while( *p ) {
if( *p == m_chDirSeparator ) pstr = p;
p = ::CharNext(p);
}
if( pstr ) ::lstrcpyn(m_lpszRoot, pstrPattern, pstr - pstrPattern + 1);
m_bFound = TRUE;
return TRUE;
}
BOOL FindNextFile()
{
ATLASSERT(m_hFind!=NULL);
if( m_hFind == NULL ) return FALSE;
if( !m_bFound ) return FALSE;
m_bFound = ::FindNextFile(m_hFind, &m_fd);
return m_bFound;
}
};
class CFindProjectFile : public CFindFileBase
{
public:
// Operations
BOOL FindFile(LPCTSTR pstrPattern = NULL, DWORD dwOidFlash = 0, LPTSTR lpszProj = NULL)
{
Close();
if( pstrPattern == NULL ) pstrPattern = _T("*.*");
::lstrcpy(m_fd.cFileName, pstrPattern);
m_hFind = ::FindFirstProjectFile(pstrPattern, &m_fd, dwOidFlash, lpszProj);
if( m_hFind == INVALID_HANDLE_VALUE ) return FALSE;
::ZeroMemory(m_lpszRoot, sizeof(m_lpszRoot));
LPCTSTR pstr = NULL;
LPCTSTR p = pstrPattern;
while( *p ) {
if( *p == m_chDirSeparator ) pstr = p;
p = ::CharNext(p);
}
if( pstr ) ::lstrcpyn(m_lpszRoot, pstrPattern, pstr - pstrPattern); else ::lstrcpy(m_lpszRoot, _T("\\"));
m_bFound = TRUE;
return TRUE;
}
BOOL FindNextFile()
{
ATLASSERT(m_hFind!=NULL);
if( m_hFind == NULL ) return FALSE;
if( !m_bFound ) return FALSE;
m_bFound = ::FindNextProjectFile(m_hFind, &m_fd);
return m_bFound;
}
};
class CFindFlashCard : public CFindFileBase
{
public:
// Operations
BOOL FindFile()
{
Close();
m_hFind = ::FindFirstFlashCard(&m_fd);
if( m_hFind == INVALID_HANDLE_VALUE ) return FALSE;
::ZeroMemory(m_lpszRoot, sizeof(m_lpszRoot));
m_lpszRoot[0] = m_chDirSeparator;
m_bFound = TRUE;
return TRUE;
}
BOOL FindNextFile()
{
ATLASSERT(m_hFind!=NULL);
if( m_hFind == NULL ) return FALSE;
if( !m_bFound ) return FALSE;
m_bFound = ::FindNextFlashCard(m_hFind, &m_fd);
return m_bFound;
}
};
#endif // __ATLCEPLUS_H__
<file_sep>/SQLCEHelper/Source/DataSource.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
// CDataSource::CDataSource
//
// Default constructor
//
CDataSource::CDataSource()
: m_pInitialize(NULL)
{
}
// CDataSource::~CDataSource
//
// Destructor
//
CDataSource::~CDataSource()
{
Close();
}
// CDataSource::Open
//
// Opens an existing data source
//
HRESULT CDataSource::Open(const CLSID &clsid, ULONG cPropSets, DBPROPSET rgPropSets[])
{
HRESULT hr;
Close();
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IDBInitialize, (LPVOID*)&m_pInitialize);
if(SUCCEEDED(hr))
{
CComPtr<IDBProperties> spProperties;
hr = m_pInitialize->QueryInterface(IID_IDBProperties, (void**)&spProperties);
if(SUCCEEDED(hr))
{
hr = spProperties->SetProperties(cPropSets, rgPropSets);
if(SUCCEEDED(hr))
hr = m_pInitialize->Initialize();
}
}
return hr;
}
// CDataSource::Create
//
// Creates a new data source and optionally returns an open session
//
HRESULT CDataSource::Create(const CLSID& clsid, ULONG cPropSets, DBPROPSET rgPropSets[], CSession* pSession)
{
HRESULT hr;
CComPtr<IDBDataSourceAdmin> spAdmin;
Close();
hr = CoCreateInstance(clsid, NULL, CLSCTX_INPROC_SERVER, IID_IDBDataSourceAdmin, (void**)&spAdmin);
if(FAILED(hr))
return hr;
if(pSession != NULL)
{
ISessionProperties* pSessionProperties = NULL;
hr = spAdmin->CreateDataSource(cPropSets, rgPropSets, NULL, IID_ISessionProperties, (IUnknown**)&pSessionProperties);
if(SUCCEEDED(hr))
pSession->Open(pSessionProperties);
}
else
hr = spAdmin->CreateDataSource(cPropSets, rgPropSets, NULL, IID_IUnknown, NULL);
// Get the IDBInitialize pointer in order to keep the data source "open"
if(SUCCEEDED(hr))
spAdmin->QueryInterface(IID_IDBInitialize, (void**)&m_pInitialize);
return hr;
}
// CDataSource::Close
//
// Closes the data source
//
HRESULT CDataSource::Close()
{
HRESULT hr = E_NOINTERFACE;
if(m_pInitialize != NULL)
{
hr = m_pInitialize->Uninitialize();
if(SUCCEEDED(hr))
m_pInitialize->Release();
}
return hr;
}
<file_sep>/FingerSuite/FingerMenuCTRL/MainFrm.h
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
//DEFINE_GUID(CLSID_ImagingFactory, 0x327abda8,0x072b,0x11d3,0x9d,0x7b,0x00,0x00,0xf8,0x1e,0xf3,0x2e);
#include "..\Common\AboutView.h"
#include "..\FingerSuiteCPL\Commons.h"
#include "..\Common\fngrsplash.h"
typedef enum {SQVGA = 240, QVGA = 320, WQVGA = 400, VGA = 640, WVGA = 800} RESOLUTION;
static UINT UWM_INTERCEPT_MENU = ::RegisterWindowMessage(UWM_INTERCEPT_MENU_MSG);
static UINT UWM_UPDATECONFIGURATION = ::RegisterWindowMessage(UWM_UPDATECONFIGURATION_MSG);
class CMainFrame : public CFrameWindowImpl<CMainFrame>, public CUpdateUI<CMainFrame>,
public CMessageFilter, public CIdleHandler
{
public:
DECLARE_FRAME_WND_CLASS(L"FINGER_MENU", IDR_MAINFRAME)
CWrapMenuWindow m_menuView;
CAboutView m_aboutView;
virtual BOOL PreTranslateMessage(MSG* pMsg)
{
if(CFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg))
return TRUE;
if (pMsg->message == WM_LBUTTONDOWN)
{
m_xPos = LOWORD(pMsg->lParam);
m_bMouseIsDown = TRUE;
}
if (pMsg->message == WM_LBUTTONUP)
{
// back gesture recognition
if (m_bMouseIsDown)
{
m_bMouseIsDown = FALSE;
int xPosNew = LOWORD(pMsg->lParam);
if ((m_xPos - xPosNew) > 100 * m_menuView.GetScaleFactor())
{
// back gesture recognized
Back();
return TRUE;
}
}
}
return m_menuView.PreTranslateMessage(pMsg);
}
virtual BOOL OnIdle()
{
return FALSE;
}
BEGIN_UPDATE_UI_MAP(CMainFrame)
END_UPDATE_UI_MAP()
BEGIN_MSG_MAP(CMainFrame)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
MESSAGE_HANDLER(WM_SETTINGCHANGE , OnSettingsChange)
MESSAGE_HANDLER(UM_MINIMIZE, OnMinimize)
MESSAGE_HANDLER(UWM_INTERCEPT_MENU, OnInterceptMenu)
MESSAGE_HANDLER(UWM_UPDATECONFIGURATION, OnUpdateConfiguration)
MESSAGE_HANDLER(UM_SETNEWMENU, OnSetNewMenu)
MESSAGE_HANDLER(UM_GETDESTWND, OnGetDestWnd)
COMMAND_ID_HANDLER(ID_MENU_CANCEL, OnCancel)
COMMAND_ID_HANDLER(ID_ACTION, OnAction)
COMMAND_ID_HANDLER(ID_MENU_EXIT, OnMenuExit)
COMMAND_ID_HANDLER(ID_MENU_ADDTOEXCLUSIONLIST, OnMenuAddToExclusionList)
COMMAND_ID_HANDLER(ID_MENU_ADDTOWNDEXCLUSIONLIST, OnMenuAddToWndExclusionList)
COMMAND_ID_HANDLER(ID_MENU_SHOWORIGINAL, OnMenuShowOriginal)
COMMAND_ID_HANDLER(ID_MENU_ABOUT, OnMenuAbout)
COMMAND_ID_HANDLER(ID_BACK, OnBack)
CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
CHAIN_MSG_MAP(CFrameWindowImpl<CMainFrame>)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
RestoreMenuBar();
CSplashWindow* pSplash = new CSplashWindow(m_hWnd, IDR_MAINFRAME, L"FingerMenu");
LoadConfiguration();
// menu
m_hWndClient = m_menuView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE |WS_CLIPSIBLINGS | WS_CLIPCHILDREN); //
// about
CString strCredits = "\n\n"
"\tFingerMenu v1.12\n\n"
"\rdeveloped by:\n"
"<NAME>\n"
"<<EMAIL>>\n"
"\n\n"
"http://forum.xda-developers.com/\n"
" showthread.php?t=459125\n";
m_aboutView.SetCredits(strCredits);
m_aboutView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE |WS_CLIPSIBLINGS | WS_CLIPCHILDREN); //
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
CreateConfigMenu();
if (m_bEnableSIP)
InstallHookOnSIP();
SetHWndServer(m_hWnd);
InstallHook();
SignalWaitEvent(EVT_FNGRMENU);
ModifyStyle(0, WS_NONAVDONEBUTTON, SWP_NOSIZE);
pSplash->Dismiss();
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
}
return 0;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//RemoveHook(); TODO
return 0;
}
LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CDCHandle dc( (HDC) wParam );
RECT rc; GetClientRect(&rc);
if (m_bDisabledTransp)
{
dc.FillSolidRect(&rc, m_clNoTranspBackground);
}
else
{
if (!(m_imgBkg.IsValid()))
CaptureScreen(dc);
m_imgBkg.Draw(dc, rc);
}
return 1;
}
LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
int fActive = LOWORD(wParam);
if ((fActive == WA_ACTIVE) || (fActive == WA_CLICKACTIVE))
{
}
else if (fActive == WA_INACTIVE)
{
if (IsWindowVisible())
{
Minimize(FALSE);
}
}
return 0;
}
LRESULT OnSettingsChange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if (wParam == SETTINGCHANGE_RESET)
{
m_menuView.ModifyTopShape();
m_menuView.Show();
}
return 0;
}
LRESULT OnGetDestWnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return (LRESULT)m_hDestWnd;
}
LRESULT OnSetNewMenu(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// always called for sub menu
CreateBackMenuBar();
SetNewMenu((HMENU)wParam);
return 0;
}
LRESULT OnMinimize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
Minimize((int)wParam);
return 0;
}
LRESULT OnCancel(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
Minimize(FALSE);
return 0;
}
/*
LRESULT OnInterceptMenu1(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LOG(L"Intercepting TrackMenuPopupEx (1) ...hMenu=%08x hWnd=%08X\n", (HMENU)wParam, (HWND)lParam);
if (IsDeviceLocked())
return 1;
HWND hDestWnd = (HWND)lParam;
HWND hWndSIP = FindWindow(NULL, L"MS_SIPBUTTON");
if (hDestWnd == hWndSIP)
{
if (m_bEnableSIP)
m_menuView.SetNewMenu((HMENU)wParam, NULL, NULL, FALSE);
else
return 1;
}
else
{
if (IsExcludedApp(hDestWnd))
return 1;
HWND hDestCtrl = ManageDOTNETApp(hDestWnd);
if (!(m_menuView.SetNewMenu((HMENU)wParam, hDestWnd, hDestCtrl, TRUE)))
return 1;
}
//Sleep(100);
RestoreMenuBar();
SwitchToMenuView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
bHandled = TRUE;
return 0;
}
*/
LRESULT OnInterceptMenu(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
//LOG(L"Intercepting TrackMenuPopupEx (2)...hMenu=%08x hWnd=%08X\n", (HMENU)wParam, (HWND)lParam);
if (IsDeviceLocked())
return 1;
LPTRACKPOPUPMENUINFO lpInfo = (LPTRACKPOPUPMENUINFO)lParam;
m_hPrevDestWnd = m_hDestWnd;
m_hDestWnd = lpInfo->hWnd;
m_uFlags = lpInfo->uFlags;
HWND hWndSIP = FindWindow(NULL, L"MS_SIPBUTTON");
if (m_hDestWnd == hWndSIP)
{
if (!(m_bEnableSIP))
return 1;
}
else
{
if (IsExcludedApp(m_hDestWnd))
return 1;
if (IsExcludedWnd(m_hDestWnd))
return 1;
}
m_menus.RemoveAll();
if (!(SetNewMenu(lpInfo->hMenu)))
return 1;
RestoreMenuBar();
SwitchToMenuView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
bHandled = TRUE;
return 0;
}
LRESULT OnAction(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
m_hPrevDestWnd = m_hDestWnd;
m_hDestWnd = m_hWnd;
SetNewMenu(m_menuConfig);
SwitchToMenuView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
return 0;
}
LRESULT OnBack(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
Back();
return 0;
}
LRESULT OnMenuExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
Minimize(FALSE);
PostMessage(WM_CLOSE);
return 0;
}
LRESULT OnMenuAddToExclusionList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
DWORD dwProcessId; GetWindowThreadProcessId(m_hPrevDestWnd, &dwProcessId);
HMODULE hProcess = (HMODULE)dwProcessId;
WCHAR szName[MAX_PATH];
if (GetModuleFileName(hProcess, szName, MAX_PATH))
{
CString szApp = (LPTSTR)szName;
szApp = szApp.Right(szApp.GetLength() - szApp.ReverseFind('\\') - 1);
if (m_excludedApps.Find(szApp) == -1)
m_excludedApps.Add(szApp);
SaveExclusionList(m_excludedApps, L"Software\\FingerMenu");
}
Minimize(-1);
return 0;
}
LRESULT OnMenuAddToWndExclusionList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
WCHAR szTitle[MAX_PATH];
::GetWindowText(m_hPrevDestWnd, szTitle, MAX_PATH);
WCHAR szClassName[MAX_PATH];
::GetClassName(m_hPrevDestWnd, szClassName, MAX_PATH);
if (lstrcmp(szClassName, L"MS_SOFTKEY_CE_1.0") == 0)
{
Minimize(FALSE);
return 0;
}
WCHAR szName[MAX_PATH];
wsprintf(szName, L"%s - %s", szTitle, szClassName);
CString szWnd = (LPTSTR)szName;
if (m_excludedWnds.Find(szWnd) == -1)
m_excludedWnds.Add(szWnd);
SaveWndExclusionList(m_excludedWnds, L"Software\\FingerMenu");
Minimize(-1);
return 0;
}
LRESULT OnMenuShowOriginal(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
Minimize(-1);
return 0;
}
LRESULT OnMenuAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
SwitchToAboutView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
return 0;
}
LRESULT OnUpdateConfiguration(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
LoadConfiguration();
Minimize(FALSE);
return 0;
}
private:
BOOL RestoreMenuBar()
{
SHMENUBARINFO mbi = { 0 };
mbi.cbSize = sizeof(mbi);
mbi.hwndParent = m_hWnd;
mbi.dwFlags = SHCMBF_HIDESIPBUTTON;
mbi.nToolBarId = FM_IDW_MENU_BAR;
mbi.hInstRes = ModuleHelper::GetResourceInstance();
mbi.hwndMB = NULL; // This gets set by SHCreateMenuBar
BOOL bRet = ::SHCreateMenuBar(&mbi);
if (bRet != FALSE)
{
m_hWndCECommandBar = mbi.hwndMB;
SizeToMenuBar();
}
return bRet;
}
BOOL CreateBackMenuBar()
{
SHMENUBARINFO mbi = { 0 };
mbi.cbSize = sizeof(mbi);
mbi.hwndParent = m_hWnd;
mbi.dwFlags = SHCMBF_HIDESIPBUTTON;
mbi.nToolBarId = FM_IDW_BACK_MENU_BAR;
mbi.hInstRes = ModuleHelper::GetResourceInstance();
mbi.hwndMB = NULL; // This gets set by SHCreateMenuBar
BOOL bRet = ::SHCreateMenuBar(&mbi);
if( bRet != FALSE)
{
m_hWndCECommandBar = mbi.hwndMB;
SizeToMenuBar();
}
return TRUE;
}
void Minimize(int iResult)
{
// check if service menu
if ((m_hWnd == m_hDestWnd) && (iResult > 0))
{
// service menu
PostMessage(WM_COMMAND, (WPARAM)iResult);
return;
}
ShowWindow(SW_HIDE);
SetTrackPopupMenuExResult(iResult);
SignalWaitEvent(EVT_FNGRMENU);
if ((!(m_uFlags & TPM_RETURNCMD)) && (iResult > 0) && (m_hWnd != m_hDestWnd))
::PostMessage(m_hDestWnd, WM_COMMAND, (WPARAM)iResult, (LPARAM)0);
}
HWND ManageDOTNETApp(HWND& hDestWnd)
{
HWND hDestCtrl = NULL;
WCHAR szClass[50];
::GetClassName(hDestWnd, szClass, 50);
if (lstrcmpi(szClass, L"MS_SOFTKEY_CE_1.0") == 0)
{
DWORD dwProcessId; GetWindowThreadProcessId(hDestWnd, &dwProcessId);
HWND hDotNETWnd = ::FindWindow(L"#NETCF_AGL_BASE_", NULL);
if (hDotNETWnd != NULL)
{
DWORD dwProcess2Id; GetWindowThreadProcessId(hDotNETWnd, &dwProcess2Id);
if (dwProcess2Id == dwProcessId)
{
hDestCtrl = hDestWnd;
hDestWnd = hDotNETWnd;
}
}
}
return hDestCtrl;
}
BOOL IsExcludedApp(HWND hWnd)
{
DWORD dwProcessId; GetWindowThreadProcessId(hWnd, &dwProcessId);
HMODULE hProcess = (HMODULE)dwProcessId;
// execute GetCommandLine() on remote process
WCHAR szName[MAX_PATH];
if (GetModuleFileName(hProcess, szName, MAX_PATH))
{
CString szApp = (LPTSTR)szName;
szApp = szApp.Right(szApp.GetLength() - szApp.ReverseFind('\\') - 1);
for (int i = 0; i < m_excludedApps.GetSize(); i ++)
{
if (m_excludedApps[i].CompareNoCase( szApp ) == 0)
return TRUE;
}
}
return FALSE;
}
BOOL IsExcludedWnd(HWND hWnd)
{
WCHAR szTitle[MAX_PATH];
::GetWindowText(hWnd, szTitle, MAX_PATH);
WCHAR szClassName[MAX_PATH];
::GetClassName(hWnd, szClassName, MAX_PATH);
WCHAR szName[MAX_PATH];
wsprintf(szName, L"%s - %s", szTitle, szClassName);
CString szWnd = (LPTSTR)szName;
for (int i = 0; i < m_excludedWnds.GetSize(); i ++)
{
if (m_excludedWnds[i].CompareNoCase( szWnd ) == 0)
return TRUE;
}
return FALSE;
}
void CaptureScreen(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
CDC dcTemp; dcTemp.CreateCompatibleDC(dc);
CBitmap bmpBkg; bmpBkg.CreateCompatibleBitmap(dc, rc.right, rc.bottom);
CBitmap bmpOld = dcTemp.SelectBitmap(bmpBkg);
dcTemp.FillSolidRect(&rc, RGB(0,0,0));
dcTemp.SelectBitmap(bmpOld);
m_imgBkg.CreateFromHBITMAP(bmpBkg);
m_imgBkg.AlphaCreate();
m_imgBkg.AlphaSet((BYTE)m_iTransp);
}
void LoadConfiguration()
{
WCHAR keyName[] = L"Software\\FingerMenu";
// load transparency level
m_iTransp = 128;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"TransparencyLevel", m_iTransp)))
LOG(L"Unable to read TransparencyLevel from registry: %s\n", ErrorString(GetLastError()));
m_bEnableSIP = TRUE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"EnableSIP", m_bEnableSIP)))
LOG(L"Unable to read EnableSIP from registry: %s\n", ErrorString(GetLastError()));
m_menuView.m_iMaxVisibleItemCount = 0;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"MaxMenuItemCount", m_menuView.m_iMaxVisibleItemCount)))
LOG(L"Unable to read MaxMenuItemCount from registry: %s\n", ErrorString(GetLastError()));
if (m_menuView.m_iMaxVisibleItemCount == 0)
m_menuView.m_iMaxVisibleItemCount = 1000;
DWORD iMaxScrollVelocity = 15;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"MaxScrollVelocity", iMaxScrollVelocity)))
LOG(L"Unable to read MaxScrollVelocity from registry: %s\n", ErrorString(GetLastError()));
m_menuView.m_menu.SetMaxVelocity(iMaxScrollVelocity);
m_bDisabledTransp = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"DisableTransparency", m_bDisabledTransp)))
LOG(L"Unable to read DisableTransparency from registry: %s\n", ErrorString(GetLastError()));
m_clNoTranspBackground = RGB(0,0,0);
RegReadColor(HKEY_LOCAL_MACHINE, keyName, L"NoTranspBkgColor", m_clNoTranspBackground);
//m_bEnableDD = FALSE;
//if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"EnableDirectDraw", m_bEnableDD)))
// LOG(L"Unable to read EnableDirectDraw from registry: %s\n", ErrorString(GetLastError()));
m_menuView.m_bNoButtons = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"NeverShowButtons", m_menuView.m_bNoButtons)))
LOG(L"Unable to read NeverShowButtons from registry: %s\n", ErrorString(GetLastError()));
m_menuView.m_bEnableAnimation = TRUE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"EnableAnimation", m_menuView.m_bEnableAnimation)))
LOG(L"Unable to read EnableAnimation from registry: %s\n", ErrorString(GetLastError()));
// load icon images
WCHAR szSkin[60] = L"default";
RegReadString(HKEY_LOCAL_MACHINE, keyName, L"Skin", szSkin);
WCHAR szAppPath[MAX_PATH] = L"";
CString strAppDirectory;
GetModuleFileName(NULL, szAppPath, MAX_PATH);
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind('\\'));
CString skinBasePath; skinBasePath.Format(L"%s\\skins\\%s", strAppDirectory, szSkin);
// detect resolution
RESOLUTION resolution = QVGA;
DEVMODE dm;
::ZeroMemory(&dm, sizeof(DEVMODE));
dm.dmSize = sizeof(DEVMODE);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm))
{
resolution = (RESOLUTION)dm.dmPelsHeight;
}
switch (resolution)
{
case SQVGA:
case QVGA:
case WQVGA:
m_menuView.SetScaleFactor(1);
break;
case VGA:
case WVGA:
m_menuView.SetScaleFactor(2);
break;
}
if ( (resolution == VGA) || (resolution == WVGA))
{
m_menuView.m_menu.m_imgSubmenuImage.Load(skinBasePath + L"\\submenu_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgCheckedImage.Load(skinBasePath + L"\\checked_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgRadioCheckedImage.Load(skinBasePath + L"\\radio_checked_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgRadioUncheckedImage.Load(skinBasePath + L"\\radio_unchecked_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgSelectionImage.Load(skinBasePath + L"\\selection_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgDPadCursorImage.Load(skinBasePath + L"\\dpad_cursor_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnUp.Load(skinBasePath + L"\\btn_up_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnUpPressed.Load(skinBasePath + L"\\btn_up_press_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnUpDisabled.Load(skinBasePath + L"\\btn_up_disabled_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnDown.Load(skinBasePath + L"\\btn_down_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnDownPressed.Load(skinBasePath + L"\\btn_down_press_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnDownDisabled.Load(skinBasePath + L"\\btn_down_disabled_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnArrowDown.Load(skinBasePath + L"\\btn_arrow_down_vga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnArrowUp.Load(skinBasePath + L"\\btn_arrow_up_vga.png", CXIMAGE_FORMAT_PNG);
}
else
{
m_menuView.m_menu.m_imgSubmenuImage.Load(skinBasePath + L"\\submenu_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgCheckedImage.Load(skinBasePath + L"\\checked_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgRadioCheckedImage.Load(skinBasePath + L"\\radio_checked_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgRadioUncheckedImage.Load(skinBasePath + L"\\radio_unchecked_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgSelectionImage.Load(skinBasePath + L"\\selection_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_menu.m_imgDPadCursorImage.Load(skinBasePath + L"\\dpad_cursor_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnUp.Load(skinBasePath + L"\\btn_up_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnUpPressed.Load(skinBasePath + L"\\btn_up_press_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnUpDisabled.Load(skinBasePath + L"\\btn_up_disabled_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnDown.Load(skinBasePath + L"\\btn_down_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnDownPressed.Load(skinBasePath + L"\\btn_down_press_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnDownDisabled.Load(skinBasePath + L"\\btn_down_disabled_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnArrowDown.Load(skinBasePath + L"\\btn_arrow_down_qvga.png", CXIMAGE_FORMAT_PNG);
m_menuView.m_bmpBtnArrowUp.Load(skinBasePath + L"\\btn_arrow_up_qvga.png", CXIMAGE_FORMAT_PNG);
}
m_menuView.SetItemHeight(m_menuView.m_menu.m_imgSelectionImage.GetHeight());
m_menuView.SetButtonHeight(m_menuView.m_bmpBtnUp.GetHeight());
// load skin settings
CSimpleIniW ini(TRUE, TRUE, TRUE);
SI_Error rc = ini.LoadFile(skinBasePath + L"\\settings_fingermenu.ini");
// load background and selected color
COLORREF clValue = 0;
m_menuView.m_menu.m_clBkg = (StringRGBToColor(ini.GetValue(L"colors", L"BkgColor"), clValue)) ? clValue : RGB(255,255,255);
m_menuView.m_menu.m_clText = (StringRGBToColor(ini.GetValue(L"colors", L"TextColor"), clValue)) ? clValue : RGB(0,0,0);
m_menuView.m_menu.m_clSelText = (StringRGBToColor(ini.GetValue(L"colors", L"SelTextColor"), clValue)) ? clValue : RGB(255,255,255);
m_menuView.m_menu.m_clDisabledText = (StringRGBToColor(ini.GetValue(L"colors", L"DisabledTextColor"), clValue)) ? clValue : RGB(160,160,160);
m_menuView.m_menu.m_clLine = (StringRGBToColor(ini.GetValue(L"colors", L"LineColor"), clValue)) ? clValue : RGB(160,160,160);
m_menuView.m_menu.m_clScrollbar = (StringRGBToColor(ini.GetValue(L"colors", L"ScrollbarColor"), clValue)) ? clValue : RGB(160,160,160);
// font
if (!(m_menuView.m_menu.m_fText.IsNull())) m_menuView.m_menu.m_fText.DeleteObject();
LOGFONT lf;
if (StringToLogFont(ini.GetValue(L"fonts", L"TextFont"), lf))
{
m_menuView.m_menu.m_fText.CreateFontIndirect(&lf);
}
// list of excluded apps
LoadExclusionList(m_excludedApps, L"Software\\FingerMenu");
LoadWndExclusionList(m_excludedWnds, L"Software\\FingerMenu");
}
int Back()
{
if ((m_menus.GetSize() - 2) >= 0)
{
int idx = -1;
HMENU hCurrMenu = m_menuItems[0].hOwnerMenu;
for (int i = 0; i < m_menus.GetSize(); i++)
{
if (m_menus[i].hMenu == hCurrMenu)
{
idx = i;
break;
}
}
if (idx >= 0)
{
if (m_menus[idx].hPrevMenu != NULL)
{
SetNewMenu(m_menus[idx].hPrevMenu);
if (idx == 1)
RestoreMenuBar();
return idx;
}
else
{
PostMessage(WM_COMMAND, ID_MENU_CANCEL, 0);
return 0;
}
}
}
else
{
PostMessage(WM_COMMAND, ID_MENU_CANCEL, 0);
return 0;
}
m_menuView.m_menu.m_idxSelected = -1;
return 0;
}
BOOL SetNewMenu(HMENU hMenu)
{
// menu
LPMENU pMu = NULL;
for (int i = 0; i < m_menus.GetSize(); i++)
{
if (m_menus[i].hMenu == hMenu)
{
pMu = &m_menus[i];
break;
}
}
if (pMu == NULL)
{
MENU m;
m.hMenu = hMenu;
m.bInitMenuSent = FALSE;
m.hPrevMenu = NULL;
m_menus.Add(m);
pMu = &m_menus[m_menus.GetSize() - 1];
}
if ((hMenu == NULL) || (hMenu == 0))
{
m_menuItems.RemoveAll();
return FALSE;
}
// reset
m_menuView.m_menu.m_idxSelected = -1;
m_menuView.m_menu.m_idxDPadSelected = -1;
m_menuItems.RemoveAll();
// let other app initialize menu
if (!pMu->bInitMenuSent)
{
pMu->bInitMenuSent = TRUE;
DWORD dwResult;
SendMessageTimeout(m_hDestWnd, WM_INITMENUPOPUP, (WPARAM)hMenu, 0, SMTO_NORMAL, 500, &dwResult);
SendMessageTimeout(m_hDestWnd, WM_ENTERMENULOOP, (WPARAM)1, 0, SMTO_NORMAL, 500, &dwResult);
}
CMenuHandle menuPopup(hMenu);
int i = 0;
int nBlankCount = 0;
while (1)
{
MENUINFO mi;
ZeroMemory(&mi, sizeof(MENUINFO));
mi.text[0] = ' ';
mi.text[1] = ' ';
mi.hOwnerMenu = hMenu;
mi.mii.cbSize = sizeof(MENUITEMINFO);
mi.mii.fMask = MIIM_CHECKMARKS | MIIM_DATA | MIIM_ID | MIIM_STATE | MIIM_SUBMENU | MIIM_TYPE | MIIM_FULLSTR;
mi.mii.dwTypeData = (LPTSTR)&mi.text[2];
mi.mii.cch = MENU_ITEM_TEXT_SIZE; //sizeof(mi.text);
if (menuPopup.GetMenuItemInfo(i, TRUE, &mi.mii))
{
//DUMP_MENUITEMINFO(&mi.mii);
if (mi.mii.fType & MFT_SEPARATOR)
{
if ((m_menuItems.GetSize() - 1) >= 0)
m_menuItems[m_menuItems.GetSize() - 1].bFollowSeparator = TRUE;
}
else
{
// modifiche al campo text
int j = 0;
WCHAR c;
while ((c = mi.text[j]) != L'\0')
{
if (mi.text[j] == L'\t')
mi.text[j] = L' ';
j++;
}
mi.hDestWnd = m_hDestWnd;
mi.fPosition = i;
if (mi.mii.dwTypeData == NULL)
nBlankCount ++;
if (mi.mii.fType & MFT_OWNERDRAW)
{
MEASUREITEMSTRUCT mis;
ZeroMemory(&mis, sizeof(MEASUREITEMSTRUCT));
mis.CtlType = ODT_MENU;
mis.itemData = i; //mi.mii.dwItemData;
// TODO
//SendMessageRemote(mi.hDestWnd, WM_MEASUREITEM, 0, (LPARAM)&mis, sizeof(MEASUREITEMSTRUCT));
/*
RECT rc; GetClientRect(&rc);
mis.itemWidth = rc.right - rc.left;
mis.itemHeight = m_itemHeight;
LOG(L"SONO QUI\n");
DRAWITEMSTRUCT dis;
ZeroMemory(&dis, sizeof(DRAWITEMSTRUCT));
CDC dc = ::GetDC(NULL);
CDC dcTemp; dcTemp.CreateCompatibleDC(dc);
CBitmap bmp; bmp.CreateCompatibleBitmap(dcTemp, mis.itemWidth, mis.itemHeight);
CBitmap bmpOld = dcTemp.SelectBitmap(bmp);
dcTemp.MoveTo(0,0);
dcTemp.LineTo(mis.itemWidth, mis.itemHeight);
dis.CtlType = ODT_MENU;
dis.itemID = mi.mii.wID;
dis.itemAction = ODA_DRAWENTIRE;
//dis.itemState = ODS_SELECTED; // TODO
dis.hwndItem = (HWND)mi.hOwnerMenu;
dis.hDC = dcTemp;
SetRect(&dis.rcItem, 0, 0, mis.itemWidth, mis.itemHeight);
dis.itemData = mi.mii.dwItemData;
SendMessageRemote(mi.hDestWnd, WM_DRAWITEM, 0, (LPARAM)&dis, sizeof(DRAWITEMSTRUCT));
dcTemp.SelectBitmap(bmpOld);
mi.imgOwnerDraw.CreateFromHBITMAP(bmp);
::ReleaseDC(NULL, dc);
CString fName; fName.Format(L"\\test%d.png", i);
mi.imgOwnerDraw.Save(fName, CXIMAGE_FORMAT_PNG);
LOG(L"SONO QUI 2\n");
*/
}
// save
m_menuItems.Add(mi);
}
}
else
{
//LOG(L"Error in SetMenu: %s\n", ErrorString(GetLastError()));
break;
}
i ++;
}
/*
if ((nBlankCount != 0) &&
(nBlankCount >= (m_menuItems.GetSize() - 1))
)
return FALSE;
*/
// gestione radio button
for (int i = 0; i < m_menuItems.GetSize(); i++)
{
if (m_menuItems[i].mii.fType & MFT_RADIOCHECK)
{
// back
for (int k = i; k >= 0; k--)
{
if (!(m_menuItems[k].bFollowSeparator))
m_menuItems[k].mii.fType |= MFT_RADIOCHECK;
else
break;
}
// forward
for (int k = i; k < m_menuItems.GetSize(); k++)
{
if (!(m_menuItems[k].bFollowSeparator))
m_menuItems[k].mii.fType |= MFT_RADIOCHECK;
else
break;
}
break;
}
}
m_menuView.Show();
return TRUE;
}
public:
static HRESULT ActivatePreviousInstance(HINSTANCE hInstance)
{
const TCHAR* pszMutex = L"FINGERMENUMUTEX";
const TCHAR* pszClass = L"FINGER_MENU";
const DWORD dRetryInterval = 100;
const int iMaxRetries = 25;
for(int i = 0; i < iMaxRetries; ++i)
{
// Don't need ownership of the mutex
HANDLE hMutex = CreateMutex(NULL, FALSE, pszMutex);
DWORD dw = GetLastError();
if(hMutex == NULL)
{
// ERROR_INVALID_HANDLE - A non-mutex object with this name already exists.
HRESULT hr = (dw == ERROR_INVALID_HANDLE) ? E_INVALIDARG : E_FAIL;
return hr;
}
// If the mutex already exists, then there should be another instance running
if(dw == ERROR_ALREADY_EXISTS)
{
// Just needed the error result, in this case, so close the handle.
CloseHandle(hMutex);
// Try to find the other instance, don't need to close HWND's.
// Don't check title in case it is changed by app after init.
HWND hwnd = FindWindow(pszClass, NULL);
if(hwnd == NULL)
{
// It's possible that the other istance is in the process of starting up or shutting down.
// So wait a bit and try again.
Sleep(dRetryInterval);
continue;
}
else
{
// Set the previous instance as the foreground window
// The "| 0x1" in the code below activates the correct owned window
// of the previous instance's main window according to the SmartPhone 2003
// wizard generated code.
if(SetForegroundWindow(reinterpret_cast<HWND>(reinterpret_cast<ULONG>(hwnd) | 0x1)) != 0)
{
// S_FALSE indicates that another instance was activated, so this instance should terminate.
return S_FALSE;
}
}
}
else
{
// This is the first istance, so return S_OK.
// Don't close the mutext handle here.
// Do it on app shutdown instead.
return S_OK;
}
}
// The mutex was created by another instance, but it's window couldn't be brought
// to the foreground, so ssume it's not a invalid instance (not this app, hung, etc.)
// and let this one start.
return S_OK;
}
void CreateConfigMenu()
{
m_menuConfig.CreatePopupMenu();
m_menuConfig.AppendMenuW(MF_STRING, ID_MENU_ADDTOEXCLUSIONLIST, LoadResourceString(IDS_MENU_ADDTOEXCLUSIONLIST)); // L"Add to Exclusion list");
m_menuConfig.AppendMenuW(MF_STRING, ID_MENU_ADDTOWNDEXCLUSIONLIST, LoadResourceString(IDS_MENU_ADDTOWNDEXCLUSIONLIST)); // L"Add to Exclusion list");
m_menuConfig.AppendMenuW(MF_STRING, ID_MENU_SHOWORIGINAL, LoadResourceString(IDS_MENU_SHOWORIGINAL));
m_menuConfig.AppendMenuW(MF_STRING, ID_MENU_ABOUT, LoadResourceString(IDS_MENU_ABOUT));
m_menuConfig.AppendMenuW(MF_STRING, ID_MENU_EXIT, LoadResourceString(IDS_MENU_EXIT));
}
void SwitchToMenuView()
{
m_hWndClient = m_menuView;
m_aboutView.ShowWindow(SW_HIDE);
m_aboutView.SetWindowLongPtr(GWL_ID, 0);
m_menuView.ShowWindow(SW_SHOW);
m_menuView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_menuView.SetFocus();
}
void SwitchToAboutView()
{
m_hWndClient = m_aboutView;
m_menuView.ShowWindow(SW_HIDE);
m_menuView.SetWindowLongPtr(GWL_ID, 0);
m_aboutView.ShowWindow(SW_SHOW);
m_aboutView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_aboutView.SetFocus();
UpdateLayout();
}
void ManageSIP()
{
}
protected:
CxImage m_imgBkg;
BOOL m_bDisabledTransp;
COLORREF m_clNoTranspBackground;
DWORD m_iTransp;
BOOL m_bEnableSIP;
BOOL m_bEnableDD;
CMenu m_menuConfig;
CSimpleArray<CString, CStringEqualHelper<CString>> m_excludedApps;
CSimpleArray<CString, CStringEqualHelper<CString>> m_excludedWnds;
DWORD m_iDisableInterval;
// back gesture recognition
int m_xPos;
int m_backGestureThreshold;
BOOL m_bMouseIsDown;
HWND m_hDestWnd;
HWND m_hPrevDestWnd;
HWND m_hDestCtrl;
BOOL m_bSendCmd;
UINT m_uFlags;
};
<file_sep>/FBReaderJ/local.properties
sdk-location=/home/tao/Desktop/tao/Program/android-sdk_r06-linux/
<file_sep>/FingerSuite/FingerMenuCTRL/skins/default/settings_fingermenu.ini
[colors]
BkgColor=255 255 255
TextColor=0 0 0
SelTextColor=255 255 255
DisabledTextColor=160 160 160
LineColor=200 200 200
ScrollbarColor=160 160 160
; Font settings.
; Options (separated by comma)
; 1. font weight: must be one in "regular", "italic", "bold", "bold italic"
; 2. font height in points
; 3. font face name
[fonts]
; examples
; TextFont=,8p,Arial
; TextFont=italic,,Tahoma
TextFont=bold,,
<file_sep>/SQLCEHelper/Source/Session.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
CSession::CSession()
: m_pSessionProps(NULL)
{
}
CSession::~CSession()
{
Close();
}
HRESULT CSession::Open(ISessionProperties* pSessionProperties)
{
Close();
m_pSessionProps = pSessionProperties;
return S_OK;
}
// CSession::Open
//
// Open a new session on the data source
//
HRESULT CSession::Open(const CDataSource& dataSource)
{
HRESULT hr;
IDBInitialize* pInitialize = dataSource;
CComPtr<IDBCreateSession> spCreateSession;
if(pInitialize == NULL)
return E_NOINTERFACE;
Close();
hr = pInitialize->QueryInterface(IID_IDBCreateSession, (void**)&spCreateSession);
if(SUCCEEDED(hr))
hr = spCreateSession->CreateSession(NULL, IID_ISessionProperties, (IUnknown**)&m_pSessionProps);
return hr;
}
// CSession::Close
//
// Closes the session
//
void CSession::Close()
{
if(m_pSessionProps != NULL)
{
m_pSessionProps->Release();
m_pSessionProps = NULL;
}
}
// CSession::SetProperties
//
// Set the session's properties
//
HRESULT CSession::SetProperties(ULONG cPropSets, DBPROPSET rgPropSets[])
{
HRESULT hr = E_NOINTERFACE;
if(m_pSessionProps == NULL)
return hr;
hr = m_pSessionProps->SetProperties(cPropSets, rgPropSets);
return hr;
}
<file_sep>/FBReaderJ/jni/ModelReader/ModelReader.cpp
#include <vector>
std::vector<int> foo() {
std::vector<int> v;
v.push_back(1);
return v;
}
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/ProgramLocation.cpp
// ProgramLocation.cpp
#include "StdAfx.h"
#include "ProgramLocation.h"
#include "Windows/DLL.h"
using namespace NWindows;
extern HINSTANCE g_hInstance;
bool GetProgramFolderPath(UString &folder)
{
if (!NDLL::MyGetModuleFileName(g_hInstance, folder))
return false;
int pos = folder.ReverseFind(WCHAR_PATH_SEPARATOR);
if (pos < 0)
return false;
folder = folder.Left(pos + 1);
return true;
}
<file_sep>/7-Zip/CPP/7zip/Archive/Zip/ZipIn.h
// Archive/ZipIn.h
#ifndef __ZIP_IN_H
#define __ZIP_IN_H
#include "Common/MyCom.h"
#include "../../IStream.h"
#include "../../Common/InBuffer.h"
#include "ZipHeader.h"
#include "ZipItemEx.h"
namespace NArchive {
namespace NZip {
class CInArchiveException
{
public:
enum ECauseType
{
kUnexpectedEndOfArchive = 0,
kArchiceHeaderCRCError,
kFileHeaderCRCError,
kIncorrectArchive,
kDataDescroptorsAreNotSupported,
kMultiVolumeArchiveAreNotSupported,
kReadStreamError,
kSeekStreamError
}
Cause;
CInArchiveException(ECauseType cause): Cause(cause) {}
};
class CInArchiveInfo
{
public:
UInt64 Base;
UInt64 StartPosition;
CByteBuffer Comment;
CInArchiveInfo(): Base(0), StartPosition(0) {}
void Clear()
{
Base = 0;
StartPosition = 0;
Comment.SetCapacity(0);
}
};
class CProgressVirt
{
public:
STDMETHOD(SetTotal)(UInt64 numFiles) PURE;
STDMETHOD(SetCompleted)(UInt64 numFiles) PURE;
};
struct CCdInfo
{
// UInt64 NumEntries;
UInt64 Size;
UInt64 Offset;
};
class CInArchive
{
CMyComPtr<IInStream> m_Stream;
UInt32 m_Signature;
UInt64 m_StreamStartPosition;
UInt64 m_Position;
bool _inBufMode;
CInBuffer _inBuffer;
HRESULT Seek(UInt64 offset);
HRESULT FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit);
void ReadFileName(UInt32 nameSize, AString &dest);
HRESULT ReadBytes(void *data, UInt32 size, UInt32 *processedSize);
bool ReadBytesAndTestSize(void *data, UInt32 size);
void SafeReadBytes(void *data, UInt32 size);
void ReadBuffer(CByteBuffer &buffer, UInt32 size);
Byte ReadByte();
UInt16 ReadUInt16();
UInt32 ReadUInt32();
UInt64 ReadUInt64();
bool ReadUInt32(UInt32 &signature);
void Skip(UInt64 num);
void IncreaseRealPosition(UInt64 addValue);
void ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock,
UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber);
HRESULT ReadLocalItem(CItemEx &item);
HRESULT ReadLocalItemDescriptor(CItemEx &item);
HRESULT ReadCdItem(CItemEx &item);
HRESULT TryEcd64(UInt64 offset, CCdInfo &cdInfo);
HRESULT FindCd(CCdInfo &cdInfo);
HRESULT TryReadCd(CObjectVector<CItemEx> &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress);
HRESULT ReadCd(CObjectVector<CItemEx> &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress);
HRESULT ReadLocalsAndCd(CObjectVector<CItemEx> &items, CProgressVirt *progress, UInt64 &cdOffset, int &numCdItems);
public:
CInArchiveInfo m_ArchiveInfo;
bool IsZip64;
bool IsOkHeaders;
HRESULT ReadHeaders(CObjectVector<CItemEx> &items, CProgressVirt *progress);
HRESULT ReadLocalItemAfterCdItem(CItemEx &item);
HRESULT ReadLocalItemAfterCdItemFull(CItemEx &item);
HRESULT Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit);
void Close();
void GetArchiveInfo(CInArchiveInfo &archiveInfo) const;
bool SeekInArchive(UInt64 position);
ISequentialInStream *CreateLimitedStream(UInt64 position, UInt64 size);
IInStream* CreateStream();
bool IsOpen() const { return m_Stream != NULL; }
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/Cab/CabHandler.cpp
// CabHandler.cpp
#include "StdAfx.h"
#include "Common/Buffer.h"
#include "Common/ComTry.h"
#include "Common/Defs.h"
#include "Common/IntToString.h"
#include "Common/StringConvert.h"
#include "Common/UTFConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../../Common/ProgressUtils.h"
#include "../../Common/StreamUtils.h"
#include "../../Compress/CopyCoder.h"
#include "../../Compress/DeflateDecoder.h"
#include "../../Compress/LzxDecoder.h"
#include "../../Compress/QuantumDecoder.h"
#include "../Common/ItemNameUtils.h"
#include "CabBlockInStream.h"
#include "CabHandler.h"
using namespace NWindows;
namespace NArchive {
namespace NCab {
// #define _CAB_DETAILS
static const UInt32 kMaxTempBufSize = 1 << 20;
#ifdef _CAB_DETAILS
enum
{
kpidBlockReal = kpidUserDefined
};
#endif
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidAttrib, VT_UI4},
{ NULL, kpidMethod, VT_BSTR},
{ NULL, kpidBlock, VT_I4}
#ifdef _CAB_DETAILS
,
{ L"BlockReal", kpidBlockReal, VT_UI4},
{ NULL, kpidOffset, VT_UI4},
{ NULL, kpidVolume, VT_UI4}
#endif
};
static const wchar_t *kMethods[] =
{
L"None",
L"MSZip",
L"Quantum",
L"LZX"
};
static const int kNumMethods = sizeof(kMethods) / sizeof(kMethods[0]);
static const wchar_t *kUnknownMethod = L"Unknown";
STATPROPSTG kArcProps[] =
{
{ NULL, kpidMethod, VT_BSTR},
// { NULL, kpidSolid, VT_BOOL},
{ NULL, kpidNumBlocks, VT_UI4},
{ NULL, kpidNumVolumes, VT_UI4}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
switch(propID)
{
case kpidMethod:
{
UString resString;
CRecordVector<Byte> ids;
int i;
for (int v = 0; v < m_Database.Volumes.Size(); v++)
{
const CDatabaseEx &de = m_Database.Volumes[v];
for (i = 0; i < de.Folders.Size(); i++)
ids.AddToUniqueSorted(de.Folders[i].GetCompressionMethod());
}
for (i = 0; i < ids.Size(); i++)
{
Byte id = ids[i];
UString method = (id < kNumMethods) ? kMethods[id] : kUnknownMethod;
if (!resString.IsEmpty())
resString += L' ';
resString += method;
}
prop = resString;
break;
}
// case kpidSolid: prop = _database.IsSolid(); break;
case kpidNumBlocks:
{
UInt32 numFolders = 0;
for (int v = 0; v < m_Database.Volumes.Size(); v++)
numFolders += m_Database.Volumes[v].Folders.Size();
prop = numFolders;
break;
}
case kpidNumVolumes:
{
prop = (UInt32)m_Database.Volumes.Size();
break;
}
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CMvItem &mvItem = m_Database.Items[index];
const CDatabaseEx &db = m_Database.Volumes[mvItem.VolumeIndex];
int itemIndex = mvItem.ItemIndex;
const CItem &item = db.Items[itemIndex];
switch(propID)
{
case kpidPath:
{
UString unicodeName;
if (item.IsNameUTF())
ConvertUTF8ToUnicode(item.Name, unicodeName);
else
unicodeName = MultiByteToUnicodeString(item.Name, CP_ACP);
prop = (const wchar_t *)NItemName::WinNameToOSName(unicodeName);
break;
}
case kpidIsDir: prop = item.IsDir(); break;
case kpidSize: prop = item.Size; break;
case kpidAttrib: prop = item.GetWinAttributes(); break;
case kpidMTime:
{
FILETIME localFileTime, utcFileTime;
if (NTime::DosTimeToFileTime(item.Time, localFileTime))
{
if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime))
utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0;
}
else
utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0;
prop = utcFileTime;
break;
}
case kpidMethod:
{
UInt32 realFolderIndex = item.GetFolderIndex(db.Folders.Size());
const CFolder &folder = db.Folders[realFolderIndex];
int methodIndex = folder.GetCompressionMethod();
UString method = (methodIndex < kNumMethods) ? kMethods[methodIndex] : kUnknownMethod;
if (methodIndex == NHeader::NCompressionMethodMajor::kLZX ||
methodIndex == NHeader::NCompressionMethodMajor::kQuantum)
{
method += L":";
wchar_t temp[32];
ConvertUInt64ToString(folder.CompressionTypeMinor, temp);
method += temp;
}
prop = method;
break;
}
case kpidBlock: prop = (Int32)m_Database.GetFolderIndex(&mvItem); break;
#ifdef _CAB_DETAILS
case kpidBlockReal: prop = (UInt32)item.FolderIndex; break;
case kpidOffset: prop = (UInt32)item.Offset; break;
case kpidVolume: prop = (UInt32)mvItem.VolumeIndex; break;
#endif
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
/*
class CProgressImp: public CProgressVirt
{
CMyComPtr<IArchiveOpenCallback> m_OpenArchiveCallback;
public:
STDMETHOD(SetTotal)(const UInt64 *numFiles);
STDMETHOD(SetCompleted)(const UInt64 *numFiles);
void Init(IArchiveOpenCallback *openArchiveCallback)
{ m_OpenArchiveCallback = openArchiveCallback; }
};
STDMETHODIMP CProgressImp::SetTotal(const UInt64 *numFiles)
{
if (m_OpenArchiveCallback)
return m_OpenArchiveCallback->SetCompleted(numFiles, NULL);
return S_OK;
}
STDMETHODIMP CProgressImp::SetCompleted(const UInt64 *numFiles)
{
if (m_OpenArchiveCallback)
return m_OpenArchiveCallback->SetCompleted(numFiles, NULL);
return S_OK;
}
*/
STDMETHODIMP CHandler::Open(IInStream *inStream,
const UInt64 *maxCheckStartPosition,
IArchiveOpenCallback *callback)
{
COM_TRY_BEGIN
Close();
HRESULT res = S_FALSE;
CInArchive archive;
CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback;
callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback);
CMyComPtr<IInStream> nextStream = inStream;
bool prevChecked = false;
UInt64 numItems = 0;
try
{
while (nextStream != 0)
{
CDatabaseEx db;
db.Stream = nextStream;
res = archive.Open(maxCheckStartPosition, db);
if (res == S_OK)
{
if (!m_Database.Volumes.IsEmpty())
{
const CDatabaseEx &dbPrev = m_Database.Volumes[prevChecked ? m_Database.Volumes.Size() - 1 : 0];
if (dbPrev.ArchiveInfo.SetID != db.ArchiveInfo.SetID ||
dbPrev.ArchiveInfo.CabinetNumber + (prevChecked ? 1: - 1) !=
db.ArchiveInfo.CabinetNumber)
res = S_FALSE;
}
}
if (res == S_OK)
m_Database.Volumes.Insert(prevChecked ? m_Database.Volumes.Size() : 0, db);
else if (res != S_FALSE)
return res;
else
{
if (m_Database.Volumes.IsEmpty())
return S_FALSE;
if (prevChecked)
break;
prevChecked = true;
}
numItems += db.Items.Size();
RINOK(callback->SetCompleted(&numItems, NULL));
nextStream = 0;
for (;;)
{
const COtherArchive *otherArchive = 0;
if (!prevChecked)
{
const CInArchiveInfo &ai = m_Database.Volumes.Front().ArchiveInfo;
if (ai.IsTherePrev())
otherArchive = &ai.PrevArc;
else
prevChecked = true;
}
if (otherArchive == 0)
{
const CInArchiveInfo &ai = m_Database.Volumes.Back().ArchiveInfo;
if (ai.IsThereNext())
otherArchive = &ai.NextArc;
}
if (!otherArchive)
break;
const UString fullName = MultiByteToUnicodeString(otherArchive->FileName, CP_ACP);
if (!openVolumeCallback)
break;
HRESULT result = openVolumeCallback->GetStream(fullName, &nextStream);
if (result == S_OK)
break;
if (result != S_FALSE)
return result;
if (prevChecked)
break;
prevChecked = true;
}
}
if (res == S_OK)
{
m_Database.FillSortAndShrink();
if (!m_Database.Check())
res = S_FALSE;
}
}
catch(...)
{
res = S_FALSE;
}
if (res != S_OK)
{
Close();
return res;
}
COM_TRY_END
return S_OK;
}
STDMETHODIMP CHandler::Close()
{
m_Database.Clear();
return S_OK;
}
class CFolderOutStream:
public ISequentialOutStream,
public CMyUnknownImp
{
public:
MY_UNKNOWN_IMP
STDMETHOD(Write)(const void *data, UInt32 size, UInt32 *processedSize);
private:
const CMvDatabaseEx *m_Database;
const CRecordVector<bool> *m_ExtractStatuses;
CByteBuffer TempBuf;
bool TempBufMode;
bool IsSupported;
UInt32 m_BufStartFolderOffset;
int m_StartIndex;
int m_CurrentIndex;
CMyComPtr<IArchiveExtractCallback> m_ExtractCallback;
bool m_TestMode;
CMyComPtr<ISequentialOutStream> m_RealOutStream;
bool m_IsOk;
bool m_FileIsOpen;
UInt32 m_RemainFileSize;
UInt64 m_FolderSize;
UInt64 m_PosInFolder;
HRESULT OpenFile();
HRESULT CloseFile();
HRESULT Write2(const void *data, UInt32 size, UInt32 *processedSize, bool isOK);
public:
HRESULT WriteEmptyFiles();
void Init(
const CMvDatabaseEx *database,
const CRecordVector<bool> *extractStatuses,
int startIndex,
UInt64 folderSize,
IArchiveExtractCallback *extractCallback,
bool testMode);
HRESULT FlushCorrupted();
HRESULT Unsupported();
UInt64 GetRemain() const { return m_FolderSize - m_PosInFolder; }
UInt64 GetPosInFolder() const { return m_PosInFolder; }
};
void CFolderOutStream::Init(
const CMvDatabaseEx *database,
const CRecordVector<bool> *extractStatuses,
int startIndex,
UInt64 folderSize,
IArchiveExtractCallback *extractCallback,
bool testMode)
{
m_Database = database;
m_ExtractStatuses = extractStatuses;
m_StartIndex = startIndex;
m_FolderSize = folderSize;
m_ExtractCallback = extractCallback;
m_TestMode = testMode;
m_CurrentIndex = 0;
m_PosInFolder = 0;
m_FileIsOpen = false;
m_IsOk = true;
TempBufMode = false;
}
HRESULT CFolderOutStream::CloseFile()
{
m_RealOutStream.Release();
HRESULT res = m_ExtractCallback->SetOperationResult(m_IsOk ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kDataError);
m_FileIsOpen = false;
return res;
}
HRESULT CFolderOutStream::OpenFile()
{
Int32 askMode = (*m_ExtractStatuses)[m_CurrentIndex] ? (m_TestMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract) :
NExtract::NAskMode::kSkip;
if (!TempBufMode)
{
const CMvItem &mvItem = m_Database->Items[m_StartIndex + m_CurrentIndex];
const CItem &item = m_Database->Volumes[mvItem.VolumeIndex].Items[mvItem.ItemIndex];
int curIndex = m_CurrentIndex + 1;
for (; curIndex < m_ExtractStatuses->Size(); curIndex++)
if ((*m_ExtractStatuses)[curIndex])
{
const CMvItem &mvItem2 = m_Database->Items[m_StartIndex + curIndex];
const CItem &item2 = m_Database->Volumes[mvItem2.VolumeIndex].Items[mvItem2.ItemIndex];
if (item.Offset != item2.Offset ||
item.Size != item2.Size ||
item.Size == 0)
break;
}
if (curIndex > m_CurrentIndex + 1)
{
size_t oldCapacity = TempBuf.GetCapacity();
IsSupported = (item.Size <= kMaxTempBufSize);
if (item.Size > oldCapacity && IsSupported)
{
TempBuf.SetCapacity(0);
TempBuf.SetCapacity(item.Size);
}
TempBufMode = true;
m_BufStartFolderOffset = item.Offset;
}
}
RINOK(m_ExtractCallback->GetStream(m_StartIndex + m_CurrentIndex, &m_RealOutStream, askMode));
if (!m_RealOutStream && !m_TestMode)
askMode = NExtract::NAskMode::kSkip;
return m_ExtractCallback->PrepareOperation(askMode);
}
HRESULT CFolderOutStream::WriteEmptyFiles()
{
if (m_FileIsOpen)
return S_OK;
for (; m_CurrentIndex < m_ExtractStatuses->Size(); m_CurrentIndex++)
{
const CMvItem &mvItem = m_Database->Items[m_StartIndex + m_CurrentIndex];
const CItem &item = m_Database->Volumes[mvItem.VolumeIndex].Items[mvItem.ItemIndex];
UInt64 fileSize = item.Size;
if (fileSize != 0)
return S_OK;
HRESULT result = OpenFile();
m_RealOutStream.Release();
RINOK(result);
RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
}
return S_OK;
}
// This is Write function
HRESULT CFolderOutStream::Write2(const void *data, UInt32 size, UInt32 *processedSize, bool isOK)
{
COM_TRY_BEGIN
UInt32 realProcessed = 0;
if (processedSize != NULL)
*processedSize = 0;
while (size != 0)
{
if (m_FileIsOpen)
{
UInt32 numBytesToWrite = MyMin(m_RemainFileSize, size);
HRESULT res = S_OK;
if (numBytesToWrite > 0)
{
if (!isOK)
m_IsOk = false;
if (m_RealOutStream)
{
UInt32 processedSizeLocal = 0;
res = m_RealOutStream->Write((const Byte *)data, numBytesToWrite, &processedSizeLocal);
numBytesToWrite = processedSizeLocal;
}
if (TempBufMode && IsSupported)
memcpy(TempBuf + (m_PosInFolder - m_BufStartFolderOffset), data, numBytesToWrite);
}
realProcessed += numBytesToWrite;
if (processedSize != NULL)
*processedSize = realProcessed;
data = (const void *)((const Byte *)data + numBytesToWrite);
size -= numBytesToWrite;
m_RemainFileSize -= numBytesToWrite;
m_PosInFolder += numBytesToWrite;
if (res != S_OK)
return res;
if (m_RemainFileSize == 0)
{
m_RealOutStream.Release();
RINOK(CloseFile());
if (TempBufMode)
{
while (m_CurrentIndex < m_ExtractStatuses->Size())
{
const CMvItem &mvItem = m_Database->Items[m_StartIndex + m_CurrentIndex];
const CItem &item = m_Database->Volumes[mvItem.VolumeIndex].Items[mvItem.ItemIndex];
if (item.Offset != m_BufStartFolderOffset)
break;
HRESULT result = OpenFile();
m_FileIsOpen = true;
m_CurrentIndex++;
m_IsOk = true;
if (result == S_OK && m_RealOutStream && IsSupported)
result = WriteStream(m_RealOutStream, TempBuf, item.Size);
if (IsSupported)
{
RINOK(CloseFile());
RINOK(result);
}
else
{
m_RealOutStream.Release();
RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
m_FileIsOpen = false;
}
}
TempBufMode = false;
}
}
if (realProcessed > 0)
break; // with this break this function works as Write-Part
}
else
{
if (m_CurrentIndex >= m_ExtractStatuses->Size())
return E_FAIL;
const CMvItem &mvItem = m_Database->Items[m_StartIndex + m_CurrentIndex];
const CItem &item = m_Database->Volumes[mvItem.VolumeIndex].Items[mvItem.ItemIndex];
m_RemainFileSize = item.Size;
UInt32 fileOffset = item.Offset;
if (fileOffset < m_PosInFolder)
return E_FAIL;
if (fileOffset > m_PosInFolder)
{
UInt32 numBytesToWrite = MyMin(fileOffset - (UInt32)m_PosInFolder, size);
realProcessed += numBytesToWrite;
if (processedSize != NULL)
*processedSize = realProcessed;
data = (const void *)((const Byte *)data + numBytesToWrite);
size -= numBytesToWrite;
m_PosInFolder += numBytesToWrite;
}
if (fileOffset == m_PosInFolder)
{
RINOK(OpenFile());
m_FileIsOpen = true;
m_CurrentIndex++;
m_IsOk = true;
}
}
}
return WriteEmptyFiles();
COM_TRY_END
}
STDMETHODIMP CFolderOutStream::Write(const void *data, UInt32 size, UInt32 *processedSize)
{
return Write2(data, size, processedSize, true);
}
HRESULT CFolderOutStream::FlushCorrupted()
{
const UInt32 kBufferSize = (1 << 10);
Byte buffer[kBufferSize];
for (int i = 0; i < kBufferSize; i++)
buffer[i] = 0;
for (;;)
{
UInt64 remain = GetRemain();
if (remain == 0)
return S_OK;
UInt32 size = (UInt32)MyMin(remain, (UInt64)kBufferSize);
UInt32 processedSizeLocal = 0;
RINOK(Write2(buffer, size, &processedSizeLocal, false));
}
}
HRESULT CFolderOutStream::Unsupported()
{
while(m_CurrentIndex < m_ExtractStatuses->Size())
{
HRESULT result = OpenFile();
if (result != S_FALSE && result != S_OK)
return result;
m_RealOutStream.Release();
RINOK(m_ExtractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
m_CurrentIndex++;
}
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testModeSpec, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = m_Database.Items.Size();
if(numItems == 0)
return S_OK;
bool testMode = (testModeSpec != 0);
UInt64 totalUnPacked = 0;
UInt32 i;
int lastFolder = -2;
UInt64 lastFolderSize = 0;
for(i = 0; i < numItems; i++)
{
int index = allFilesMode ? i : indices[i];
const CMvItem &mvItem = m_Database.Items[index];
const CItem &item = m_Database.Volumes[mvItem.VolumeIndex].Items[mvItem.ItemIndex];
if (item.IsDir())
continue;
int folderIndex = m_Database.GetFolderIndex(&mvItem);
if (folderIndex != lastFolder)
totalUnPacked += lastFolderSize;
lastFolder = folderIndex;
lastFolderSize = item.GetEndOffset();
}
totalUnPacked += lastFolderSize;
extractCallback->SetTotal(totalUnPacked);
totalUnPacked = 0;
UInt64 totalPacked = 0;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
NCompress::NDeflate::NDecoder::CCOMCoder *deflateDecoderSpec = NULL;
CMyComPtr<ICompressCoder> deflateDecoder;
NCompress::NLzx::CDecoder *lzxDecoderSpec = NULL;
CMyComPtr<ICompressCoder> lzxDecoder;
NCompress::NQuantum::CDecoder *quantumDecoderSpec = NULL;
CMyComPtr<ICompressCoder> quantumDecoder;
CCabBlockInStream *cabBlockInStreamSpec = new CCabBlockInStream();
CMyComPtr<ISequentialInStream> cabBlockInStream = cabBlockInStreamSpec;
if (!cabBlockInStreamSpec->Create())
return E_OUTOFMEMORY;
CRecordVector<bool> extractStatuses;
for(i = 0; i < numItems;)
{
int index = allFilesMode ? i : indices[i];
const CMvItem &mvItem = m_Database.Items[index];
const CDatabaseEx &db = m_Database.Volumes[mvItem.VolumeIndex];
int itemIndex = mvItem.ItemIndex;
const CItem &item = db.Items[itemIndex];
i++;
if (item.IsDir())
{
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
CMyComPtr<ISequentialOutStream> realOutStream;
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
RINOK(extractCallback->PrepareOperation(askMode));
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
int folderIndex = m_Database.GetFolderIndex(&mvItem);
if (folderIndex < 0)
{
// If we need previous archive
Int32 askMode= testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
CMyComPtr<ISequentialOutStream> realOutStream;
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
RINOK(extractCallback->PrepareOperation(askMode));
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kDataError));
continue;
}
int startIndex2 = m_Database.FolderStartFileIndex[folderIndex];
int startIndex = startIndex2;
extractStatuses.Clear();
for (; startIndex < index; startIndex++)
extractStatuses.Add(false);
extractStatuses.Add(true);
startIndex++;
UInt64 curUnpack = item.GetEndOffset();
for(;i < numItems; i++)
{
int indexNext = allFilesMode ? i : indices[i];
const CMvItem &mvItem = m_Database.Items[indexNext];
const CItem &item = m_Database.Volumes[mvItem.VolumeIndex].Items[mvItem.ItemIndex];
if (item.IsDir())
continue;
int newFolderIndex = m_Database.GetFolderIndex(&mvItem);
if (newFolderIndex != folderIndex)
break;
for (; startIndex < indexNext; startIndex++)
extractStatuses.Add(false);
extractStatuses.Add(true);
startIndex++;
curUnpack = item.GetEndOffset();
}
lps->OutSize = totalUnPacked;
lps->InSize = totalPacked;
RINOK(lps->SetCur());
CFolderOutStream *cabFolderOutStream = new CFolderOutStream;
CMyComPtr<ISequentialOutStream> outStream(cabFolderOutStream);
const CFolder &folder = db.Folders[item.GetFolderIndex(db.Folders.Size())];
cabFolderOutStream->Init(&m_Database, &extractStatuses, startIndex2,
curUnpack, extractCallback, testMode);
cabBlockInStreamSpec->MsZip = false;
switch(folder.GetCompressionMethod())
{
case NHeader::NCompressionMethodMajor::kNone:
break;
case NHeader::NCompressionMethodMajor::kMSZip:
if(deflateDecoderSpec == NULL)
{
deflateDecoderSpec = new NCompress::NDeflate::NDecoder::CCOMCoder;
deflateDecoder = deflateDecoderSpec;
}
cabBlockInStreamSpec->MsZip = true;
break;
case NHeader::NCompressionMethodMajor::kLZX:
if(lzxDecoderSpec == NULL)
{
lzxDecoderSpec = new NCompress::NLzx::CDecoder;
lzxDecoder = lzxDecoderSpec;
}
RINOK(lzxDecoderSpec->SetParams(folder.CompressionTypeMinor));
break;
case NHeader::NCompressionMethodMajor::kQuantum:
if(quantumDecoderSpec == NULL)
{
quantumDecoderSpec = new NCompress::NQuantum::CDecoder;
quantumDecoder = quantumDecoderSpec;
}
quantumDecoderSpec->SetParams(folder.CompressionTypeMinor);
break;
default:
{
RINOK(cabFolderOutStream->Unsupported());
totalUnPacked += curUnpack;
continue;
}
}
cabBlockInStreamSpec->InitForNewFolder();
HRESULT res = S_OK;
{
int volIndex = mvItem.VolumeIndex;
int locFolderIndex = item.GetFolderIndex(db.Folders.Size());
bool keepHistory = false;
bool keepInputBuffer = false;
for (UInt32 f = 0; cabFolderOutStream->GetRemain() != 0;)
{
if (volIndex >= m_Database.Volumes.Size())
{
res = S_FALSE;
break;
}
const CDatabaseEx &db = m_Database.Volumes[volIndex];
const CFolder &folder = db.Folders[locFolderIndex];
if (f == 0)
{
cabBlockInStreamSpec->SetStream(db.Stream);
cabBlockInStreamSpec->ReservedSize = db.ArchiveInfo.GetDataBlockReserveSize();
RINOK(db.Stream->Seek(db.StartPosition + folder.DataStart, STREAM_SEEK_SET, NULL));
}
if (f == folder.NumDataBlocks)
{
volIndex++;
locFolderIndex = 0;
f = 0;
continue;
}
f++;
cabBlockInStreamSpec->DataError = false;
if (!keepInputBuffer)
cabBlockInStreamSpec->InitForNewBlock();
UInt32 packSize, unpackSize;
res = cabBlockInStreamSpec->PreRead(packSize, unpackSize);
if (res == S_FALSE)
break;
RINOK(res);
keepInputBuffer = (unpackSize == 0);
if (keepInputBuffer)
continue;
UInt64 totalUnPacked2 = totalUnPacked + cabFolderOutStream->GetPosInFolder();
totalPacked += packSize;
lps->OutSize = totalUnPacked2;
lps->InSize = totalPacked;
RINOK(lps->SetCur());
UInt64 unpackRemain = cabFolderOutStream->GetRemain();
const UInt32 kBlockSizeMax = (1 << 15);
if (unpackRemain > kBlockSizeMax)
unpackRemain = kBlockSizeMax;
if (unpackRemain > unpackSize)
unpackRemain = unpackSize;
switch(folder.GetCompressionMethod())
{
case NHeader::NCompressionMethodMajor::kNone:
res = copyCoder->Code(cabBlockInStream, outStream, NULL, &unpackRemain, NULL);
break;
case NHeader::NCompressionMethodMajor::kMSZip:
deflateDecoderSpec->SetKeepHistory(keepHistory);
res = deflateDecoder->Code(cabBlockInStream, outStream, NULL, &unpackRemain, NULL);
break;
case NHeader::NCompressionMethodMajor::kLZX:
lzxDecoderSpec->SetKeepHistory(keepHistory);
res = lzxDecoder->Code(cabBlockInStream, outStream, NULL, &unpackRemain, NULL);
break;
case NHeader::NCompressionMethodMajor::kQuantum:
quantumDecoderSpec->SetKeepHistory(keepHistory);
res = quantumDecoder->Code(cabBlockInStream, outStream, NULL, &unpackRemain, NULL);
break;
}
if (res != S_OK)
{
if (res != S_FALSE)
RINOK(res);
break;
}
keepHistory = true;
}
if (res == S_OK)
{
RINOK(cabFolderOutStream->WriteEmptyFiles());
}
}
if (res != S_OK || cabFolderOutStream->GetRemain() != 0)
{
RINOK(cabFolderOutStream->FlushCorrupted());
}
totalUnPacked += curUnpack;
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = m_Database.Items.Size();
return S_OK;
}
}}
<file_sep>/FingerSuite/FingerMsgBox/MsgBoxWindow.h
// WTLApp1View.h : interface of the CWTLApp1View class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
//#include "..\Common\ext\RegionBuilder.h"
#ifndef __FNGRBTN_H__
#error MsgBoxWindows.h requires fngrbtn.h to be included first
#endif
#define UM_STARTANIM WM_USER + 1
#define UM_MINIMIZE WM_USER + 2
#define BORDER_WIDTH 8
#define BOTTOM_BORDER_HEIGHT 3
#define LEFT_BORDER_WIDTH 3
#define MIN_HEIGHT 80
#define IDC_BTN_OK 10001
#define IDC_BTN_CANCEL 10002
#define IDC_BTN_YES 10003
#define IDC_BTN_NO 10004
#define IDC_BTN_ABORT 10005
#define IDC_BTN_IGNORE 10006
#define IDC_BTN_RETRY 10007
class CMsgBoxWindow : public CWindowImpl<CMsgBoxWindow>
{
public:
DECLARE_WND_CLASS(NULL)
typedef CWindowImpl<CMsgBoxWindow> Super;
// controls
CFingerButton m_btn1;
CFingerButton m_btn2;
CFingerButton m_btn3;
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
CMsgBoxWindow ()
{
m_iScaleFactor = 1;
}
HWND Create(HWND hWndParent)
{
m_btn1.SetArrayImageSet(m_arrDynamicImages);
m_btn2.SetArrayImageSet(m_arrDynamicImages);
m_btn3.SetArrayImageSet(m_arrDynamicImages);
return Super::Create(hWndParent, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
}
void SetScaleFactor(int iScaleFactor)
{
m_iScaleFactor = iScaleFactor;
}
BOOL SetMsgBox(HWND hOwnrWnd, UINT uType, LPCTSTR pwszCaption, LPCTSTR pwszText)
{
m_hOwnrWnd = hOwnrWnd;
m_uType = uType;
lstrcpy(m_szCaption, pwszCaption);
lstrcpy(m_szText, pwszText);
ModifyShape();
ModifyButtons();
return TRUE;
}
HWND GetOwnerWnd()
{
return m_hOwnrWnd;
}
void DoPaint(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
// fill background
dc.FillSolidRect(&rc, m_clBkg);
int sx = m_icnInfo.GetWidth();
int sy = m_icnInfo.GetHeight();
RECT rcHeader;
SetRect(&rcHeader, 0, 0, rc.right, m_imgHeader.GetHeight());
m_imgHeader.Draw(dc, rcHeader);
BOOL bIconDrawn = FALSE;
if ((m_uType & MB_ICONEXCLAMATION) || (m_uType & MB_ICONWARNING))
{
m_icnWarning.Draw(dc);
bIconDrawn = TRUE;
goto iconend;
}
if ((m_uType & MB_ICONINFORMATION) || (m_uType & MB_ICONASTERISK))
{
m_icnInfo.Draw(dc);
bIconDrawn = TRUE;
goto iconend;
}
if (m_uType & MB_ICONQUESTION)
{
m_icnQuestion.Draw(dc);
bIconDrawn = TRUE;
goto iconend;
}
if ((m_uType & MB_ICONSTOP) || (m_uType & MB_ICONERROR) || (m_uType & MB_ICONHAND))
{
m_icnStop.Draw(dc);
bIconDrawn = TRUE;
goto iconend;
}
iconend:
// draw caption
int border = BORDER_WIDTH * m_iScaleFactor / 2;
RECT rcCaption;
SetRect(&rcCaption, ((bIconDrawn) ? sx : border * m_iScaleFactor), 0, rc.right, sy);
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(m_clCaptionText);
CFont oldFont = dc.SelectFont(m_fCaption);
UINT uFormat = DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS;
if (m_bCenterCaption)
{
uFormat |= DT_CENTER;
rcCaption.left -= (bIconDrawn) ? sx : 0;
}
dc.DrawText(m_szCaption, -1, &rcCaption, uFormat);
dc.SelectFont(oldFont);
// draw text
// dc.SetBkMode(TRANSPARENT);
dc.SetBkColor( RGB(255,216,0) );
dc.SetTextColor(m_clText);
oldFont = dc.SelectFont(m_fText);
dc.DrawText(m_szText, -1, &m_rcText, DT_LEFT | DT_WORDBREAK | DT_END_ELLIPSIS);
dc.SelectFont(oldFont);
// draw button line (dotted line 1px)
CPen pen2; pen2.CreatePen(PS_DASH, 1, m_clLine);
CPen penOld2 = dc.SelectPen(pen2);
dc.MoveTo(rc.left, rc.bottom - m_arrDynamicImages[0].GetHeight() - BOTTOM_BORDER_HEIGHT * m_iScaleFactor - 2);
dc.LineTo(rc.right, rc.bottom - m_arrDynamicImages[0].GetHeight() - BOTTOM_BORDER_HEIGHT * m_iScaleFactor - 2);
dc.SelectPen(penOld2);
}
BEGIN_MSG_MAP(CMsgBoxWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_COMMAND, OnCommand)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
//ModifyShape();
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
RECT rc; GetClientRect(&rc);
}
bHandled = FALSE;
return 0;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if(wParam != NULL)
{
DoPaint((HDC)wParam);
}
else
{
//CPaintDC dc(m_hWnd);
CBufferedPaintDC dc(m_hWnd, 0);
DoPaint(dc.m_hDC);
}
return 0;
}
LRESULT OnCommand(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
int wID = LOWORD(wParam);
switch (wID)
{
case IDC_BTN_YES:
SetMsgBoxResult(IDYES);
break;
case IDC_BTN_NO:
SetMsgBoxResult(IDNO);
break;
case IDC_BTN_OK:
SetMsgBoxResult(IDOK);
break;
case IDC_BTN_CANCEL:
SetMsgBoxResult(IDCANCEL);
break;
case IDC_BTN_ABORT:
SetMsgBoxResult(IDABORT);
break;
case IDC_BTN_IGNORE:
SetMsgBoxResult(IDIGNORE);
break;
case IDC_BTN_RETRY:
SetMsgBoxResult(IDRETRY);
break;
}
GetParent().SendMessage(UM_MINIMIZE, 0, 0);
return 0;
}
public:
CxImage m_icnStop;
CxImage m_icnWarning;
CxImage m_icnQuestion;
CxImage m_icnInfo;
CxImage m_imgHeader;
CFontHandle m_fText;
CFontHandle m_fCaption;
CFontHandle m_fBtn;
int m_xCaption;
int m_yCaption;
int m_xText;
int m_yText;
COLORREF m_clCaptionText;
COLORREF m_clText;
COLORREF m_clBtnText;
COLORREF m_clBtnSelText;
COLORREF m_clBkg;
COLORREF m_clLine;
BOOL m_bDisabledTransp;
COLORREF m_clNoTranspBackground;
DWORD m_iTransp;
BOOL m_bCenterCaption;
CxImage m_arrDynamicImages[9];
private:
HWND m_hOwnrWnd;
UINT m_uType;
WCHAR m_szText[500];
WCHAR m_szCaption[500];
int m_iScaleFactor;
RECT m_rcText;
int CalculateTextHeight()
{
/*
RECT rcText;
SetRect(&rcText, 0,
sy,
rc.right,
rc.bottom - (m_arrImages[0].GetHeight() + BOTTOM_BORDER_HEIGHT * m_iScaleFactor));
*/
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iHeight = 0;
int iWidth = rcParent.right - rcParent.left - 2 * BORDER_WIDTH * m_iScaleFactor - 2 * LEFT_BORDER_WIDTH * m_iScaleFactor;
// RECT rc; GetClientRect(&rc);
SetRect(&m_rcText, 0,
0,
iWidth,
0);
CDC dc = ::GetDC(m_hWnd);
CFont oldFont = dc.SelectFont(m_fText);
dc.DrawText(m_szText, -1, &m_rcText, DT_LEFT | DT_WORDBREAK | DT_END_ELLIPSIS | DT_CALCRECT);
dc.SelectFont(oldFont);
iHeight = m_rcText.bottom;
OffsetRect(&m_rcText, LEFT_BORDER_WIDTH * m_iScaleFactor, m_imgHeader.GetHeight());
return max( (int)((float)iHeight * 1.5f), MIN_HEIGHT * m_iScaleFactor );
}
public:
void ModifyShape()
{
int nUsedRects = 3 * m_iScaleFactor;
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iWidth = rcParent.right - rcParent.left - 2 * BORDER_WIDTH * m_iScaleFactor;
int iHeight = CalculateTextHeight() + m_imgHeader.GetHeight() + m_arrDynamicImages[0].GetHeight() + BOTTOM_BORDER_HEIGHT * m_iScaleFactor;
//iHeight = max( iHeight, 160 * m_iScaleFactor);
iHeight = min(iHeight, rcParent.bottom - rcParent.top - 2 * m_iScaleFactor);
// upper region
RGNDATA *pRgnData;
RECT *pRect;
DWORD dwTemp = sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT);
pRgnData = (RGNDATA*)malloc(dwTemp);
pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRgnData->rdh.iType = RDH_RECTANGLES;
pRgnData->rdh.nCount = nUsedRects;
pRgnData->rdh.nRgnSize = 0;
pRgnData->rdh.rcBound.left = pRgnData->rdh.rcBound.top=0;
pRgnData->rdh.rcBound.right = iWidth;
pRgnData->rdh.rcBound.bottom = nUsedRects;
if (nUsedRects == 3)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 2;
pRect->right = iWidth - 2;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 1;
pRect->right = iWidth - 1;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 0;
pRect->right = iWidth;
}
else if (nUsedRects == 6)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 5;
pRect->right = iWidth - 5;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 3;
pRect->right = iWidth - 3;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 2;
pRect->right = iWidth - 2;
// 4th
pRect = &(((RECT *)&pRgnData->Buffer)[3]);
pRect->top = 3;
pRect->bottom = 4;
pRect->left = 1;
pRect->right = iWidth - 1;
// 5th
pRect = &(((RECT *)&pRgnData->Buffer)[4]);
pRect->top = 4;
pRect->bottom = 5;
pRect->left = 1;
pRect->right = iWidth - 1;
// 6th
pRect = &(((RECT *)&pRgnData->Buffer)[5]);
pRect->top = 5;
pRect->bottom = 6;
pRect->left = 0;
pRect->right = iWidth;
}
HRGN hrgnTop = ExtCreateRegion(NULL, dwTemp, pRgnData);
free(pRgnData);
// lower region
dwTemp = sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT);
pRgnData = (RGNDATA*)malloc(dwTemp);
pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRgnData->rdh.iType = RDH_RECTANGLES;
pRgnData->rdh.nCount = nUsedRects;
pRgnData->rdh.nRgnSize = 0;
pRgnData->rdh.rcBound.left = pRgnData->rdh.rcBound.top=0;
pRgnData->rdh.rcBound.right = iWidth;
pRgnData->rdh.rcBound.bottom = nUsedRects;
if (nUsedRects == 3)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 2;
pRect->right = iWidth - 2;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 1;
pRect->right = iWidth - 1;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 0;
pRect->right = iWidth;
}
else if (nUsedRects == 6)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[5]);
pRect->top = 5;
pRect->bottom = 6;
pRect->left = 5;
pRect->right = iWidth - 5;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[4]);
pRect->top = 4;
pRect->bottom = 5;
pRect->left = 3;
pRect->right = iWidth - 3;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[3]);
pRect->top = 3;
pRect->bottom = 4;
pRect->left = 2;
pRect->right = iWidth - 2;
// 4th
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 1;
pRect->right = iWidth - 1;
// 5th
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 1;
pRect->right = iWidth - 1;
// 6th
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 0;
pRect->right = iWidth;
}
HRGN hrgnBottom = ExtCreateRegion(NULL, dwTemp, pRgnData);
::OffsetRgn(hrgnBottom, 0, iHeight - nUsedRects);
free(pRgnData);
HRGN hrgnMiddle = ::CreateRectRgn(0, 0, iWidth, iHeight - 2 * nUsedRects);
::OffsetRgn(hrgnMiddle, 0, nUsedRects);
CombineRgn(hrgnMiddle, hrgnTop, hrgnMiddle, RGN_OR);
CombineRgn(hrgnMiddle, hrgnBottom, hrgnMiddle, RGN_OR);
SetWindowRgn(hrgnMiddle, FALSE);
ResizeClient(iWidth, iHeight, FALSE);
CenterWindow();
}
void ModifyButtons()
{
RECT rc; GetClientRect(&rc);
int btnHeight = m_arrDynamicImages[0].GetHeight();
if (m_btn1.IsWindow())
m_btn1.DestroyWindow();
if (m_btn2.IsWindow())
m_btn2.DestroyWindow();
if (m_btn3.IsWindow())
m_btn3.DestroyWindow();
int type = m_uType & 0x000F;
if (type == MB_OKCANCEL)
{
RECT rcBtn;
SetRect(&rcBtn, 0, rc.bottom - btnHeight - BOTTOM_BORDER_HEIGHT * m_iScaleFactor, rc.right / 2, rc.bottom);
RECT rcBtn1; CopyRect(&rcBtn1, &rcBtn);
InflateRect(&rcBtn1, -5, 0);
m_btn1.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_OK), m_fBtn, IDC_BTN_OK);
m_btn1.MoveWindow(&rcBtn1);
RECT rcBtn2; CopyRect(&rcBtn2, &rcBtn);
OffsetRect(&rcBtn2, rc.right/2, 0);
InflateRect(&rcBtn2, -4, 0);
m_btn2.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_CANCEL), m_fBtn, IDC_BTN_CANCEL);
m_btn2.MoveWindow(&rcBtn2);
}
if (type == MB_YESNO)
{
RECT rcBtn;
SetRect(&rcBtn, 0, rc.bottom - btnHeight - BOTTOM_BORDER_HEIGHT * m_iScaleFactor, rc.right / 2, rc.bottom);
RECT rcBtn1; CopyRect(&rcBtn1, &rcBtn);
InflateRect(&rcBtn1, -5, 0);
m_btn1.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_YES), m_fBtn, IDC_BTN_YES);
m_btn1.MoveWindow(&rcBtn1);
RECT rcBtn2; CopyRect(&rcBtn2, &rcBtn);
OffsetRect(&rcBtn2, rc.right/2, 0);
InflateRect(&rcBtn2, -4, 0);
m_btn2.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_NO), m_fBtn, IDC_BTN_NO);
m_btn2.MoveWindow(&rcBtn2);
}
if (type == MB_YESNOCANCEL)
{
RECT rcBtn;
SetRect(&rcBtn, 0, rc.bottom - btnHeight - BOTTOM_BORDER_HEIGHT * m_iScaleFactor, rc.right / 3, rc.bottom);
RECT rcBtn1; CopyRect(&rcBtn1, &rcBtn);
InflateRect(&rcBtn1, -5, 0);
m_btn1.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_YES), m_fBtn, IDC_BTN_YES);
m_btn1.MoveWindow(&rcBtn1);
RECT rcBtn2; CopyRect(&rcBtn2, &rcBtn);
OffsetRect(&rcBtn2, rc.right / 3, 0);
InflateRect(&rcBtn2, -4, 0);
m_btn2.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_NO), m_fBtn, IDC_BTN_NO);
m_btn2.MoveWindow(&rcBtn2);
RECT rcBtn3; CopyRect(&rcBtn3, &rcBtn);
OffsetRect(&rcBtn3, 2 * rc.right / 3, 0);
InflateRect(&rcBtn3, -4, 0);
m_btn3.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_CANCEL), m_fBtn, IDC_BTN_CANCEL);
m_btn3.MoveWindow(&rcBtn3);
}
if (type == MB_OK)
{
RECT rcBtn;
SetRect(&rcBtn, 0, rc.bottom - btnHeight - BOTTOM_BORDER_HEIGHT * m_iScaleFactor, rc.right, rc.bottom);
InflateRect(&rcBtn, -5, 0);
m_btn1.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_OK), m_fBtn, IDC_BTN_OK);
m_btn1.MoveWindow(&rcBtn);
}
if (type == MB_RETRYCANCEL)
{
RECT rcBtn;
SetRect(&rcBtn, 0, rc.bottom - btnHeight - BOTTOM_BORDER_HEIGHT * m_iScaleFactor, rc.right / 2, rc.bottom);
RECT rcBtn1; CopyRect(&rcBtn1, &rcBtn);
InflateRect(&rcBtn1, -5, 0);
m_btn1.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_RETRY), m_fBtn, IDC_BTN_RETRY);
m_btn1.MoveWindow(&rcBtn1);
RECT rcBtn2; CopyRect(&rcBtn2, &rcBtn);
OffsetRect(&rcBtn2, rc.right/2, 0);
InflateRect(&rcBtn2, -4, 0);
m_btn2.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_CANCEL), m_fBtn, IDC_BTN_CANCEL);
m_btn2.MoveWindow(&rcBtn2);
}
if (type == MB_ABORTRETRYIGNORE)
{
RECT rcBtn;
SetRect(&rcBtn, 0, rc.bottom - btnHeight - BOTTOM_BORDER_HEIGHT * m_iScaleFactor, rc.right / 3, rc.bottom);
RECT rcBtn1; CopyRect(&rcBtn1, &rcBtn);
InflateRect(&rcBtn1, -5, 0);
m_btn1.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_ABORT), m_fBtn, IDC_BTN_ABORT);
m_btn1.MoveWindow(&rcBtn1);
RECT rcBtn2; CopyRect(&rcBtn2, &rcBtn);
OffsetRect(&rcBtn2, rc.right / 3, 0);
InflateRect(&rcBtn2, -4, 0);
m_btn2.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_RETRY), m_fBtn, IDC_BTN_RETRY);
m_btn2.MoveWindow(&rcBtn2);
RECT rcBtn3; CopyRect(&rcBtn3, &rcBtn);
OffsetRect(&rcBtn3, 2 * rc.right / 3, 0);
InflateRect(&rcBtn3, -4, 0);
m_btn3.Create(m_hWnd, FNGRBTN_TYPE_DYNAMIC, TRUE, m_clBkg, m_clBtnText, m_clBtnSelText, LoadResourceString(IDS_IGNORE), m_fBtn, IDC_BTN_IGNORE);
m_btn3.MoveWindow(&rcBtn3);
}
//return TRUE;
}
};
<file_sep>/7-Zip/CPP/7zip/Archive/Zip/ZipIn.cpp
// Archive/ZipIn.cpp
#include "StdAfx.h"
#include "../../../../C/CpuArch.h"
#include "Common/DynamicBuffer.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/StreamUtils.h"
#include "ZipIn.h"
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
#define Get64(p) GetUi64(p)
namespace NArchive {
namespace NZip {
HRESULT CInArchive::Open(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
{
_inBufMode = false;
Close();
RINOK(stream->Seek(0, STREAM_SEEK_CUR, &m_StreamStartPosition));
m_Position = m_StreamStartPosition;
RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit));
RINOK(stream->Seek(m_Position, STREAM_SEEK_SET, NULL));
m_Stream = stream;
return S_OK;
}
void CInArchive::Close()
{
_inBuffer.ReleaseStream();
m_Stream.Release();
}
HRESULT CInArchive::Seek(UInt64 offset)
{
return m_Stream->Seek(offset, STREAM_SEEK_SET, NULL);
}
//////////////////////////////////////
// Markers
static inline bool TestMarkerCandidate(const Byte *p, UInt32 &value)
{
value = Get32(p);
return
(value == NSignature::kLocalFileHeader) ||
(value == NSignature::kEndOfCentralDir);
}
static const UInt32 kNumMarkerAddtionalBytes = 2;
static inline bool TestMarkerCandidate2(const Byte *p, UInt32 &value)
{
value = Get32(p);
if (value == NSignature::kEndOfCentralDir)
return (Get16(p + 4) == 0);
return (value == NSignature::kLocalFileHeader && p[4] < 128);
}
HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
{
m_ArchiveInfo.Clear();
m_Position = m_StreamStartPosition;
Byte marker[NSignature::kMarkerSize];
RINOK(ReadStream_FALSE(stream, marker, NSignature::kMarkerSize));
m_Position += NSignature::kMarkerSize;
if (TestMarkerCandidate(marker, m_Signature))
return S_OK;
CByteDynamicBuffer dynamicBuffer;
const UInt32 kSearchMarkerBufferSize = 0x10000;
dynamicBuffer.EnsureCapacity(kSearchMarkerBufferSize);
Byte *buffer = dynamicBuffer;
UInt32 numBytesPrev = NSignature::kMarkerSize - 1;
memcpy(buffer, marker + 1, numBytesPrev);
UInt64 curTestPos = m_StreamStartPosition + 1;
for (;;)
{
if (searchHeaderSizeLimit != NULL)
if (curTestPos - m_StreamStartPosition > *searchHeaderSizeLimit)
break;
size_t numReadBytes = kSearchMarkerBufferSize - numBytesPrev;
RINOK(ReadStream(stream, buffer + numBytesPrev, &numReadBytes));
m_Position += numReadBytes;
UInt32 numBytesInBuffer = numBytesPrev + (UInt32)numReadBytes;
const UInt32 kMarker2Size = NSignature::kMarkerSize + kNumMarkerAddtionalBytes;
if (numBytesInBuffer < kMarker2Size)
break;
UInt32 numTests = numBytesInBuffer - kMarker2Size + 1;
for (UInt32 pos = 0; pos < numTests; pos++)
{
if (buffer[pos] != 0x50)
continue;
if (TestMarkerCandidate2(buffer + pos, m_Signature))
{
curTestPos += pos;
m_ArchiveInfo.StartPosition = curTestPos;
m_Position = curTestPos + NSignature::kMarkerSize;
return S_OK;
}
}
curTestPos += numTests;
numBytesPrev = numBytesInBuffer - numTests;
memmove(buffer, buffer + numTests, numBytesPrev);
}
return S_FALSE;
}
HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize)
{
size_t realProcessedSize = size;
HRESULT result = S_OK;
if (_inBufMode)
{
try { realProcessedSize = _inBuffer.ReadBytes((Byte *)data, size); }
catch (const CInBufferException &e) { return e.ErrorCode; }
}
else
result = ReadStream(m_Stream, data, &realProcessedSize);
if (processedSize != NULL)
*processedSize = (UInt32)realProcessedSize;
m_Position += realProcessedSize;
return result;
}
void CInArchive::Skip(UInt64 num)
{
for (UInt64 i = 0; i < num; i++)
ReadByte();
}
void CInArchive::IncreaseRealPosition(UInt64 addValue)
{
if (m_Stream->Seek(addValue, STREAM_SEEK_CUR, &m_Position) != S_OK)
throw CInArchiveException(CInArchiveException::kSeekStreamError);
}
bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size)
{
UInt32 realProcessedSize;
if (ReadBytes(data, size, &realProcessedSize) != S_OK)
throw CInArchiveException(CInArchiveException::kReadStreamError);
return (realProcessedSize == size);
}
void CInArchive::SafeReadBytes(void *data, UInt32 size)
{
if (!ReadBytesAndTestSize(data, size))
throw CInArchiveException(CInArchiveException::kUnexpectedEndOfArchive);
}
void CInArchive::ReadBuffer(CByteBuffer &buffer, UInt32 size)
{
buffer.SetCapacity(size);
if (size > 0)
SafeReadBytes(buffer, size);
}
Byte CInArchive::ReadByte()
{
Byte b;
SafeReadBytes(&b, 1);
return b;
}
UInt16 CInArchive::ReadUInt16()
{
Byte buf[2];
SafeReadBytes(buf, 2);
return Get16(buf);
}
UInt32 CInArchive::ReadUInt32()
{
Byte buf[4];
SafeReadBytes(buf, 4);
return Get32(buf);
}
UInt64 CInArchive::ReadUInt64()
{
Byte buf[8];
SafeReadBytes(buf, 8);
return Get64(buf);
}
bool CInArchive::ReadUInt32(UInt32 &value)
{
Byte buf[4];
if (!ReadBytesAndTestSize(buf, 4))
return false;
value = Get32(buf);
return true;
}
void CInArchive::ReadFileName(UInt32 nameSize, AString &dest)
{
if (nameSize == 0)
dest.Empty();
char *p = dest.GetBuffer((int)nameSize);
SafeReadBytes(p, nameSize);
p[nameSize] = 0;
dest.ReleaseBuffer();
}
void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const
{
archiveInfo = m_ArchiveInfo;
}
void CInArchive::ReadExtra(UInt32 extraSize, CExtraBlock &extraBlock,
UInt64 &unpackSize, UInt64 &packSize, UInt64 &localHeaderOffset, UInt32 &diskStartNumber)
{
extraBlock.Clear();
UInt32 remain = extraSize;
while(remain >= 4)
{
CExtraSubBlock subBlock;
subBlock.ID = ReadUInt16();
UInt32 dataSize = ReadUInt16();
remain -= 4;
if (dataSize > remain) // it's bug
dataSize = remain;
if (subBlock.ID == NFileHeader::NExtraID::kZip64)
{
if (unpackSize == 0xFFFFFFFF)
{
if (dataSize < 8)
break;
unpackSize = ReadUInt64();
remain -= 8;
dataSize -= 8;
}
if (packSize == 0xFFFFFFFF)
{
if (dataSize < 8)
break;
packSize = ReadUInt64();
remain -= 8;
dataSize -= 8;
}
if (localHeaderOffset == 0xFFFFFFFF)
{
if (dataSize < 8)
break;
localHeaderOffset = ReadUInt64();
remain -= 8;
dataSize -= 8;
}
if (diskStartNumber == 0xFFFF)
{
if (dataSize < 4)
break;
diskStartNumber = ReadUInt32();
remain -= 4;
dataSize -= 4;
}
for (UInt32 i = 0; i < dataSize; i++)
ReadByte();
}
else
{
ReadBuffer(subBlock.Data, dataSize);
extraBlock.SubBlocks.Add(subBlock);
}
remain -= dataSize;
}
Skip(remain);
}
HRESULT CInArchive::ReadLocalItem(CItemEx &item)
{
const int kBufSize = 26;
Byte p[kBufSize];
SafeReadBytes(p, kBufSize);
item.ExtractVersion.Version = p[0];
item.ExtractVersion.HostOS = p[1];
item.Flags = Get16(p + 2);
item.CompressionMethod = Get16(p + 4);
item.Time = Get32(p + 6);
item.FileCRC = Get32(p + 10);
item.PackSize = Get32(p + 14);
item.UnPackSize = Get32(p + 18);
UInt32 fileNameSize = Get16(p + 22);
item.LocalExtraSize = Get16(p + 24);
ReadFileName(fileNameSize, item.Name);
item.FileHeaderWithNameSize = 4 + NFileHeader::kLocalBlockSize + fileNameSize;
if (item.LocalExtraSize > 0)
{
UInt64 localHeaderOffset = 0;
UInt32 diskStartNumber = 0;
ReadExtra(item.LocalExtraSize, item.LocalExtra, item.UnPackSize, item.PackSize,
localHeaderOffset, diskStartNumber);
}
/*
if (item.IsDir())
item.UnPackSize = 0; // check It
*/
return S_OK;
}
static bool FlagsAreSame(CItem &i1, CItem &i2)
{
if (i1.CompressionMethod != i2.CompressionMethod)
return false;
// i1.Time
if (i1.Flags == i2.Flags)
return true;
UInt32 mask = 0xFFFF;
switch(i1.CompressionMethod)
{
case NFileHeader::NCompressionMethod::kDeflated:
mask = 0x7FF9;
break;
default:
if (i1.CompressionMethod <= NFileHeader::NCompressionMethod::kImploded)
mask = 0x7FFF;
}
return ((i1.Flags & mask) == (i2.Flags & mask));
}
HRESULT CInArchive::ReadLocalItemAfterCdItem(CItemEx &item)
{
if (item.FromLocal)
return S_OK;
try
{
RINOK(Seek(m_ArchiveInfo.Base + item.LocalHeaderPosition));
CItemEx localItem;
if (ReadUInt32() != NSignature::kLocalFileHeader)
return S_FALSE;
RINOK(ReadLocalItem(localItem));
if (!FlagsAreSame(item, localItem))
return S_FALSE;
if ((!localItem.HasDescriptor() &&
(
item.FileCRC != localItem.FileCRC ||
item.PackSize != localItem.PackSize ||
item.UnPackSize != localItem.UnPackSize
)
) ||
item.Name.Length() != localItem.Name.Length()
)
return S_FALSE;
item.FileHeaderWithNameSize = localItem.FileHeaderWithNameSize;
item.LocalExtraSize = localItem.LocalExtraSize;
item.LocalExtra = localItem.LocalExtra;
item.FromLocal = true;
}
catch(...) { return S_FALSE; }
return S_OK;
}
HRESULT CInArchive::ReadLocalItemDescriptor(CItemEx &item)
{
if (item.HasDescriptor())
{
const int kBufferSize = (1 << 12);
Byte buffer[kBufferSize];
UInt32 numBytesInBuffer = 0;
UInt32 packedSize = 0;
bool descriptorWasFound = false;
for (;;)
{
UInt32 processedSize;
RINOK(ReadBytes(buffer + numBytesInBuffer, kBufferSize - numBytesInBuffer, &processedSize));
numBytesInBuffer += processedSize;
if (numBytesInBuffer < NFileHeader::kDataDescriptorSize)
return S_FALSE;
UInt32 i;
for (i = 0; i <= numBytesInBuffer - NFileHeader::kDataDescriptorSize; i++)
{
// descriptorSignature field is Info-ZIP's extension
// to Zip specification.
UInt32 descriptorSignature = Get32(buffer + i);
// !!!! It must be fixed for Zip64 archives
UInt32 descriptorPackSize = Get32(buffer + i + 8);
if (descriptorSignature== NSignature::kDataDescriptor && descriptorPackSize == packedSize + i)
{
descriptorWasFound = true;
item.FileCRC = Get32(buffer + i + 4);
item.PackSize = descriptorPackSize;
item.UnPackSize = Get32(buffer + i + 12);
IncreaseRealPosition(Int64(Int32(0 - (numBytesInBuffer - i - NFileHeader::kDataDescriptorSize))));
break;
}
}
if (descriptorWasFound)
break;
packedSize += i;
int j;
for (j = 0; i < numBytesInBuffer; i++, j++)
buffer[j] = buffer[i];
numBytesInBuffer = j;
}
}
else
IncreaseRealPosition(item.PackSize);
return S_OK;
}
HRESULT CInArchive::ReadLocalItemAfterCdItemFull(CItemEx &item)
{
if (item.FromLocal)
return S_OK;
try
{
RINOK(ReadLocalItemAfterCdItem(item));
if (item.HasDescriptor())
{
RINOK(Seek(m_ArchiveInfo.Base + item.GetDataPosition() + item.PackSize));
if (ReadUInt32() != NSignature::kDataDescriptor)
return S_FALSE;
UInt32 crc = ReadUInt32();
UInt64 packSize, unpackSize;
/*
if (IsZip64)
{
packSize = ReadUInt64();
unpackSize = ReadUInt64();
}
else
*/
{
packSize = ReadUInt32();
unpackSize = ReadUInt32();
}
if (crc != item.FileCRC || item.PackSize != packSize || item.UnPackSize != unpackSize)
return S_FALSE;
}
}
catch(...) { return S_FALSE; }
return S_OK;
}
HRESULT CInArchive::ReadCdItem(CItemEx &item)
{
item.FromCentral = true;
const int kBufSize = 42;
Byte p[kBufSize];
SafeReadBytes(p, kBufSize);
item.MadeByVersion.Version = p[0];
item.MadeByVersion.HostOS = p[1];
item.ExtractVersion.Version = p[2];
item.ExtractVersion.HostOS = p[3];
item.Flags = Get16(p + 4);
item.CompressionMethod = Get16(p + 6);
item.Time = Get32(p + 8);
item.FileCRC = Get32(p + 12);
item.PackSize = Get32(p + 16);
item.UnPackSize = Get32(p + 20);
UInt16 headerNameSize = Get16(p + 24);
UInt16 headerExtraSize = Get16(p + 26);
UInt16 headerCommentSize = Get16(p + 28);
UInt32 headerDiskNumberStart = Get16(p + 30);
item.InternalAttributes = Get16(p + 32);
item.ExternalAttributes = Get32(p + 34);
item.LocalHeaderPosition = Get32(p + 38);
ReadFileName(headerNameSize, item.Name);
if (headerExtraSize > 0)
{
ReadExtra(headerExtraSize, item.CentralExtra, item.UnPackSize, item.PackSize,
item.LocalHeaderPosition, headerDiskNumberStart);
}
if (headerDiskNumberStart != 0)
throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
// May be these strings must be deleted
/*
if (item.IsDir())
item.UnPackSize = 0;
*/
ReadBuffer(item.Comment, headerCommentSize);
return S_OK;
}
HRESULT CInArchive::TryEcd64(UInt64 offset, CCdInfo &cdInfo)
{
RINOK(Seek(offset));
const UInt32 kEcd64Size = 56;
Byte buf[kEcd64Size];
if (!ReadBytesAndTestSize(buf, kEcd64Size))
return S_FALSE;
if (Get32(buf) != NSignature::kZip64EndOfCentralDir)
return S_FALSE;
// cdInfo.NumEntries = Get64(buf + 24);
cdInfo.Size = Get64(buf + 40);
cdInfo.Offset = Get64(buf + 48);
return S_OK;
}
HRESULT CInArchive::FindCd(CCdInfo &cdInfo)
{
UInt64 endPosition;
RINOK(m_Stream->Seek(0, STREAM_SEEK_END, &endPosition));
const UInt32 kBufSizeMax = (1 << 16) + kEcdSize + kZip64EcdLocatorSize;
CByteBuffer byteBuffer;
byteBuffer.SetCapacity(kBufSizeMax);
Byte *buf = byteBuffer;
UInt32 bufSize = (endPosition < kBufSizeMax) ? (UInt32)endPosition : kBufSizeMax;
if (bufSize < kEcdSize)
return S_FALSE;
UInt64 startPosition = endPosition - bufSize;
RINOK(m_Stream->Seek(startPosition, STREAM_SEEK_SET, &m_Position));
if (m_Position != startPosition)
return S_FALSE;
if (!ReadBytesAndTestSize(buf, bufSize))
return S_FALSE;
for (int i = (int)(bufSize - kEcdSize); i >= 0; i--)
{
if (Get32(buf + i) == NSignature::kEndOfCentralDir)
{
if (i >= kZip64EcdLocatorSize)
{
const Byte *locator = buf + i - kZip64EcdLocatorSize;
if (Get32(locator) == NSignature::kZip64EndOfCentralDirLocator)
{
UInt64 ecd64Offset = Get64(locator + 8);
if (TryEcd64(ecd64Offset, cdInfo) == S_OK)
return S_OK;
if (TryEcd64(m_ArchiveInfo.StartPosition + ecd64Offset, cdInfo) == S_OK)
{
m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition;
return S_OK;
}
}
}
if (Get32(buf + i + 4) == 0)
{
// cdInfo.NumEntries = GetUInt16(buf + i + 10);
cdInfo.Size = Get32(buf + i + 12);
cdInfo.Offset = Get32(buf + i + 16);
UInt64 curPos = endPosition - bufSize + i;
UInt64 cdEnd = cdInfo.Size + cdInfo.Offset;
if (curPos > cdEnd)
m_ArchiveInfo.Base = curPos - cdEnd;
return S_OK;
}
}
}
return S_FALSE;
}
HRESULT CInArchive::TryReadCd(CObjectVector<CItemEx> &items, UInt64 cdOffset, UInt64 cdSize, CProgressVirt *progress)
{
items.Clear();
RINOK(m_Stream->Seek(cdOffset, STREAM_SEEK_SET, &m_Position));
if (m_Position != cdOffset)
return S_FALSE;
if (!_inBuffer.Create(1 << 15))
return E_OUTOFMEMORY;
_inBuffer.SetStream(m_Stream);
_inBuffer.Init();
_inBufMode = true;
while(m_Position - cdOffset < cdSize)
{
if (ReadUInt32() != NSignature::kCentralFileHeader)
return S_FALSE;
CItemEx cdItem;
RINOK(ReadCdItem(cdItem));
items.Add(cdItem);
if (progress && items.Size() % 1000 == 0)
RINOK(progress->SetCompleted(items.Size()));
}
return (m_Position - cdOffset == cdSize) ? S_OK : S_FALSE;
}
HRESULT CInArchive::ReadCd(CObjectVector<CItemEx> &items, UInt64 &cdOffset, UInt64 &cdSize, CProgressVirt *progress)
{
m_ArchiveInfo.Base = 0;
CCdInfo cdInfo;
RINOK(FindCd(cdInfo));
HRESULT res = S_FALSE;
cdSize = cdInfo.Size;
cdOffset = cdInfo.Offset;
res = TryReadCd(items, m_ArchiveInfo.Base + cdOffset, cdSize, progress);
if (res == S_FALSE && m_ArchiveInfo.Base == 0)
{
res = TryReadCd(items, cdInfo.Offset + m_ArchiveInfo.StartPosition, cdSize, progress);
if (res == S_OK)
m_ArchiveInfo.Base = m_ArchiveInfo.StartPosition;
}
if (!ReadUInt32(m_Signature))
return S_FALSE;
return res;
}
HRESULT CInArchive::ReadLocalsAndCd(CObjectVector<CItemEx> &items, CProgressVirt *progress, UInt64 &cdOffset, int &numCdItems)
{
items.Clear();
numCdItems = 0;
while (m_Signature == NSignature::kLocalFileHeader)
{
// FSeek points to next byte after signature
// NFileHeader::CLocalBlock localHeader;
CItemEx item;
item.LocalHeaderPosition = m_Position - m_StreamStartPosition - 4; // points to signature;
RINOK(ReadLocalItem(item));
item.FromLocal = true;
ReadLocalItemDescriptor(item);
items.Add(item);
if (progress && items.Size() % 100 == 0)
RINOK(progress->SetCompleted(items.Size()));
if (!ReadUInt32(m_Signature))
break;
}
cdOffset = m_Position - 4;
int i;
for (i = 0; i < items.Size(); i++, numCdItems++)
{
if (progress && i % 1000 == 0)
RINOK(progress->SetCompleted(items.Size()));
if (m_Signature == NSignature::kEndOfCentralDir)
break;
if (m_Signature != NSignature::kCentralFileHeader)
return S_FALSE;
CItemEx cdItem;
RINOK(ReadCdItem(cdItem));
if (i == 0)
{
int j;
for (j = 0; j < items.Size(); j++)
{
CItemEx &item = items[j];
if (item.Name == cdItem.Name)
{
m_ArchiveInfo.Base = item.LocalHeaderPosition - cdItem.LocalHeaderPosition;
break;
}
}
if (j == items.Size())
return S_FALSE;
}
int index;
int left = 0, right = items.Size();
for (;;)
{
if (left >= right)
return S_FALSE;
index = (left + right) / 2;
UInt64 position = items[index].LocalHeaderPosition - m_ArchiveInfo.Base;
if (cdItem.LocalHeaderPosition == position)
break;
if (cdItem.LocalHeaderPosition < position)
right = index;
else
left = index + 1;
}
CItemEx &item = items[index];
// item.LocalHeaderPosition = cdItem.LocalHeaderPosition;
item.MadeByVersion = cdItem.MadeByVersion;
item.CentralExtra = cdItem.CentralExtra;
if (
// item.ExtractVersion != cdItem.ExtractVersion ||
!FlagsAreSame(item, cdItem) ||
item.FileCRC != cdItem.FileCRC)
return S_FALSE;
if (item.Name.Length() != cdItem.Name.Length() ||
item.PackSize != cdItem.PackSize ||
item.UnPackSize != cdItem.UnPackSize
)
return S_FALSE;
item.Name = cdItem.Name;
item.InternalAttributes = cdItem.InternalAttributes;
item.ExternalAttributes = cdItem.ExternalAttributes;
item.Comment = cdItem.Comment;
item.FromCentral = cdItem.FromCentral;
if (!ReadUInt32(m_Signature))
return S_FALSE;
}
for (i = 0; i < items.Size(); i++)
items[i].LocalHeaderPosition -= m_ArchiveInfo.Base;
return S_OK;
}
struct CEcd
{
UInt16 thisDiskNumber;
UInt16 startCDDiskNumber;
UInt16 numEntriesInCDOnThisDisk;
UInt16 numEntriesInCD;
UInt32 cdSize;
UInt32 cdStartOffset;
UInt16 commentSize;
void Parse(const Byte *p);
};
void CEcd::Parse(const Byte *p)
{
thisDiskNumber = Get16(p);
startCDDiskNumber = Get16(p + 2);
numEntriesInCDOnThisDisk = Get16(p + 4);
numEntriesInCD = Get16(p + 6);
cdSize = Get32(p + 8);
cdStartOffset = Get32(p + 12);
commentSize = Get16(p + 16);
}
struct CEcd64
{
UInt16 versionMade;
UInt16 versionNeedExtract;
UInt32 thisDiskNumber;
UInt32 startCDDiskNumber;
UInt64 numEntriesInCDOnThisDisk;
UInt64 numEntriesInCD;
UInt64 cdSize;
UInt64 cdStartOffset;
void Parse(const Byte *p);
CEcd64() { memset(this, 0, sizeof(*this)); }
};
void CEcd64::Parse(const Byte *p)
{
versionMade = Get16(p);
versionNeedExtract = Get16(p + 2);
thisDiskNumber = Get32(p + 4);
startCDDiskNumber = Get32(p + 8);
numEntriesInCDOnThisDisk = Get64(p + 12);
numEntriesInCD = Get64(p + 20);
cdSize = Get64(p + 28);
cdStartOffset = Get64(p + 36);
}
#define COPY_ECD_ITEM_16(n) if (!isZip64 || ecd. n != 0xFFFF) ecd64. n = ecd. n;
#define COPY_ECD_ITEM_32(n) if (!isZip64 || ecd. n != 0xFFFFFFFF) ecd64. n = ecd. n;
HRESULT CInArchive::ReadHeaders(CObjectVector<CItemEx> &items, CProgressVirt *progress)
{
// m_Signature must be kLocalFileHeaderSignature or
// kEndOfCentralDirSignature
// m_Position points to next byte after signature
IsZip64 = false;
items.Clear();
UInt64 cdSize, cdStartOffset;
HRESULT res;
try
{
res = ReadCd(items, cdStartOffset, cdSize, progress);
}
catch(CInArchiveException &)
{
res = S_FALSE;
}
if (res != S_FALSE && res != S_OK)
return res;
/*
if (res != S_OK)
return res;
res = S_FALSE;
*/
int numCdItems = items.Size();
if (res == S_FALSE)
{
_inBufMode = false;
m_ArchiveInfo.Base = 0;
RINOK(m_Stream->Seek(m_ArchiveInfo.StartPosition, STREAM_SEEK_SET, &m_Position));
if (m_Position != m_ArchiveInfo.StartPosition)
return S_FALSE;
if (!ReadUInt32(m_Signature))
return S_FALSE;
RINOK(ReadLocalsAndCd(items, progress, cdStartOffset, numCdItems));
cdSize = (m_Position - 4) - cdStartOffset;
cdStartOffset -= m_ArchiveInfo.Base;
}
CEcd64 ecd64;
bool isZip64 = false;
UInt64 zip64EcdStartOffset = m_Position - 4 - m_ArchiveInfo.Base;
if (m_Signature == NSignature::kZip64EndOfCentralDir)
{
IsZip64 = isZip64 = true;
UInt64 recordSize = ReadUInt64();
const int kBufSize = kZip64EcdSize;
Byte buf[kBufSize];
SafeReadBytes(buf, kBufSize);
ecd64.Parse(buf);
Skip(recordSize - kZip64EcdSize);
if (!ReadUInt32(m_Signature))
return S_FALSE;
if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0)
throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
if (ecd64.numEntriesInCDOnThisDisk != numCdItems ||
ecd64.numEntriesInCD != numCdItems ||
ecd64.cdSize != cdSize ||
(ecd64.cdStartOffset != cdStartOffset &&
(!items.IsEmpty())))
return S_FALSE;
}
if (m_Signature == NSignature::kZip64EndOfCentralDirLocator)
{
/* UInt32 startEndCDDiskNumber = */ ReadUInt32();
UInt64 endCDStartOffset = ReadUInt64();
/* UInt32 numberOfDisks = */ ReadUInt32();
if (zip64EcdStartOffset != endCDStartOffset)
return S_FALSE;
if (!ReadUInt32(m_Signature))
return S_FALSE;
}
if (m_Signature != NSignature::kEndOfCentralDir)
return S_FALSE;
const int kBufSize = kEcdSize - 4;
Byte buf[kBufSize];
SafeReadBytes(buf, kBufSize);
CEcd ecd;
ecd.Parse(buf);
COPY_ECD_ITEM_16(thisDiskNumber);
COPY_ECD_ITEM_16(startCDDiskNumber);
COPY_ECD_ITEM_16(numEntriesInCDOnThisDisk);
COPY_ECD_ITEM_16(numEntriesInCD);
COPY_ECD_ITEM_32(cdSize);
COPY_ECD_ITEM_32(cdStartOffset);
ReadBuffer(m_ArchiveInfo.Comment, ecd.commentSize);
if (ecd64.thisDiskNumber != 0 || ecd64.startCDDiskNumber != 0)
throw CInArchiveException(CInArchiveException::kMultiVolumeArchiveAreNotSupported);
if ((UInt16)ecd64.numEntriesInCDOnThisDisk != ((UInt16)numCdItems) ||
(UInt16)ecd64.numEntriesInCD != ((UInt16)numCdItems) ||
(UInt32)ecd64.cdSize != (UInt32)cdSize ||
((UInt32)(ecd64.cdStartOffset) != (UInt32)cdStartOffset &&
(!items.IsEmpty())))
return S_FALSE;
_inBufMode = false;
_inBuffer.Free();
IsOkHeaders = (numCdItems == items.Size());
return S_OK;
}
ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size)
{
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> stream(streamSpec);
SeekInArchive(m_ArchiveInfo.Base + position);
streamSpec->SetStream(m_Stream);
streamSpec->Init(size);
return stream.Detach();
}
IInStream* CInArchive::CreateStream()
{
CMyComPtr<IInStream> stream = m_Stream;
return stream.Detach();
}
bool CInArchive::SeekInArchive(UInt64 position)
{
UInt64 newPosition;
if (m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition) != S_OK)
return false;
return (newPosition == position);
}
}}
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdDecoder.cpp
// PpmdDecoder.cpp
// 2009-05-30 : <NAME> : Public domain
#include "StdAfx.h"
#include "Common/Defs.h"
#include "Windows/Defs.h"
#include "PpmdDecoder.h"
namespace NCompress {
namespace NPpmd {
const int kLenIdFinished = -1;
const int kLenIdNeedInit = -2;
STDMETHODIMP CDecoder::SetDecoderProperties2(const Byte *properties, UInt32 size)
{
if (size < 5)
return E_INVALIDARG;
_order = properties[0];
_usedMemorySize = 0;
for (int i = 0; i < 4; i++)
_usedMemorySize += ((UInt32)(properties[1 + i])) << (i * 8);
if (_usedMemorySize > kMaxMemBlockSize)
return E_NOTIMPL;
if (!_rangeDecoder.Create(1 << 20))
return E_OUTOFMEMORY;
if (!_info.SubAllocator.StartSubAllocator(_usedMemorySize))
return E_OUTOFMEMORY;
return S_OK;
}
class CDecoderFlusher
{
CDecoder *_coder;
public:
bool NeedFlush;
CDecoderFlusher(CDecoder *coder): _coder(coder), NeedFlush(true) {}
~CDecoderFlusher()
{
if (NeedFlush)
_coder->Flush();
_coder->ReleaseStreams();
}
};
HRESULT CDecoder::CodeSpec(UInt32 size, Byte *memStream)
{
if (_outSizeDefined)
{
const UInt64 rem = _outSize - _processedSize;
if (size > rem)
size = (UInt32)rem;
}
const UInt32 startSize = size;
if (_remainLen == kLenIdFinished)
return S_OK;
if (_remainLen == kLenIdNeedInit)
{
_rangeDecoder.Init();
_remainLen = 0;
_info.MaxOrder = 0;
_info.StartModelRare(_order);
}
while (size != 0)
{
int symbol = _info.DecodeSymbol(&_rangeDecoder);
if (symbol < 0)
{
_remainLen = kLenIdFinished;
break;
}
if (memStream != 0)
*memStream++ = (Byte)symbol;
else
_outStream.WriteByte((Byte)symbol);
size--;
}
_processedSize += startSize - size;
return S_OK;
}
STDMETHODIMP CDecoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 * /* inSize */, const UInt64 *outSize, ICompressProgressInfo *progress)
{
if (!_outStream.Create(1 << 20))
return E_OUTOFMEMORY;
SetInStream(inStream);
_outStream.SetStream(outStream);
SetOutStreamSize(outSize);
CDecoderFlusher flusher(this);
for (;;)
{
_processedSize = _outStream.GetProcessedSize();
UInt32 curSize = (1 << 18);
RINOK(CodeSpec(curSize, NULL));
if (_remainLen == kLenIdFinished)
break;
if (progress != NULL)
{
UInt64 inSize = _rangeDecoder.GetProcessedSize();
RINOK(progress->SetRatioInfo(&inSize, &_processedSize));
}
if (_outSizeDefined)
if (_outStream.GetProcessedSize() >= _outSize)
break;
}
flusher.NeedFlush = false;
return Flush();
}
#ifdef _NO_EXCEPTIONS
#define PPMD_TRY_BEGIN
#define PPMD_TRY_END
#else
#define PPMD_TRY_BEGIN try {
#define PPMD_TRY_END } \
catch(const CInBufferException &e) { return e.ErrorCode; } \
catch(const COutBufferException &e) { return e.ErrorCode; } \
catch(...) { return S_FALSE; }
#endif
STDMETHODIMP CDecoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
{
PPMD_TRY_BEGIN
return CodeReal(inStream, outStream, inSize, outSize, progress);
PPMD_TRY_END
}
STDMETHODIMP CDecoder::SetInStream(ISequentialInStream *inStream)
{
_rangeDecoder.SetStream(inStream);
return S_OK;
}
STDMETHODIMP CDecoder::ReleaseInStream()
{
_rangeDecoder.ReleaseStream();
return S_OK;
}
STDMETHODIMP CDecoder::SetOutStreamSize(const UInt64 *outSize)
{
_outSizeDefined = (outSize != NULL);
if (_outSizeDefined)
_outSize = *outSize;
_processedSize = 0;
_remainLen = kLenIdNeedInit;
_outStream.Init();
return S_OK;
}
#ifndef NO_READ_FROM_CODER
STDMETHODIMP CDecoder::Read(void *data, UInt32 size, UInt32 *processedSize)
{
PPMD_TRY_BEGIN
if (processedSize)
*processedSize = 0;
const UInt64 startPos = _processedSize;
RINOK(CodeSpec(size, (Byte *)data));
if (processedSize)
*processedSize = (UInt32)(_processedSize - startPos);
return Flush();
PPMD_TRY_END
}
#endif
}}
<file_sep>/SQLCEHelper/Source/SqlCeHelper.cpp
#include "StdAfx.h"
#include "../Include/SqlCeHelper.h"
/*
TO-DO-LIST
**Support to create database file programmatically
**Support to open the database with password
**Support to specify the Open Mode
**Support to load Ole Db without COM registry.
//http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/35db5fb8-443c-4b87-bda7-68fc7df6c6e6
**Support Transactions
**Support Parameters
*/
//http://www.microsoft.com/downloads/details.aspx?FamilyID=1ff0529a-eb1f-4044-b4b7-40b00710f7b7&displaylang=en
//Microsoft SQL Server Compact 3.5 Books Online and Samples
//C:\Program Files\Microsoft SQL Server Compact Edition\v3.5\Devices\wce500\armv4i
//sqlce.ppc.wce5.armv4i.CAB
//sqlce.repl.ppc.wce5.armv4i.CAB
SqlCeHelper::SqlCeHelper(void):
isOpen(false),
currentRowCount(0)
{
}
SqlCeHelper::~SqlCeHelper(void)
{
Close();
}
bool SqlCeHelper::CreateDatabase(const CString& dbPath)
{
HRESULT hr = -1;
DBPROP dbprop[1]; // property used in property set to initialize provider
DBPROPSET dbpropset[1]; // Property Set used to initialize provider
// Initialize environment
//
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if(FAILED(hr))
{
goto Exit;
}
VariantInit(&dbprop[0].vValue);
HANDLE hFind; // File handle
WIN32_FIND_DATA FindFileData; // The file structure description
hFind = FindFirstFile(dbPath, &FindFileData);
if (INVALID_HANDLE_VALUE != hFind)
{
FindClose(hFind);
DeleteDatabase(dbPath);
}
// Initialize a property with name of database
//
dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt = VT_BSTR;
dbprop[0].vValue.bstrVal= SysAllocString(dbPath);
if(NULL == dbprop[0].vValue.bstrVal)
{
goto Exit;
}
// Initialize the property set
//
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties = dbprop;
dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);
hr = dataSource.Create(CLSID_SQLSERVERCE, 1, dbpropset, &session);
if(FAILED(hr))
{
goto Exit;
}
Exit:
VariantClear(&dbprop[0].vValue);
return (hr >= 0);
}
bool SqlCeHelper::DeleteDatabase(const CString& dbPath)
{
BOOL r = DeleteFile(dbPath);
return r?true:false;
}
bool SqlCeHelper::Open(const CString& dbPath)
{
HRESULT hr = -1;
DBPROP dbprop[1]; // property used in property set to initialize provider
DBPROPSET dbpropset[1]; // Property Set used to initialize provider
// Initialize environment
//
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if(FAILED(hr))
{
goto Exit;
}
HANDLE hFind; // File handle
WIN32_FIND_DATA FindFileData; // The file structure description
hFind = FindFirstFile(dbPath, &FindFileData);
if (INVALID_HANDLE_VALUE == hFind)
{
goto Exit;
}
// Initialize a property with name of database
//
dbprop[0].dwPropertyID = DBPROP_INIT_DATASOURCE;
dbprop[0].dwOptions = DBPROPOPTIONS_REQUIRED;
dbprop[0].vValue.vt = VT_BSTR;
dbprop[0].vValue.bstrVal= SysAllocString(dbPath);
if(NULL == dbprop[0].vValue.bstrVal)
{
goto Exit;
}
// Initialize the property set
//
dbpropset[0].guidPropertySet = DBPROPSET_DBINIT;
dbpropset[0].rgProperties = dbprop;
dbpropset[0].cProperties = sizeof(dbprop)/sizeof(dbprop[0]);
hr = dataSource.Open(CLSID_SQLSERVERCE, 1, dbpropset);
if(FAILED(hr))
{
goto Exit;
}
hr = session.Open(dataSource);
if(FAILED(hr))
{
goto Exit;
}
Exit:
VariantClear(&dbprop[0].vValue);
return (hr >= 0);
}
void SqlCeHelper::Close()
{
if(!isOpen)
{
return;
}
CloseReader();
session.Close();
dataSource.Close();
// Uninitialize the environment
CoUninitialize();
isOpen = false;
}
int SqlCeHelper::ExecuteNonQuery(const CString& sql)
{
CCommand command(session);
command.SetText(sql);
LONG rowsAffected;
command.Execute(&rowsAffected);
return (int)rowsAffected;
}
void SqlCeHelper::BeginTransaction()
{
}
void SqlCeHelper::CommitTransaction()
{
}
void SqlCeHelper::RollbackTransaction()
{
}
//Changed from
//ms-help://MS.SSC.v35/MS.SSC.v35.EN/ssctechref/html/a25fafe1-e90a-4545-8836-749dd44135c0.htm
CString SqlCeHelper::GetErrorsMessage()
{
static CString sErrIErrorInfo = L"IErrorInfo interface";
static CString sErrIErrorRecords = L"IErrorRecords interface";
static CString sErrRecordCount = L"error record count";
static CString sErrInfo = L"ERRORINFO structure";
static CString sErrStandardInfo = L"standard error info";
static CString sErrDescription = L"standard error description";
static CString sErrNoSource = L"error source";
HRESULT hr = S_OK;
IErrorInfo *pIErrorInfo = NULL;
IErrorRecords *pIErrorRecords = NULL;
ERRORINFO errorInfo = { 0 };
IErrorInfo *pIErrorInfoRecord = NULL;
CString message = L"";
char str[255];
try
{
// This interface supports returning error information.
// Get the error object from the system for the current
// thread.
hr = GetErrorInfo(0, &pIErrorInfo);
if ( hr == S_FALSE )
{
message = "No error occured.";
return message;
}
if(FAILED(hr) || NULL == pIErrorInfo)
throw sErrIErrorInfo;
// The error records are retrieved from the IIErrorRecords
// interface, which can be obtained from the IErrorInfo
// interface.
hr = pIErrorInfo->QueryInterface(IID_IErrorRecords,
(void **) &pIErrorRecords);
if ( FAILED(hr) || NULL == pIErrorRecords )
throw sErrIErrorRecords;
// The IErrorInfo interface is no longer required because
// we have the IErrorRecords interface, relase it.
pIErrorInfo->Release();
pIErrorInfo = NULL;
ULONG ulNumErrorRecs = 0;
// Determine the number of records in this error object
hr = pIErrorRecords->GetRecordCount(&ulNumErrorRecs);
if ( FAILED(hr) )
throw sErrRecordCount;
// Loop over each error record in the error object to display
// information about each error. Errors are returned.
for (DWORD dwErrorIndex = 0;
dwErrorIndex < ulNumErrorRecs;
dwErrorIndex++)
{
// Retrieve basic error information for this error.
hr = pIErrorRecords->GetBasicErrorInfo(dwErrorIndex,
&errorInfo);
if ( FAILED(hr) )
throw sErrInfo;
TCHAR szCLSID[64] = { 0 };
TCHAR szIID[64] = { 0 };
TCHAR szDISPID[64] = { 0 };
StringFromGUID2(errorInfo.clsid, (LPOLESTR)szCLSID,
sizeof(szCLSID));
StringFromGUID2(errorInfo.iid, (LPOLESTR)szIID,
sizeof(szIID));
sprintf(str, "HRESULT = %lx\n", errorInfo.hrError);
message += str;
sprintf(str, "clsid = %S\n", szCLSID);
message += str;
sprintf(str, "iid = %S\n", szIID);
message += str;
sprintf(str, "dispid = %ld\n", errorInfo.dispid);
message += str;
sprintf(str, "Native Error Code = %lx\n", errorInfo.dwMinor);
message += str;
// Retrieve standard error information for this error.
hr = pIErrorRecords->GetErrorInfo(dwErrorIndex, NULL,
&pIErrorInfoRecord);
if ( FAILED(hr) )
throw sErrStandardInfo;
BSTR bstrDescriptionOfError;
BSTR bstrSourceOfError;
// Get the description of the error.
hr = pIErrorInfoRecord->GetDescription(
&bstrDescriptionOfError);
if ( FAILED(hr) )
throw sErrDescription;
sprintf(str, "Description = %S\n", bstrDescriptionOfError);
message += str;
// Get the source of the error.
hr = pIErrorInfoRecord->GetSource(&bstrSourceOfError);
if ( FAILED(hr) )
throw sErrNoSource;
sprintf(str, "Description = %S\n", bstrSourceOfError);
message += str;
// This interface variable will be used the next time
// though this loop. In the last error case this interface
// is no longer needed so we must release it.
if(NULL != pIErrorInfoRecord)
pIErrorInfoRecord->Release();
pIErrorInfoRecord = NULL;
}
}
catch( CString& szMsg )
{
message = L"Failed to retrieve " + szMsg;
}
if( pIErrorInfoRecord )
pIErrorInfoRecord->Release();
if ( pIErrorInfo )
pIErrorInfo->Release();
if ( pIErrorRecords )
pIErrorRecords->Release();
return message;
}
int SqlCeHelper::ExecuteReader(const CString& sql)
{
CCommand command(session);
command.SetText(sql);
ULONG rows;
command.Execute(rowset);
rowset.GetRowCount(&rows);
currentRowCount = 0;
totalRowCount = (int)rows;
rowset.MoveFirst();
return totalRowCount;
}
bool SqlCeHelper::IsEndOfRecordSet()
{
return (currentRowCount == totalRowCount);
}
void SqlCeHelper::MoveNext()
{
++currentRowCount;
rowset.MoveNext();
}
void SqlCeHelper::CloseReader()
{
currentRowCount = 0;
totalRowCount = 0;
rowset.Close();
}
int SqlCeHelper::GetRowInt(const long ordinal)
{
int i;
rowset.GetValue(ordinal, i);
return i;
}
double SqlCeHelper::GetRowDouble(const long ordinal)
{
double d;
rowset.GetValue(ordinal, d);
return d;
}
CString SqlCeHelper::GetRowStr(const long ordinal)
{
CString s;
rowset.GetValue(ordinal, s);
return s;
}
<file_sep>/SQLCEHelper/Include/BlobStream.h
#ifndef __BLOBSTREAM_H__
#define __BLOBSTREAM_H__
class CBlobStream : public ISequentialStream
{
public:
CBlobStream();
virtual ~CBlobStream();
void Clear();
//
// ISequentialStream interface implementation.
//
virtual HRESULT STDMETHODCALLTYPE QueryInterface(
/* [in] */ REFIID riid,
/* [iid_is][out] */ void __RPC_FAR *__RPC_FAR *ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef( void);
virtual ULONG STDMETHODCALLTYPE Release( void);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Read(
/* [length_is][size_is][out] */ void __RPC_FAR *pv,
/* [in] */ ULONG cb,
/* [out] */ ULONG __RPC_FAR *pcbRead);
virtual /* [local] */ HRESULT STDMETHODCALLTYPE Write(
/* [size_is][in] */ const void __RPC_FAR *pv,
/* [in] */ ULONG cb,
/* [out] */ ULONG __RPC_FAR *pcbWritten);
HRESULT WriteFromStream(IStream *pStream, ULONG cb, ULONG *pcbWritten);
HRESULT WriteFromStream(ISequentialStream *pStream, ULONG cb, ULONG *pcbWritten);
ULONG GetSize () { return m_nLength; }
BYTE* GetData () { return m_pBuffer; }
protected:
BYTE* m_pBuffer;
ULONG m_nLength,
m_iPosRead,
m_iPosWrite,
m_nRef;
DBSTATUS m_dbStatus;
};
#endif<file_sep>/7-Zip/CPP/7zip/Archive/Udf/UdfHandler.h
// Udf/Handler.h
#ifndef __UDF_HANDLER_H
#define __UDF_HANDLER_H
#include "Common/MyCom.h"
#include "../IArchive.h"
#include "UdfIn.h"
namespace NArchive {
namespace NUdf {
struct CRef2
{
int Vol;
int Fs;
int Ref;
};
class CHandler:
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp
{
CMyComPtr<IInStream> _inStream;
CInArchive _archive;
CRecordVector<CRef2> _refs2;
public:
MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/UI/Far/Plugin.cpp
// Plugin.cpp
#include "StdAfx.h"
#include "Common/IntToString.h"
#include "Common/StringConvert.h"
#include "Common/Wildcard.h"
#include "Windows/FileDir.h"
#include "Windows/PropVariantConversions.h"
#include "../Common/PropIDUtils.h"
#include "FarUtils.h"
#include "Messages.h"
#include "Plugin.h"
using namespace NWindows;
using namespace NFar;
CPlugin::CPlugin(const UString &fileName, IInFolderArchive *archiveHandler, UString archiveTypeName):
m_ArchiveHandler(archiveHandler),
m_FileName(fileName),
_archiveTypeName(archiveTypeName)
{
if (!m_FileInfo.Find(m_FileName))
throw "error";
archiveHandler->BindToRootFolder(&_folder);
}
CPlugin::~CPlugin() {}
static void MyGetFileTime(IFolderFolder *anArchiveFolder, UInt32 itemIndex,
PROPID propID, FILETIME &fileTime)
{
NCOM::CPropVariant prop;
if (anArchiveFolder->GetProperty(itemIndex, propID, &prop) != S_OK)
throw 271932;
if (prop.vt == VT_EMPTY)
{
fileTime.dwHighDateTime = 0;
fileTime.dwLowDateTime = 0;
}
else
{
if (prop.vt != VT_FILETIME)
throw 4191730;
fileTime = prop.filetime;
}
}
#define kDotsReplaceString "[[..]]"
#define kDotsReplaceStringU L"[[..]]"
static void CopyStrLimited(char *dest, const AString &src, int len)
{
len--;
if (src.Length() < len)
len = src.Length();
memcpy(dest, src, sizeof(dest[0]) * len);
dest[len] = 0;
}
#define COPY_STR_LIMITED(dest, src) CopyStrLimited(dest, src, sizeof(dest) / sizeof(dest[0]))
void CPlugin::ReadPluginPanelItem(PluginPanelItem &panelItem, UInt32 itemIndex)
{
NCOM::CPropVariant prop;
if (_folder->GetProperty(itemIndex, kpidName, &prop) != S_OK)
throw 271932;
if (prop.vt != VT_BSTR)
throw 272340;
CSysString oemString = UnicodeStringToMultiByte(prop.bstrVal, CP_OEMCP);
if (oemString == "..")
oemString = kDotsReplaceString;
COPY_STR_LIMITED(panelItem.FindData.cFileName, oemString);
panelItem.FindData.cAlternateFileName[0] = 0;
if (_folder->GetProperty(itemIndex, kpidAttrib, &prop) != S_OK)
throw 271932;
if (prop.vt == VT_UI4)
panelItem.FindData.dwFileAttributes = prop.ulVal;
else if (prop.vt == VT_EMPTY)
panelItem.FindData.dwFileAttributes = m_FileInfo.Attrib;
else
throw 21631;
if (_folder->GetProperty(itemIndex, kpidIsDir, &prop) != S_OK)
throw 271932;
if (prop.vt == VT_BOOL)
{
if (VARIANT_BOOLToBool(prop.boolVal))
panelItem.FindData.dwFileAttributes |= FILE_ATTRIBUTE_DIRECTORY;
}
else if (prop.vt != VT_EMPTY)
throw 21632;
if (_folder->GetProperty(itemIndex, kpidSize, &prop) != S_OK)
throw 271932;
UInt64 length;
if (prop.vt == VT_EMPTY)
length = 0;
else
length = ::ConvertPropVariantToUInt64(prop);
panelItem.FindData.nFileSizeLow = (UInt32)length;
panelItem.FindData.nFileSizeHigh = (UInt32)(length >> 32);
MyGetFileTime(_folder, itemIndex, kpidCTime, panelItem.FindData.ftCreationTime);
MyGetFileTime(_folder, itemIndex, kpidATime, panelItem.FindData.ftLastAccessTime);
MyGetFileTime(_folder, itemIndex, kpidMTime, panelItem.FindData.ftLastWriteTime);
if (panelItem.FindData.ftLastWriteTime.dwHighDateTime == 0 &&
panelItem.FindData.ftLastWriteTime.dwLowDateTime == 0)
panelItem.FindData.ftLastWriteTime = m_FileInfo.MTime;
if (_folder->GetProperty(itemIndex, kpidPackSize, &prop) != S_OK)
throw 271932;
if (prop.vt == VT_EMPTY)
length = 0;
else
length = ::ConvertPropVariantToUInt64(prop);
panelItem.PackSize = UInt32(length);
panelItem.PackSizeHigh = UInt32(length >> 32);
panelItem.Flags = 0;
panelItem.NumberOfLinks = 0;
panelItem.Description = NULL;
panelItem.Owner = NULL;
panelItem.CustomColumnData = NULL;
panelItem.CustomColumnNumber = 0;
panelItem.Reserved[0] = 0;
panelItem.Reserved[1] = 0;
panelItem.Reserved[2] = 0;
}
int CPlugin::GetFindData(PluginPanelItem **panelItems, int *itemsNumber, int opMode)
{
// CScreenRestorer screenRestorer;
if ((opMode & OPM_SILENT) == 0 && (opMode & OPM_FIND ) == 0)
{
/*
screenRestorer.Save();
const char *msgItems[]=
{
g_StartupInfo.GetMsgString(NMessageID::kWaitTitle),
g_StartupInfo.GetMsgString(NMessageID::kReadingList)
};
g_StartupInfo.ShowMessage(0, NULL, msgItems,
sizeof(msgItems) / sizeof(msgItems[0]), 0);
*/
}
UInt32 numItems;
_folder->GetNumberOfItems(&numItems);
*panelItems = new PluginPanelItem[numItems];
try
{
for (UInt32 i = 0; i < numItems; i++)
{
PluginPanelItem &panelItem = (*panelItems)[i];
ReadPluginPanelItem(panelItem, i);
panelItem.UserData = i;
}
}
catch(...)
{
delete [](*panelItems);
throw;
}
*itemsNumber = numItems;
return(TRUE);
}
void CPlugin::FreeFindData(struct PluginPanelItem *panelItems, int itemsNumber)
{
for (int i = 0; i < itemsNumber; i++)
if (panelItems[i].Description != NULL)
delete []panelItems[i].Description;
delete []panelItems;
}
void CPlugin::EnterToDirectory(const UString &dirName)
{
CMyComPtr<IFolderFolder> newFolder;
UString s = dirName;
if (dirName == kDotsReplaceStringU)
s = L"..";
_folder->BindToFolder(s, &newFolder);
if (newFolder == NULL)
if (dirName.IsEmpty())
return;
else
throw 40325;
_folder = newFolder;
}
int CPlugin::SetDirectory(const char *aszDir, int /* opMode */)
{
UString path = MultiByteToUnicodeString(aszDir, CP_OEMCP);
if (path == WSTRING_PATH_SEPARATOR)
{
_folder.Release();
m_ArchiveHandler->BindToRootFolder(&_folder);
}
else if (path == L"..")
{
CMyComPtr<IFolderFolder> newFolder;
_folder->BindToParentFolder(&newFolder);
if (newFolder == NULL)
throw 40312;
_folder = newFolder;
}
else if (path.IsEmpty())
EnterToDirectory(path);
else
{
if (path[0] == WCHAR_PATH_SEPARATOR)
{
_folder.Release();
m_ArchiveHandler->BindToRootFolder(&_folder);
path = path.Mid(1);
}
UStringVector pathParts;
SplitPathToParts(path, pathParts);
for (int i = 0; i < pathParts.Size(); i++)
EnterToDirectory(pathParts[i]);
}
GetCurrentDir();
return TRUE;
}
void CPlugin::GetPathParts(UStringVector &pathParts)
{
pathParts.Clear();
CMyComPtr<IFolderFolder> folderItem = _folder;
for (;;)
{
CMyComPtr<IFolderFolder> newFolder;
folderItem->BindToParentFolder(&newFolder);
if (newFolder == NULL)
break;
NCOM::CPropVariant prop;
if (folderItem->GetFolderProperty(kpidName, &prop) == S_OK)
if (prop.vt == VT_BSTR)
pathParts.Insert(0, (const wchar_t *)prop.bstrVal);
folderItem = newFolder;
}
}
void CPlugin::GetCurrentDir()
{
m_CurrentDir.Empty();
UStringVector pathParts;
GetPathParts(pathParts);
for (int i = 0; i < pathParts.Size(); i++)
{
m_CurrentDir += WCHAR_PATH_SEPARATOR;
m_CurrentDir += pathParts[i];
}
}
static char *kPluginFormatName = "7-ZIP";
struct CPROPIDToName
{
PROPID PropID;
int PluginID;
};
static CPROPIDToName kPROPIDToName[] =
{
{ kpidName, NMessageID::kName },
{ kpidExtension, NMessageID::kExtension },
{ kpidIsDir, NMessageID::kIsFolder },
{ kpidSize, NMessageID::kSize },
{ kpidPackSize, NMessageID::kPackSize },
{ kpidAttrib, NMessageID::kAttributes },
{ kpidCTime, NMessageID::kCTime },
{ kpidATime, NMessageID::kATime },
{ kpidMTime, NMessageID::kMTime },
{ kpidSolid, NMessageID::kSolid },
{ kpidCommented, NMessageID::kCommented },
{ kpidEncrypted, NMessageID::kEncrypted },
{ kpidSplitBefore, NMessageID::kSplitBefore },
{ kpidSplitAfter, NMessageID::kSplitAfter },
{ kpidDictionarySize, NMessageID::kDictionarySize },
{ kpidCRC, NMessageID::kCRC },
{ kpidType, NMessageID::kType },
{ kpidIsAnti, NMessageID::kAnti },
{ kpidMethod, NMessageID::kMethod },
{ kpidHostOS, NMessageID::kHostOS },
{ kpidFileSystem, NMessageID::kFileSystem },
{ kpidUser, NMessageID::kUser },
{ kpidGroup, NMessageID::kGroup },
{ kpidBlock, NMessageID::kBlock },
{ kpidComment, NMessageID::kComment },
{ kpidPosition, NMessageID::kPosition },
{ kpidNumSubDirs, NMessageID::kNumSubFolders },
{ kpidNumSubFiles, NMessageID::kNumSubFiles },
{ kpidUnpackVer, NMessageID::kUnpackVer },
{ kpidVolume, NMessageID::kVolume },
{ kpidIsVolume, NMessageID::kIsVolume },
{ kpidOffset, NMessageID::kOffset },
{ kpidLinks, NMessageID::kLinks },
{ kpidNumBlocks, NMessageID::kNumBlocks },
{ kpidNumVolumes, NMessageID::kNumVolumes },
{ kpidBit64, NMessageID::kBit64 },
{ kpidBigEndian, NMessageID::kBigEndian },
{ kpidCpu, NMessageID::kCpu },
{ kpidPhySize, NMessageID::kPhySize },
{ kpidHeadersSize, NMessageID::kHeadersSize },
{ kpidChecksum, NMessageID::kChecksum },
{ kpidCharacts, NMessageID::kCharacts },
{ kpidVa, NMessageID::kVa },
{ kpidId, NMessageID::kId },
{ kpidShortName, NMessageID::kShortName},
{ kpidCreatorApp, NMessageID::kCreatorApp },
{ kpidSectorSize, NMessageID::kSectorSize },
{ kpidPosixAttrib, NMessageID::kPosixAttrib },
{ kpidLink, NMessageID::kLink },
{ kpidTotalSize, NMessageID::kTotalSize },
{ kpidFreeSpace, NMessageID::kFreeSpace },
{ kpidClusterSize, NMessageID::kClusterSize },
{ kpidVolumeName, NMessageID::kLabel }
};
static const int kNumPROPIDToName = sizeof(kPROPIDToName) / sizeof(kPROPIDToName[0]);
static int FindPropertyToName(PROPID propID)
{
for (int i = 0; i < kNumPROPIDToName; i++)
if (kPROPIDToName[i].PropID == propID)
return i;
return -1;
}
/*
struct CPropertyIDInfo
{
PROPID PropID;
const char *FarID;
int Width;
// char CharID;
};
static CPropertyIDInfo kPropertyIDInfos[] =
{
{ kpidName, "N", 0},
{ kpidSize, "S", 8},
{ kpidPackedSize, "P", 8},
{ kpidAttrib, "A", 0},
{ kpidCTime, "DC", 14},
{ kpidATime, "DA", 14},
{ kpidMTime, "DM", 14},
{ kpidSolid, NULL, 0, 'S'},
{ kpidEncrypted, NULL, 0, 'P'}
{ kpidDictionarySize, IDS_PROPERTY_DICTIONARY_SIZE },
{ kpidSplitBefore, NULL, 'B'},
{ kpidSplitAfter, NULL, 'A'},
{ kpidComment, , NULL, 'C'},
{ kpidCRC, IDS_PROPERTY_CRC }
// { kpidType, L"Type" }
};
static const int kNumPropertyIDInfos = sizeof(kPropertyIDInfos) /
sizeof(kPropertyIDInfos[0]);
static int FindPropertyInfo(PROPID propID)
{
for (int i = 0; i < kNumPropertyIDInfos; i++)
if (kPropertyIDInfos[i].PropID == propID)
return i;
return -1;
}
*/
// char *g_Titles[] = { "a", "f", "v" };
/*
static void SmartAddToString(AString &destString, const char *srcString)
{
if (!destString.IsEmpty())
destString += ',';
destString += srcString;
}
*/
/*
void CPlugin::AddColumn(PROPID propID)
{
int index = FindPropertyInfo(propID);
if (index >= 0)
{
for (int i = 0; i < m_ProxyHandler->m_InternalProperties.Size(); i++)
{
const CArchiveItemProperty &aHandlerProperty = m_ProxyHandler->m_InternalProperties[i];
if (aHandlerProperty.ID == propID)
break;
}
if (i == m_ProxyHandler->m_InternalProperties.Size())
return;
const CPropertyIDInfo &propertyIDInfo = kPropertyIDInfos[index];
SmartAddToString(PanelModeColumnTypes, propertyIDInfo.FarID);
char tmp[32];
itoa(propertyIDInfo.Width, tmp, 10);
SmartAddToString(PanelModeColumnWidths, tmp);
return;
}
}
*/
static AString GetNameOfProp(PROPID propID, const wchar_t *name)
{
int index = FindPropertyToName(propID);
if (index < 0)
{
if (name)
return UnicodeStringToMultiByte((const wchar_t *)name, CP_OEMCP);
char s[32];
ConvertUInt64ToString(propID, s);
return s;
}
return g_StartupInfo.GetMsgString(kPROPIDToName[index].PluginID);
}
static AString GetNameOfProp2(PROPID propID, const wchar_t *name)
{
AString s = GetNameOfProp(propID, name);
if (s.Length() > (kInfoPanelLineSize - 1))
s = s.Left(kInfoPanelLineSize - 1);
return s;
}
static AString ConvertSizeToString(UInt64 value)
{
char s[32];
ConvertUInt64ToString(value, s);
int i = MyStringLen(s);
int pos = sizeof(s) / sizeof(s[0]);
s[--pos] = L'\0';
while (i > 3)
{
s[--pos] = s[--i];
s[--pos] = s[--i];
s[--pos] = s[--i];
s[--pos] = ' ';
}
while (i > 0)
s[--pos] = s[--i];
return s + pos;
}
static AString PropToString(const NCOM::CPropVariant &prop, PROPID propID)
{
AString s;
if (prop.vt == VT_BSTR)
s = GetSystemString(prop.bstrVal, CP_OEMCP);
else if (prop.vt == VT_BOOL)
{
int messageID = VARIANT_BOOLToBool(prop.boolVal) ?
NMessageID::kYes : NMessageID::kNo;
return g_StartupInfo.GetMsgString(messageID);
}
else if (prop.vt != VT_EMPTY)
{
if ((
propID == kpidSize ||
propID == kpidPackSize ||
propID == kpidNumSubDirs ||
propID == kpidNumSubFiles ||
propID == kpidNumBlocks ||
propID == kpidPhySize ||
propID == kpidHeadersSize ||
propID == kpidClusterSize
) && (prop.vt == VT_UI8 || prop.vt == VT_UI4))
s = ConvertSizeToString(ConvertPropVariantToUInt64(prop));
else
s = UnicodeStringToMultiByte(ConvertPropertyToString(prop, propID), CP_OEMCP);
}
s.Replace((char)0xA, ' ');
s.Replace((char)0xD, ' ');
return s;
}
static AString PropToString2(const NCOM::CPropVariant &prop, PROPID propID)
{
AString s = PropToString(prop, propID);
if (s.Length() > (kInfoPanelLineSize - 1))
s = s.Left(kInfoPanelLineSize - 1);
return s;
}
void CPlugin::GetOpenPluginInfo(struct OpenPluginInfo *info)
{
info->StructSize = sizeof(*info);
info->Flags = OPIF_USEFILTER | OPIF_USESORTGROUPS| OPIF_USEHIGHLIGHTING|
OPIF_ADDDOTS | OPIF_COMPAREFATTIME;
COPY_STR_LIMITED(m_FileNameBuffer, UnicodeStringToMultiByte(m_FileName, CP_OEMCP));
info->HostFile = m_FileNameBuffer; // test it it is not static
COPY_STR_LIMITED(m_CurrentDirBuffer, UnicodeStringToMultiByte(m_CurrentDir, CP_OEMCP));
info->CurDir = m_CurrentDirBuffer;
info->Format = kPluginFormatName;
UString name;
{
UString fullName;
int index;
NFile::NDirectory::MyGetFullPathName(m_FileName, fullName, index);
name = fullName.Mid(index);
}
m_PannelTitle =
UString(L' ') +
_archiveTypeName +
UString(L':') +
name +
UString(L' ');
if (!m_CurrentDir.IsEmpty())
{
// m_PannelTitle += '\\';
m_PannelTitle += m_CurrentDir;
}
COPY_STR_LIMITED(m_PannelTitleBuffer, UnicodeStringToMultiByte(m_PannelTitle, CP_OEMCP));
info->PanelTitle = m_PannelTitleBuffer;
memset(m_InfoLines, 0, sizeof(m_InfoLines));
MyStringCopy(m_InfoLines[0].Text, "");
m_InfoLines[0].Separator = TRUE;
MyStringCopy(m_InfoLines[1].Text, g_StartupInfo.GetMsgString(NMessageID::kArchiveType));
MyStringCopy(m_InfoLines[1].Data, (const char *)UnicodeStringToMultiByte(_archiveTypeName, CP_OEMCP));
int numItems = 2;
{
CMyComPtr<IFolderProperties> folderProperties;
_folder.QueryInterface(IID_IFolderProperties, &folderProperties);
if (folderProperties)
{
UInt32 numProps;
if (folderProperties->GetNumberOfFolderProperties(&numProps) == S_OK)
{
for (UInt32 i = 0; i < numProps && numItems < kNumInfoLinesMax; i++)
{
CMyComBSTR name;
PROPID propID;
VARTYPE vt;
if (folderProperties->GetFolderPropertyInfo(i, &name, &propID, &vt) != S_OK)
continue;
NCOM::CPropVariant prop;
if (_folder->GetFolderProperty(propID, &prop) != S_OK || prop.vt == VT_EMPTY)
continue;
InfoPanelLine &item = m_InfoLines[numItems++];
COPY_STR_LIMITED(item.Text, GetNameOfProp2(propID, name));
COPY_STR_LIMITED(item.Data, PropToString2(prop, propID));
}
}
}
}
if (numItems < kNumInfoLinesMax)
{
InfoPanelLine &item = m_InfoLines[numItems++];
MyStringCopy(item.Text, "");
MyStringCopy(item.Data, "");
item.Separator = TRUE;
}
{
CMyComPtr<IGetFolderArchiveProperties> getFolderArchiveProperties;
_folder.QueryInterface(IID_IGetFolderArchiveProperties, &getFolderArchiveProperties);
if (getFolderArchiveProperties)
{
CMyComPtr<IFolderArchiveProperties> getProps;
getFolderArchiveProperties->GetFolderArchiveProperties(&getProps);
if (getProps)
{
UInt32 numProps;
if (getProps->GetNumberOfArchiveProperties(&numProps) == S_OK)
{
/*
if (numProps > 0)
message += kSeparator;
*/
for (UInt32 i = 0; i < numProps && numItems < kNumInfoLinesMax; i++)
{
CMyComBSTR name;
PROPID propID;
VARTYPE vt;
if (getProps->GetArchivePropertyInfo(i, &name, &propID, &vt) != S_OK)
continue;
NCOM::CPropVariant prop;
if (getProps->GetArchiveProperty(propID, &prop) != S_OK || prop.vt == VT_EMPTY)
continue;
InfoPanelLine &item = m_InfoLines[numItems++];
COPY_STR_LIMITED(item.Text, GetNameOfProp2(propID, name));
COPY_STR_LIMITED(item.Data, PropToString2(prop, propID));
}
}
}
}
}
//m_InfoLines[1].Separator = 0;
info->InfoLines = m_InfoLines;
info->InfoLinesNumber = numItems;
info->DescrFiles = NULL;
info->DescrFilesNumber = 0;
PanelModeColumnTypes.Empty();
PanelModeColumnWidths.Empty();
/*
AddColumn(kpidName);
AddColumn(kpidSize);
AddColumn(kpidPackedSize);
AddColumn(kpidMTime);
AddColumn(kpidCTime);
AddColumn(kpidATime);
AddColumn(kpidAttrib);
PanelMode.ColumnTypes = (char *)(const char *)PanelModeColumnTypes;
PanelMode.ColumnWidths = (char *)(const char *)PanelModeColumnWidths;
PanelMode.ColumnTitles = NULL;
PanelMode.FullScreen = TRUE;
PanelMode.DetailedStatus = FALSE;
PanelMode.AlignExtensions = FALSE;
PanelMode.CaseConversion = FALSE;
PanelMode.StatusColumnTypes = "N";
PanelMode.StatusColumnWidths = "0";
PanelMode.Reserved[0] = 0;
PanelMode.Reserved[1] = 0;
info->PanelModesArray = &PanelMode;
info->PanelModesNumber = 1;
*/
info->PanelModesArray = NULL;
info->PanelModesNumber = 0;
info->StartPanelMode = 0;
info->StartSortMode = 0;
info->KeyBar = NULL;
info->ShortcutData = NULL;
}
struct CArchiveItemProperty
{
AString Name;
PROPID ID;
VARTYPE Type;
};
HRESULT CPlugin::ShowAttributesWindow()
{
PluginPanelItem pluginPanelItem;
if (!g_StartupInfo.ControlGetActivePanelCurrentItemInfo(pluginPanelItem))
return S_FALSE;
if (strcmp(pluginPanelItem.FindData.cFileName, "..") == 0 &&
NFile::NFind::NAttributes::IsDir(pluginPanelItem.FindData.dwFileAttributes))
return S_FALSE;
int itemIndex = pluginPanelItem.UserData;
CObjectVector<CArchiveItemProperty> properties;
UInt32 numProps;
RINOK(_folder->GetNumberOfProperties(&numProps));
int i;
for (i = 0; i < (int)numProps; i++)
{
CMyComBSTR name;
PROPID propID;
VARTYPE vt;
RINOK(_folder->GetPropertyInfo(i, &name, &propID, &vt));
CArchiveItemProperty prop;
prop.Type = vt;
prop.ID = propID;
if (prop.ID == kpidPath)
prop.ID = kpidName;
prop.Name = GetNameOfProp(propID, name);
properties.Add(prop);
}
int size = 2;
CRecordVector<CInitDialogItem> initDialogItems;
int xSize = 70;
CInitDialogItem idi =
{ DI_DOUBLEBOX, 3, 1, xSize - 4, size - 2, false, false, 0, false, NMessageID::kProperties, NULL, NULL };
initDialogItems.Add(idi);
AStringVector values;
for (i = 0; i < properties.Size(); i++)
{
const CArchiveItemProperty &property = properties[i];
CInitDialogItem idi =
{ DI_TEXT, 5, 3 + i, 0, 0, false, false, 0, false, 0, NULL, NULL };
int index = FindPropertyToName(property.ID);
if (index < 0)
{
idi.DataMessageId = -1;
idi.DataString = property.Name;
}
else
idi.DataMessageId = kPROPIDToName[index].PluginID;
initDialogItems.Add(idi);
NCOM::CPropVariant prop;
RINOK(_folder->GetProperty(itemIndex, property.ID, &prop));
CSysString s = PropToString(prop, property.ID);
values.Add(s);
{
CInitDialogItem idi =
{ DI_TEXT, 30, 3 + i, 0, 0, false, false, 0, false, -1, NULL, NULL };
initDialogItems.Add(idi);
}
}
int numLines = values.Size();
for (i = 0; i < numLines; i++)
{
CInitDialogItem &idi = initDialogItems[1 + i * 2 + 1];
idi.DataString = values[i];
}
int numDialogItems = initDialogItems.Size();
CRecordVector<FarDialogItem> dialogItems;
dialogItems.Reserve(numDialogItems);
for (i = 0; i < numDialogItems; i++)
dialogItems.Add(FarDialogItem());
g_StartupInfo.InitDialogItems(&initDialogItems.Front(),
&dialogItems.Front(), numDialogItems);
int maxLen = 0;
for (i = 0; i < numLines; i++)
{
FarDialogItem &dialogItem = dialogItems[1 + i * 2];
int len = (int)strlen(dialogItem.Data);
if (len > maxLen)
maxLen = len;
}
int maxLen2 = 0;
const int kSpace = 10;
for (i = 0; i < numLines; i++)
{
FarDialogItem &dialogItem = dialogItems[1 + i * 2 + 1];
int len = (int)strlen(dialogItem.Data);
if (len > maxLen2)
maxLen2 = len;
dialogItem.X1 = maxLen + kSpace;
}
size = numLines + 6;
xSize = maxLen + kSpace + maxLen2 + 5;
FarDialogItem &firstDialogItem = dialogItems.Front();
firstDialogItem.Y2 = size - 2;
firstDialogItem.X2 = xSize - 4;
/* int askCode = */ g_StartupInfo.ShowDialog(xSize, size, NULL, &dialogItems.Front(), numDialogItems);
return S_OK;
}
int CPlugin::ProcessKey(int key, unsigned int controlState)
{
if (controlState == PKF_CONTROL && key == 'A')
{
HRESULT result = ShowAttributesWindow();
if (result == S_OK)
return TRUE;
if (result == S_FALSE)
return FALSE;
throw "Error";
}
if ((controlState & PKF_ALT) != 0 && key == VK_F6)
{
UString folderPath;
if (!NFile::NDirectory::GetOnlyDirPrefix(m_FileName, folderPath))
return FALSE;
PanelInfo panelInfo;
g_StartupInfo.ControlGetActivePanelInfo(panelInfo);
GetFilesReal(panelInfo.SelectedItems,
panelInfo.SelectedItemsNumber, FALSE,
UnicodeStringToMultiByte(folderPath, CP_OEMCP), OPM_SILENT, true);
g_StartupInfo.Control(this, FCTL_UPDATEPANEL, NULL);
g_StartupInfo.Control(this, FCTL_REDRAWPANEL, NULL);
g_StartupInfo.Control(this, FCTL_UPDATEANOTHERPANEL, NULL);
g_StartupInfo.Control(this, FCTL_REDRAWANOTHERPANEL, NULL);
return TRUE;
}
return FALSE;
}
<file_sep>/FingerSuite/FingerMenuDLL/InterceptEngine.h
#ifndef _INTERCEPT_ENGINE_H_
#define _INTERCEPT_ENGINE_H_
//Redefinitions for some CE internal structures and undocumented APIs
#include "hook\SysDecls.h"
#define UWM_INTERCEPT_MENU_MSG _T("UWM_INTERCEPT_MENU_MSG-44E531B1_14D3_11d5_A025_006067718D04")
#define UWM_INTERCEPT_MSGBOX_MSG _T("UWM_INTERCEPT_MSGBOX_MSG-44E531B1_14D3_11d5_A025_006067718D04")
#define UWM_INTERCEPT_NOTIF_MSG _T("UWM_INTERCEPT_NOTIF_MSG-44E531B1_14D3_11d5_A025_006067718D04")
#define UWM_NOTIF_POPUP_MSG _T("UWM_NOTIF_POPUP_MSG-44E531B1_14D3_11d5_A025_006067718D04")
#define EVT_FNGRMENU _T("FNGRMENUWAITEVT")
#define EVT_FNGRMSGBOX _T("FNGRMSGBOXWAITEVT")
#define NOTIF_ADD 1
#define NOTIF_UPD 2
#define NOTIF_DEL 3
/*
struct HookedAPI holds information for one system API,
which is hooked by us.
*/
struct HookedAPI
{
BOOL m_bUsed;
BOOL m_bSwapped;
int m_iOrigApiSetId;
CINFO * m_pOrigApiSet;
CINFO * m_pOurApiSet;
};
struct ProcessInfo
{
DWORD dwID;
DWORD dwTrust;
HINSTANCE hSpyDllLoaded;
WCHAR szExeFile[_MAX_PATH]; //Points into array m_szExeFile
};
typedef struct tagTRACKPOPUPMENUINFO
{
HMENU hMenu;
UINT uFlags;
HWND hWnd;
} TRACKPOPUPMENUINFO, *LPTRACKPOPUPMENUINFO;
typedef struct tagMSGBOXINFO
{
HWND hWnd;
UINT uType;
WCHAR szCaption[128];
WCHAR szText[1024];
} MSGBOXINFO, *LPMSGBOXINFO;
typedef struct tagNOTIFICATIONINFO
{
SHNOTIFICATIONDATA nd;
WCHAR szTitle[256];
WCHAR szHTML[512];
SOFTKEYCMD rgskc[30];
WCHAR sk1Title[50];
WCHAR sk2Title[50];
DWORD grfFlagsOriginal;
BOOL isManaged;
} NOTIFICATIONINFO, *LPNOTIFICATIONINFO;
#define MANAGED_NOTIF_SIZE 7
WCHAR g_szManagedNotificationCLSID[MANAGED_NOTIF_SIZE][39] =
{
L"{a877d65b-239c-47a7-9304-0d347f580408}", // new text message
L"{a877d660-239c-47a7-9304-0d347f580408}", // missed call
L"{f528c2e3-17da-4248-88dd-38c4cdcf0d20}", // customer experience
L"{15f11f90-8a5f-454c-89fc-ba9b7aab0cad}", // reminder
L"{a877d663-239c-47a7-9304-0d347f580408}", // main battery very low
L"{1ee011d2-f265-4214-a4ed-f0ea2e827f2a}", // bluetooth utiliry
L"{0d3132c4-1298-469c-b2b8-f28ce2d649d0}" // bluetooth 1
};
extern "C" __declspec(dllexport) BOOL SetHWndServer(HWND hWndServer);
extern "C" __declspec(dllexport) BOOL SetHWndServerMsgBox(HWND hWndServer);
extern "C" __declspec(dllexport) BOOL StartHookOnServer();
extern "C" __declspec(dllexport) BOOL StartHookOnShellServer();
extern "C" __declspec(dllexport) BOOL StopHookOnServer();
extern "C" __declspec(dllexport) BOOL InstallHook();
extern "C" __declspec(dllexport) BOOL InstallHookOnShell();
extern "C" __declspec(dllexport) BOOL RemoveHook();
extern "C" __declspec(dllexport) BOOL SignalWaitEvent(LPTSTR szEvt);
extern "C" __declspec(dllexport) void SetTrackPopupMenuExResult(int bResult);
extern "C" __declspec(dllexport) void SetMsgBoxResult(int iResult);
extern "C" __declspec(dllexport) BOOL SetHWndServerNotif(HWND hWndServer);
extern "C" __declspec(dllexport) BOOL StartHookOnSIP();
extern "C" __declspec(dllexport) BOOL StopHookOnSIP();
extern "C" __declspec(dllexport) BOOL InstallHookOnSIP();
extern "C" __declspec(dllexport) BOOL StartHookOnHHTaskBar();
extern "C" __declspec(dllexport) BOOL InstallHookOnHHTaskBar();
extern "C" __declspec(dllexport) BOOL IsManagedNotification(REFCLSID clsid);
#endif // _INTERCEPT_ENGINE_H_<file_sep>/7-Zip/CPP/7zip/Archive/CpioHandler.cpp
// CpioHandler.cpp
#include "StdAfx.h"
#include "Common/ComTry.h"
#include "Common/StringToInt.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"
#include "../Compress/CopyCoder.h"
#include "Common/ItemNameUtils.h"
namespace NArchive {
namespace NCpio {
namespace NFileHeader
{
namespace NMagic
{
extern const char *kMagic1 = "070701";
extern const char *kMagic2 = "070702";
extern const char *kMagic3 = "070707";
extern const char *kEndName = "TRAILER!!!";
const Byte kMagicForRecord2[2] = { 0xC7, 0x71 };
}
const UInt32 kRecord2Size = 26;
/*
struct CRecord2
{
unsigned short c_magic;
short c_dev;
unsigned short c_ino;
unsigned short c_mode;
unsigned short c_uid;
unsigned short c_gid;
unsigned short c_nlink;
short c_rdev;
unsigned short c_mtimes[2];
unsigned short c_namesize;
unsigned short c_filesizes[2];
};
*/
const UInt32 kRecordSize = 110;
/*
struct CRecord
{
char Magic[6]; // "070701" for "new" portable format, "070702" for CRC format
char inode[8];
char Mode[8];
char UID[8];
char GID[8];
char nlink[8];
char mtime[8];
char Size[8]; // must be 0 for FIFOs and directories
char DevMajor[8];
char DevMinor[8];
char RDevMajor[8]; //only valid for chr and blk special files
char RDevMinor[8]; //only valid for chr and blk special files
char NameSize[8]; // count includes terminating NUL in pathname
char ChkSum[8]; // 0 for "new" portable format; for CRC format the sum of all the bytes in the file
bool CheckMagic() const
{ return memcmp(Magic, NMagic::kMagic1, 6) == 0 ||
memcmp(Magic, NMagic::kMagic2, 6) == 0; };
};
*/
const UInt32 kOctRecordSize = 76;
}
struct CItem
{
AString Name;
UInt32 inode;
UInt32 Mode;
UInt32 UID;
UInt32 GID;
UInt32 Size;
UInt32 MTime;
// char LinkFlag;
// AString LinkName; ?????
char Magic[8];
UInt32 NumLinks;
UInt32 DevMajor;
UInt32 DevMinor;
UInt32 RDevMajor;
UInt32 RDevMinor;
UInt32 ChkSum;
UInt32 Align;
bool IsDir() const { return (Mode & 0170000) == 0040000; }
};
class CItemEx: public CItem
{
public:
UInt64 HeaderPosition;
UInt32 HeaderSize;
UInt64 GetDataPosition() const { return HeaderPosition + HeaderSize; };
};
const UInt32 kMaxBlockSize = NFileHeader::kRecordSize;
class CInArchive
{
CMyComPtr<IInStream> m_Stream;
UInt64 m_Position;
UInt16 _blockSize;
Byte _block[kMaxBlockSize];
UInt32 _blockPos;
Byte ReadByte();
UInt16 ReadUInt16();
UInt32 ReadUInt32();
bool ReadNumber(UInt32 &resultValue);
bool ReadOctNumber(int size, UInt32 &resultValue);
HRESULT ReadBytes(void *data, UInt32 size, UInt32 &processedSize);
public:
HRESULT Open(IInStream *inStream);
HRESULT GetNextItem(bool &filled, CItemEx &itemInfo);
HRESULT Skip(UInt64 numBytes);
HRESULT SkipDataRecords(UInt64 dataSize, UInt32 align);
};
HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 &processedSize)
{
size_t realProcessedSize = size;
RINOK(ReadStream(m_Stream, data, &realProcessedSize));
processedSize = (UInt32)realProcessedSize;
m_Position += processedSize;
return S_OK;
}
Byte CInArchive::ReadByte()
{
if (_blockPos >= _blockSize)
throw "Incorrect cpio archive";
return _block[_blockPos++];
}
UInt16 CInArchive::ReadUInt16()
{
UInt16 value = 0;
for (int i = 0; i < 2; i++)
{
Byte b = ReadByte();
value |= (UInt16(b) << (8 * i));
}
return value;
}
UInt32 CInArchive::ReadUInt32()
{
UInt32 value = 0;
for (int i = 0; i < 4; i++)
{
Byte b = ReadByte();
value |= (UInt32(b) << (8 * i));
}
return value;
}
HRESULT CInArchive::Open(IInStream *inStream)
{
RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &m_Position));
m_Stream = inStream;
return S_OK;
}
bool CInArchive::ReadNumber(UInt32 &resultValue)
{
resultValue = 0;
for (int i = 0; i < 8; i++)
{
char c = char(ReadByte());
int d;
if (c >= '0' && c <= '9')
d = c - '0';
else if (c >= 'A' && c <= 'F')
d = 10 + c - 'A';
else if (c >= 'a' && c <= 'f')
d = 10 + c - 'a';
else
return false;
resultValue *= 0x10;
resultValue += d;
}
return true;
}
static bool OctalToNumber(const char *s, UInt64 &res)
{
const char *end;
res = ConvertOctStringToUInt64(s, &end);
return (*end == ' ' || *end == 0);
}
static bool OctalToNumber32(const char *s, UInt32 &res)
{
UInt64 res64;
if (!OctalToNumber(s, res64))
return false;
res = (UInt32)res64;
return (res64 <= 0xFFFFFFFF);
}
bool CInArchive::ReadOctNumber(int size, UInt32 &resultValue)
{
char sz[32 + 4];
int i;
for (i = 0; i < size && i < 32; i++)
sz[i] = (char)ReadByte();
sz[i] = 0;
return OctalToNumber32(sz, resultValue);
}
#define GetFromHex(y) { if (!ReadNumber(y)) return S_FALSE; }
#define GetFromOct6(y) { if (!ReadOctNumber(6, y)) return S_FALSE; }
#define GetFromOct11(y) { if (!ReadOctNumber(11, y)) return S_FALSE; }
static unsigned short ConvertValue(unsigned short value, bool convert)
{
if (!convert)
return value;
return (unsigned short)((((unsigned short)(value & 0xFF)) << 8) | (value >> 8));
}
static UInt32 GetAlignedSize(UInt32 size, UInt32 align)
{
while ((size & (align - 1)) != 0)
size++;
return size;
}
HRESULT CInArchive::GetNextItem(bool &filled, CItemEx &item)
{
filled = false;
UInt32 processedSize;
item.HeaderPosition = m_Position;
_blockSize = kMaxBlockSize;
RINOK(ReadBytes(_block, 2, processedSize));
if (processedSize != 2)
return S_FALSE;
_blockPos = 0;
UInt32 nameSize;
bool oldBE =
_block[0] == NFileHeader::NMagic::kMagicForRecord2[1] &&
_block[1] == NFileHeader::NMagic::kMagicForRecord2[0];
bool binMode = (_block[0] == NFileHeader::NMagic::kMagicForRecord2[0] &&
_block[1] == NFileHeader::NMagic::kMagicForRecord2[1]) ||
oldBE;
if (binMode)
{
RINOK(ReadBytes(_block + 2, NFileHeader::kRecord2Size - 2, processedSize));
if (processedSize != NFileHeader::kRecord2Size - 2)
return S_FALSE;
item.Align = 2;
_blockPos = 2;
item.DevMajor = 0;
item.DevMinor = ConvertValue(ReadUInt16(), oldBE);
item.inode = ConvertValue(ReadUInt16(), oldBE);
item.Mode = ConvertValue(ReadUInt16(), oldBE);
item.UID = ConvertValue(ReadUInt16(), oldBE);
item.GID = ConvertValue(ReadUInt16(), oldBE);
item.NumLinks = ConvertValue(ReadUInt16(), oldBE);
item.RDevMajor =0;
item.RDevMinor = ConvertValue(ReadUInt16(), oldBE);
UInt16 timeHigh = ConvertValue(ReadUInt16(), oldBE);
UInt16 timeLow = ConvertValue(ReadUInt16(), oldBE);
item.MTime = (UInt32(timeHigh) << 16) + timeLow;
nameSize = ConvertValue(ReadUInt16(), oldBE);
UInt16 sizeHigh = ConvertValue(ReadUInt16(), oldBE);
UInt16 sizeLow = ConvertValue(ReadUInt16(), oldBE);
item.Size = (UInt32(sizeHigh) << 16) + sizeLow;
item.ChkSum = 0;
item.HeaderSize = GetAlignedSize(
nameSize + NFileHeader::kRecord2Size, item.Align);
nameSize = item.HeaderSize - NFileHeader::kRecord2Size;
}
else
{
RINOK(ReadBytes(_block + 2, 4, processedSize));
if (processedSize != 4)
return S_FALSE;
bool magicOK =
memcmp(_block, NFileHeader::NMagic::kMagic1, 6) == 0 ||
memcmp(_block, NFileHeader::NMagic::kMagic2, 6) == 0;
_blockPos = 6;
if (magicOK)
{
RINOK(ReadBytes(_block + 6, NFileHeader::kRecordSize - 6, processedSize));
if (processedSize != NFileHeader::kRecordSize - 6)
return S_FALSE;
item.Align = 4;
GetFromHex(item.inode);
GetFromHex(item.Mode);
GetFromHex(item.UID);
GetFromHex(item.GID);
GetFromHex(item.NumLinks);
UInt32 mTime;
GetFromHex(mTime);
item.MTime = mTime;
GetFromHex(item.Size);
GetFromHex(item.DevMajor);
GetFromHex(item.DevMinor);
GetFromHex(item.RDevMajor);
GetFromHex(item.RDevMinor);
GetFromHex(nameSize);
GetFromHex(item.ChkSum);
item.HeaderSize = GetAlignedSize(
nameSize + NFileHeader::kRecordSize, item.Align);
nameSize = item.HeaderSize - NFileHeader::kRecordSize;
}
else
{
if (!memcmp(_block, NFileHeader::NMagic::kMagic3, 6) == 0)
return S_FALSE;
RINOK(ReadBytes(_block + 6, NFileHeader::kOctRecordSize - 6, processedSize));
if (processedSize != NFileHeader::kOctRecordSize - 6)
return S_FALSE;
item.Align = 1;
item.DevMajor = 0;
GetFromOct6(item.DevMinor);
GetFromOct6(item.inode);
GetFromOct6(item.Mode);
GetFromOct6(item.UID);
GetFromOct6(item.GID);
GetFromOct6(item.NumLinks);
item.RDevMajor = 0;
GetFromOct6(item.RDevMinor);
UInt32 mTime;
GetFromOct11(mTime);
item.MTime = mTime;
GetFromOct6(nameSize);
GetFromOct11(item.Size); // ?????
item.HeaderSize = GetAlignedSize(
nameSize + NFileHeader::kOctRecordSize, item.Align);
nameSize = item.HeaderSize - NFileHeader::kOctRecordSize;
}
}
if (nameSize == 0 || nameSize >= (1 << 27))
return E_FAIL;
RINOK(ReadBytes(item.Name.GetBuffer(nameSize), nameSize, processedSize));
if (processedSize != nameSize)
return E_FAIL;
item.Name.ReleaseBuffer();
if (strcmp(item.Name, NFileHeader::NMagic::kEndName) == 0)
return S_OK;
filled = true;
return S_OK;
}
HRESULT CInArchive::Skip(UInt64 numBytes)
{
UInt64 newPostion;
RINOK(m_Stream->Seek(numBytes, STREAM_SEEK_CUR, &newPostion));
m_Position += numBytes;
if (m_Position != newPostion)
return E_FAIL;
return S_OK;
}
HRESULT CInArchive::SkipDataRecords(UInt64 dataSize, UInt32 align)
{
while ((dataSize & (align - 1)) != 0)
dataSize++;
return Skip(dataSize);
}
class CHandler:
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp
{
CObjectVector<CItemEx> _items;
CMyComPtr<IInStream> _stream;
public:
MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};
/*
enum
{
kpidinode = kpidUserDefined,
kpidiChkSum
};
*/
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidIsDir, VT_BOOL},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidPosixAttrib, VT_UI4},
// { L"inode", kpidinode, VT_UI4}
// { L"CheckSum", kpidiChkSum, VT_UI4}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps_NO
STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)
{
COM_TRY_BEGIN
// try
{
CInArchive archive;
UInt64 endPos = 0;
bool needSetTotal = true;
if (callback != NULL)
{
RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos));
RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
}
RINOK(archive.Open(stream));
_items.Clear();
for (;;)
{
CItemEx item;
bool filled;
HRESULT result = archive.GetNextItem(filled, item);
if (result == S_FALSE)
return S_FALSE;
if (result != S_OK)
return S_FALSE;
if (!filled)
break;
_items.Add(item);
archive.SkipDataRecords(item.Size, item.Align);
if (callback != NULL)
{
if (needSetTotal)
{
RINOK(callback->SetTotal(NULL, &endPos));
needSetTotal = false;
}
if (_items.Size() % 100 == 0)
{
UInt64 numFiles = _items.Size();
UInt64 numBytes = item.HeaderPosition;
RINOK(callback->SetCompleted(&numFiles, &numBytes));
}
}
}
if (_items.Size() == 0)
return S_FALSE;
_stream = stream;
}
/*
catch(...)
{
return S_FALSE;
}
*/
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_items.Clear();
_stream.Release();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _items.Size();
return S_OK;
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CItemEx &item = _items[index];
switch(propID)
{
case kpidPath: prop = NItemName::GetOSName(MultiByteToUnicodeString(item.Name, CP_OEMCP)); break;
case kpidIsDir: prop = item.IsDir(); break;
case kpidSize:
case kpidPackSize:
prop = (UInt64)item.Size;
break;
case kpidMTime:
{
if (item.MTime != 0)
{
FILETIME utc;
NWindows::NTime::UnixTimeToFileTime(item.MTime, utc);
prop = utc;
}
break;
}
case kpidPosixAttrib: prop = item.Mode; break;
/*
case kpidinode: prop = item.inode; break;
case kpidiChkSum: prop = item.ChkSum; break;
*/
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _items.Size();
if (numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
totalSize += _items[allFilesMode ? i : indices[i]].Size;
extractCallback->SetTotal(totalSize);
UInt64 currentTotalSize = 0;
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
streamSpec->SetStream(_stream);
for (i = 0; i < numItems; i++)
{
lps->InSize = lps->OutSize = currentTotalSize;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> outStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
Int32 index = allFilesMode ? i : indices[i];
const CItemEx &item = _items[index];
RINOK(extractCallback->GetStream(index, &outStream, askMode));
currentTotalSize += item.Size;
if (item.IsDir())
{
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
if (!testMode && !outStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
if (testMode)
{
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
RINOK(_stream->Seek(item.GetDataPosition(), STREAM_SEEK_SET, NULL));
streamSpec->Init(item.Size);
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
outStream.Release();
RINOK(extractCallback->SetOperationResult((copyCoderSpec->TotalSize == item.Size) ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kDataError));
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
COM_TRY_BEGIN
const CItemEx &item = _items[index];
return CreateLimitedInStream(_stream, item.GetDataPosition(), item.Size, stream);
COM_TRY_END
}
static IInArchive *CreateArc() { return new NArchive::NCpio::CHandler; }
static CArcInfo g_ArcInfo =
{ L"Cpio", L"cpio", 0, 0xED, { 0 }, 0, false, CreateArc, 0 };
REGISTER_ARC(Cpio)
}}
<file_sep>/SQLCEHelper/Source/DbMemory.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
// CDbMemory::Free(DBPROP* pProp)
//
// Frees a single DBPROP value
//
void CDbMemory::Free(DBPROP* pProp)
{
ATLASSERT(pProp != NULL);
VariantClear(&pProp->vValue);
Free(pProp->colid);
}
// CDbMemory::Free
//
// Frees a provider-allocated DBPROPSET
//
void CDbMemory::Free(DBPROPSET* pPropSet)
{
ULONG iProp;
ATLASSERT(pPropSet != NULL);
for(iProp = 0; iProp < pPropSet->cProperties; ++iProp)
Free(&pPropSet->rgProperties[iProp]);
if(pPropSet->rgProperties != NULL)
CoTaskMemFree(pPropSet->rgProperties);
}
void CDbMemory::Free(DBID &dbid)
{
switch(dbid.eKind)
{
case DBKIND_GUID_NAME:
if(dbid.uName.pwszName != NULL)
CoTaskMemFree(dbid.uName.pwszName);
break;
case DBKIND_NAME:
if(dbid.uName.pwszName != NULL)
CoTaskMemFree(dbid.uName.pwszName);
break;
case DBKIND_PGUID_NAME:
if(dbid.uName.pwszName != NULL)
CoTaskMemFree(dbid.uName.pwszName);
if(dbid.uGuid.pguid != NULL)
CoTaskMemFree(dbid.uGuid.pguid);
break;
case DBKIND_PGUID_PROPID:
if(dbid.uGuid.pguid != NULL)
CoTaskMemFree(dbid.uGuid.pguid);
break;
}
}
void CDbMemory::Free(DBINDEXCOLUMNDESC *pKeyColumnDesc, ULONG nKeys)
{
ULONG i;
for(i = 0; i < nKeys; ++i)
Free(*pKeyColumnDesc[i].pColumnID);
CoTaskMemFree(pKeyColumnDesc);
}
<file_sep>/7-Zip/CPP/7zip/Archive/Rar/RarHandler.cpp
// RarHandler.cpp
#include "StdAfx.h"
#include "Common/ComTry.h"
#include "Common/IntToString.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../../IPassword.h"
#include "../../Common/CreateCoder.h"
#include "../../Common/FilterCoder.h"
#include "../../Common/MethodId.h"
#include "../../Common/ProgressUtils.h"
#include "../../Compress/CopyCoder.h"
#include "../../Crypto/Rar20Crypto.h"
#include "../../Crypto/RarAes.h"
#include "../Common/ItemNameUtils.h"
#include "../Common/OutStreamWithCRC.h"
#include "RarHandler.h"
using namespace NWindows;
using namespace NTime;
namespace NArchive {
namespace NRar {
static const wchar_t *kHostOS[] =
{
L"MS DOS",
L"OS/2",
L"Win32",
L"Unix",
L"Mac OS",
L"BeOS"
};
static const int kNumHostOSes = sizeof(kHostOS) / sizeof(kHostOS[0]);
static const wchar_t *kUnknownOS = L"Unknown";
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidIsDir, VT_BOOL},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidATime, VT_FILETIME},
{ NULL, kpidAttrib, VT_UI4},
{ NULL, kpidEncrypted, VT_BOOL},
{ NULL, kpidSolid, VT_BOOL},
{ NULL, kpidCommented, VT_BOOL},
{ NULL, kpidSplitBefore, VT_BOOL},
{ NULL, kpidSplitAfter, VT_BOOL},
{ NULL, kpidCRC, VT_UI4},
{ NULL, kpidHostOS, VT_BSTR},
{ NULL, kpidMethod, VT_BSTR},
{ NULL, kpidUnpackVer, VT_UI1}
};
STATPROPSTG kArcProps[] =
{
{ NULL, kpidSolid, VT_BOOL},
{ NULL, kpidNumBlocks, VT_UI4},
// { NULL, kpidEncrypted, VT_BOOL},
{ NULL, kpidIsVolume, VT_BOOL},
{ NULL, kpidNumVolumes, VT_UI4},
{ NULL, kpidPhySize, VT_UI8}
// { NULL, kpidCommented, VT_BOOL}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
UInt64 CHandler::GetPackSize(int refIndex) const
{
const CRefItem &refItem = _refItems[refIndex];
UInt64 totalPackSize = 0;
for (int i = 0; i < refItem.NumItems; i++)
totalPackSize += _items[refItem.ItemIndex + i].PackSize;
return totalPackSize;
}
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
// COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
switch(propID)
{
case kpidSolid: prop = _archiveInfo.IsSolid(); break;
// case kpidEncrypted: prop = _archiveInfo.IsEncrypted(); break; // it's for encrypted names.
case kpidIsVolume: prop = _archiveInfo.IsVolume(); break;
case kpidNumVolumes: prop = (UInt32)_archives.Size(); break;
case kpidOffset: if (_archiveInfo.StartPosition != 0) prop = _archiveInfo.StartPosition; break;
// case kpidCommented: prop = _archiveInfo.IsCommented(); break;
case kpidNumBlocks:
{
UInt32 numBlocks = 0;
for (int i = 0; i < _refItems.Size(); i++)
if (!IsSolid(i))
numBlocks++;
prop = (UInt32)numBlocks;
break;
}
}
prop.Detach(value);
return S_OK;
// COM_TRY_END
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _refItems.Size();
return S_OK;
}
static bool RarTimeToFileTime(const CRarTime &rarTime, FILETIME &result)
{
if (!DosTimeToFileTime(rarTime.DosTime, result))
return false;
UInt64 value = (((UInt64)result.dwHighDateTime) << 32) + result.dwLowDateTime;
value += (UInt64)rarTime.LowSecond * 10000000;
value += ((UInt64)rarTime.SubTime[2] << 16) +
((UInt64)rarTime.SubTime[1] << 8) +
((UInt64)rarTime.SubTime[0]);
result.dwLowDateTime = (DWORD)value;
result.dwHighDateTime = DWORD(value >> 32);
return true;
}
static void RarTimeToProp(const CRarTime &rarTime, NWindows::NCOM::CPropVariant &prop)
{
FILETIME localFileTime, utcFileTime;
if (RarTimeToFileTime(rarTime, localFileTime))
{
if (!LocalFileTimeToFileTime(&localFileTime, &utcFileTime))
utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0;
}
else
utcFileTime.dwHighDateTime = utcFileTime.dwLowDateTime = 0;
prop = utcFileTime;
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CRefItem &refItem = _refItems[index];
const CItemEx &item = _items[refItem.ItemIndex];
switch(propID)
{
case kpidPath:
{
UString u;
if (item.HasUnicodeName() && !item.UnicodeName.IsEmpty())
u = item.UnicodeName;
else
u = MultiByteToUnicodeString(item.Name, CP_OEMCP);
prop = (const wchar_t *)NItemName::WinNameToOSName(u);
break;
}
case kpidIsDir: prop = item.IsDir(); break;
case kpidSize: prop = item.Size; break;
case kpidPackSize: prop = GetPackSize(index); break;
case kpidMTime: RarTimeToProp(item.MTime, prop); break;
case kpidCTime: if (item.CTimeDefined) RarTimeToProp(item.CTime, prop); break;
case kpidATime: if (item.ATimeDefined) RarTimeToProp(item.ATime, prop); break;
case kpidAttrib: prop = item.GetWinAttributes(); break;
case kpidEncrypted: prop = item.IsEncrypted(); break;
case kpidSolid: prop = IsSolid(index); break;
case kpidCommented: prop = item.IsCommented(); break;
case kpidSplitBefore: prop = item.IsSplitBefore(); break;
case kpidSplitAfter: prop = _items[refItem.ItemIndex + refItem.NumItems - 1].IsSplitAfter(); break;
case kpidCRC:
{
const CItemEx &lastItem = _items[refItem.ItemIndex + refItem.NumItems - 1];
prop = ((lastItem.IsSplitAfter()) ? item.FileCRC : lastItem.FileCRC);
break;
}
case kpidUnpackVer: prop = item.UnPackVersion; break;
case kpidMethod:
{
UString method;
if (item.Method >= Byte('0') && item.Method <= Byte('5'))
{
method = L"m";
wchar_t temp[32];
ConvertUInt64ToString(item.Method - Byte('0'), temp);
method += temp;
if (!item.IsDir())
{
method += L":";
ConvertUInt64ToString(16 + item.GetDictSize(), temp);
method += temp;
}
}
else
{
wchar_t temp[32];
ConvertUInt64ToString(item.Method, temp);
method += temp;
}
prop = method;
break;
}
case kpidHostOS: prop = (item.HostOS < kNumHostOSes) ? (kHostOS[item.HostOS]) : kUnknownOS; break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
class CVolumeName
{
bool _first;
bool _newStyle;
UString _unchangedPart;
UString _changedPart;
UString _afterPart;
public:
CVolumeName(): _newStyle(true) {};
bool InitName(const UString &name, bool newStyle)
{
_first = true;
_newStyle = newStyle;
int dotPos = name.ReverseFind('.');
UString basePart = name;
if (dotPos >= 0)
{
UString ext = name.Mid(dotPos + 1);
if (ext.CompareNoCase(L"rar") == 0)
{
_afterPart = name.Mid(dotPos);
basePart = name.Left(dotPos);
}
else if (ext.CompareNoCase(L"exe") == 0)
{
_afterPart = L".rar";
basePart = name.Left(dotPos);
}
else if (!_newStyle)
{
if (ext.CompareNoCase(L"000") == 0 ||
ext.CompareNoCase(L"001") == 0 ||
ext.CompareNoCase(L"r00") == 0 ||
ext.CompareNoCase(L"r01") == 0)
{
_afterPart.Empty();
_first = false;
_changedPart = ext;
_unchangedPart = name.Left(dotPos + 1);
return true;
}
}
}
if (!_newStyle)
{
_afterPart.Empty();
_unchangedPart = basePart + UString(L".");
_changedPart = L"r00";
return true;
}
int numLetters = 1;
if (basePart.Right(numLetters) == L"1" || basePart.Right(numLetters) == L"0")
{
while (numLetters < basePart.Length())
{
if (basePart[basePart.Length() - numLetters - 1] != '0')
break;
numLetters++;
}
}
else
return false;
_unchangedPart = basePart.Left(basePart.Length() - numLetters);
_changedPart = basePart.Right(numLetters);
return true;
}
UString GetNextName()
{
UString newName;
if (_newStyle || !_first)
{
int i;
int numLetters = _changedPart.Length();
for (i = numLetters - 1; i >= 0; i--)
{
wchar_t c = _changedPart[i];
if (c == L'9')
{
c = L'0';
newName = c + newName;
if (i == 0)
newName = UString(L'1') + newName;
continue;
}
c++;
newName = UString(c) + newName;
i--;
for (; i >= 0; i--)
newName = _changedPart[i] + newName;
break;
}
_changedPart = newName;
}
_first = false;
return _unchangedPart + _changedPart + _afterPart;
}
};
HRESULT CHandler::Open2(IInStream *stream,
const UInt64 *maxCheckStartPosition,
IArchiveOpenCallback *openArchiveCallback)
{
{
CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback;
CMyComPtr<ICryptoGetTextPassword> getTextPassword;
CMyComPtr<IArchiveOpenCallback> openArchiveCallbackWrap = openArchiveCallback;
CVolumeName seqName;
UInt64 totalBytes = 0;
UInt64 curBytes = 0;
if (openArchiveCallback != NULL)
{
openArchiveCallbackWrap.QueryInterface(IID_IArchiveOpenVolumeCallback, &openVolumeCallback);
openArchiveCallbackWrap.QueryInterface(IID_ICryptoGetTextPassword, &getTextPassword);
}
for (;;)
{
CMyComPtr<IInStream> inStream;
if (!_archives.IsEmpty())
{
if (!openVolumeCallback)
break;
if (_archives.Size() == 1)
{
if (!_archiveInfo.IsVolume())
break;
UString baseName;
{
NCOM::CPropVariant prop;
RINOK(openVolumeCallback->GetProperty(kpidName, &prop));
if (prop.vt != VT_BSTR)
break;
baseName = prop.bstrVal;
}
seqName.InitName(baseName, _archiveInfo.HaveNewVolumeName());
}
UString fullName = seqName.GetNextName();
HRESULT result = openVolumeCallback->GetStream(fullName, &inStream);
if (result == S_FALSE)
break;
if (result != S_OK)
return result;
if (!stream)
break;
}
else
inStream = stream;
UInt64 endPos = 0;
if (openArchiveCallback != NULL)
{
RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos));
RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
totalBytes += endPos;
RINOK(openArchiveCallback->SetTotal(NULL, &totalBytes));
}
NArchive::NRar::CInArchive archive;
RINOK(archive.Open(inStream, maxCheckStartPosition));
if (_archives.IsEmpty())
archive.GetArchiveInfo(_archiveInfo);
CItemEx item;
for (;;)
{
bool decryptionError;
HRESULT result = archive.GetNextItem(item, getTextPassword, decryptionError);
if (result == S_FALSE)
{
if (decryptionError && _items.IsEmpty())
return S_FALSE;
break;
}
RINOK(result);
if (item.IgnoreItem())
continue;
bool needAdd = true;
if (item.IsSplitBefore())
{
if (!_refItems.IsEmpty())
{
CRefItem &refItem = _refItems.Back();
refItem.NumItems++;
needAdd = false;
}
}
if (needAdd)
{
CRefItem refItem;
refItem.ItemIndex = _items.Size();
refItem.NumItems = 1;
refItem.VolumeIndex = _archives.Size();
_refItems.Add(refItem);
}
_items.Add(item);
if (openArchiveCallback != NULL && _items.Size() % 100 == 0)
{
UInt64 numFiles = _items.Size();
UInt64 numBytes = curBytes + item.Position;
RINOK(openArchiveCallback->SetCompleted(&numFiles, &numBytes));
}
}
curBytes += endPos;
_archives.Add(archive);
}
}
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *stream,
const UInt64 *maxCheckStartPosition,
IArchiveOpenCallback *openArchiveCallback)
{
COM_TRY_BEGIN
Close();
try
{
HRESULT res = Open2(stream, maxCheckStartPosition, openArchiveCallback);
if (res != S_OK)
Close();
return res;
}
catch(const CInArchiveException &) { Close(); return S_FALSE; }
catch(...) { Close(); throw; }
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
COM_TRY_BEGIN
_refItems.Clear();
_items.Clear();
_archives.Clear();
return S_OK;
COM_TRY_END
}
struct CMethodItem
{
Byte RarUnPackVersion;
CMyComPtr<ICompressCoder> Coder;
};
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
CMyComPtr<ICryptoGetTextPassword> getTextPassword;
UInt64 censoredTotalUnPacked = 0,
// censoredTotalPacked = 0,
importantTotalUnPacked = 0;
// importantTotalPacked = 0;
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _refItems.Size();
if (numItems == 0)
return S_OK;
int lastIndex = 0;
CRecordVector<int> importantIndexes;
CRecordVector<bool> extractStatuses;
for (UInt32 t = 0; t < numItems; t++)
{
int index = allFilesMode ? t : indices[t];
const CRefItem &refItem = _refItems[index];
const CItemEx &item = _items[refItem.ItemIndex];
censoredTotalUnPacked += item.Size;
// censoredTotalPacked += item.PackSize;
int j;
for (j = lastIndex; j <= index; j++)
// if (!_items[_refItems[j].ItemIndex].IsSolid())
if (!IsSolid(j))
lastIndex = j;
for (j = lastIndex; j <= index; j++)
{
const CRefItem &refItem = _refItems[j];
const CItemEx &item = _items[refItem.ItemIndex];
// const CItemEx &item = _items[j];
importantTotalUnPacked += item.Size;
// importantTotalPacked += item.PackSize;
importantIndexes.Add(j);
extractStatuses.Add(j == index);
}
lastIndex = index + 1;
}
extractCallback->SetTotal(importantTotalUnPacked);
UInt64 currentImportantTotalUnPacked = 0;
UInt64 currentImportantTotalPacked = 0;
UInt64 currentUnPackSize, currentPackSize;
CObjectVector<CMethodItem> methodItems;
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CFilterCoder *filterStreamSpec = new CFilterCoder;
CMyComPtr<ISequentialInStream> filterStream = filterStreamSpec;
NCrypto::NRar20::CDecoder *rar20CryptoDecoderSpec = NULL;
CMyComPtr<ICompressFilter> rar20CryptoDecoder;
NCrypto::NRar29::CDecoder *rar29CryptoDecoderSpec = NULL;
CMyComPtr<ICompressFilter> rar29CryptoDecoder;
CFolderInStream *folderInStreamSpec = NULL;
CMyComPtr<ISequentialInStream> folderInStream;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
bool solidStart = true;
for (int i = 0; i < importantIndexes.Size(); i++,
currentImportantTotalUnPacked += currentUnPackSize,
currentImportantTotalPacked += currentPackSize)
{
lps->InSize = currentImportantTotalPacked;
lps->OutSize = currentImportantTotalUnPacked;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> realOutStream;
Int32 askMode;
if (extractStatuses[i])
askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
else
askMode = NExtract::NAskMode::kSkip;
UInt32 index = importantIndexes[i];
const CRefItem &refItem = _refItems[index];
const CItemEx &item = _items[refItem.ItemIndex];
currentUnPackSize = item.Size;
currentPackSize = GetPackSize(index);
if (item.IgnoreItem())
continue;
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
if (!IsSolid(index))
solidStart = true;
if (item.IsDir())
{
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
bool mustBeProcessedAnywhere = false;
if (i < importantIndexes.Size() - 1)
{
// const CRefItem &nextRefItem = _refItems[importantIndexes[i + 1]];
// const CItemEx &nextItemInfo = _items[nextRefItem.ItemIndex];
// mustBeProcessedAnywhere = nextItemInfo.IsSolid();
mustBeProcessedAnywhere = IsSolid(importantIndexes[i + 1]);
}
if (!mustBeProcessedAnywhere && !testMode && !realOutStream)
continue;
if (!realOutStream && !testMode)
askMode = NExtract::NAskMode::kSkip;
RINOK(extractCallback->PrepareOperation(askMode));
COutStreamWithCRC *outStreamSpec = new COutStreamWithCRC;
CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
outStreamSpec->SetStream(realOutStream);
outStreamSpec->Init();
realOutStream.Release();
/*
for (int partIndex = 0; partIndex < 1; partIndex++)
{
CMyComPtr<ISequentialInStream> inStream;
// item redefinition
const CItemEx &item = _items[refItem.ItemIndex + partIndex];
NArchive::NRar::CInArchive &archive = _archives[refItem.VolumeIndex + partIndex];
inStream.Attach(archive.CreateLimitedStream(item.GetDataPosition(),
item.PackSize));
*/
if (!folderInStream)
{
folderInStreamSpec = new CFolderInStream;
folderInStream = folderInStreamSpec;
}
folderInStreamSpec->Init(&_archives, &_items, refItem);
UInt64 packSize = currentPackSize;
// packedPos += item.PackSize;
// unpackedPos += 0;
CMyComPtr<ISequentialInStream> inStream;
if (item.IsEncrypted())
{
CMyComPtr<ICryptoSetPassword> cryptoSetPassword;
if (item.UnPackVersion >= 29)
{
if (!rar29CryptoDecoder)
{
rar29CryptoDecoderSpec = new NCrypto::NRar29::CDecoder;
rar29CryptoDecoder = rar29CryptoDecoderSpec;
// RINOK(rar29CryptoDecoder.CoCreateInstance(CLSID_CCryptoRar29Decoder));
}
rar29CryptoDecoderSpec->SetRar350Mode(item.UnPackVersion < 36);
CMyComPtr<ICompressSetDecoderProperties2> cryptoProperties;
RINOK(rar29CryptoDecoder.QueryInterface(IID_ICompressSetDecoderProperties2,
&cryptoProperties));
RINOK(cryptoProperties->SetDecoderProperties2(item.Salt, item.HasSalt() ? sizeof(item.Salt) : 0));
filterStreamSpec->Filter = rar29CryptoDecoder;
}
else if (item.UnPackVersion >= 20)
{
if (!rar20CryptoDecoder)
{
rar20CryptoDecoderSpec = new NCrypto::NRar20::CDecoder;
rar20CryptoDecoder = rar20CryptoDecoderSpec;
// RINOK(rar20CryptoDecoder.CoCreateInstance(CLSID_CCryptoRar20Decoder));
}
filterStreamSpec->Filter = rar20CryptoDecoder;
}
else
{
outStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
continue;
}
RINOK(filterStreamSpec->Filter.QueryInterface(IID_ICryptoSetPassword,
&cryptoSetPassword));
if (!getTextPassword)
extractCallback->QueryInterface(IID_ICryptoGetTextPassword, (void **)&getTextPassword);
if (getTextPassword)
{
CMyComBSTR password;
RINOK(getTextPassword->CryptoGetTextPassword(&password));
if (item.UnPackVersion >= 29)
{
CByteBuffer buffer;
UString unicodePassword(password);
const UInt32 sizeInBytes = unicodePassword.Length() * 2;
buffer.SetCapacity(sizeInBytes);
for (int i = 0; i < unicodePassword.Length(); i++)
{
wchar_t c = unicodePassword[i];
((Byte *)buffer)[i * 2] = (Byte)c;
((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8);
}
RINOK(cryptoSetPassword->CryptoSetPassword(
(const Byte *)buffer, sizeInBytes));
}
else
{
AString oemPassword = UnicodeStringToMultiByte(
(const wchar_t *)password, CP_OEMCP);
RINOK(cryptoSetPassword->CryptoSetPassword(
(const Byte *)(const char *)oemPassword, oemPassword.Length()));
}
}
else
{
RINOK(cryptoSetPassword->CryptoSetPassword(0, 0));
}
filterStreamSpec->SetInStream(folderInStream);
inStream = filterStream;
}
else
{
inStream = folderInStream;
}
CMyComPtr<ICompressCoder> commonCoder;
switch(item.Method)
{
case '0':
{
commonCoder = copyCoder;
break;
}
case '1':
case '2':
case '3':
case '4':
case '5':
{
/*
if (item.UnPackVersion >= 29)
{
outStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
continue;
}
*/
int m;
for (m = 0; m < methodItems.Size(); m++)
if (methodItems[m].RarUnPackVersion == item.UnPackVersion)
break;
if (m == methodItems.Size())
{
CMethodItem mi;
mi.RarUnPackVersion = item.UnPackVersion;
mi.Coder.Release();
if (item.UnPackVersion <= 30)
{
UInt32 methodID = 0x040300;
if (item.UnPackVersion < 20)
methodID += 1;
else if (item.UnPackVersion < 29)
methodID += 2;
else
methodID += 3;
RINOK(CreateCoder(EXTERNAL_CODECS_VARS methodID, mi.Coder, false));
}
if (mi.Coder == 0)
{
outStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
continue;
}
m = methodItems.Add(mi);
}
CMyComPtr<ICompressCoder> decoder = methodItems[m].Coder;
CMyComPtr<ICompressSetDecoderProperties2> compressSetDecoderProperties;
RINOK(decoder.QueryInterface(IID_ICompressSetDecoderProperties2,
&compressSetDecoderProperties));
Byte isSolid = (Byte)((IsSolid(index) || item.IsSplitBefore()) ? 1: 0);
if (solidStart)
{
isSolid = false;
solidStart = false;
}
RINOK(compressSetDecoderProperties->SetDecoderProperties2(&isSolid, 1));
commonCoder = decoder;
break;
}
default:
outStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kUnSupportedMethod));
continue;
}
HRESULT result = commonCoder->Code(inStream, outStream, &packSize, &item.Size, progress);
if (item.IsEncrypted())
filterStreamSpec->ReleaseInStream();
if (result == S_FALSE)
{
outStream.Release();
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kDataError));
continue;
}
if (result != S_OK)
return result;
/*
if (refItem.NumItems == 1 &&
!item.IsSplitBefore() && !item.IsSplitAfter())
*/
{
const CItemEx &lastItem = _items[refItem.ItemIndex + refItem.NumItems - 1];
bool crcOK = outStreamSpec->GetCRC() == lastItem.FileCRC;
outStream.Release();
RINOK(extractCallback->SetOperationResult(crcOK ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kCRCError));
}
/*
else
{
bool crcOK = true;
for (int partIndex = 0; partIndex < refItem.NumItems; partIndex++)
{
const CItemEx &item = _items[refItem.ItemIndex + partIndex];
if (item.FileCRC != folderInStreamSpec->CRCs[partIndex])
{
crcOK = false;
break;
}
}
RINOK(extractCallback->SetOperationResult(crcOK ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kCRCError));
}
*/
}
return S_OK;
COM_TRY_END
}
IMPL_ISetCompressCodecsInfo
}}
<file_sep>/SQLCEHelper/TestApp/SqlCeHelperTestCases.h
#pragma once
#include "../Include/SqlCeHelper.h"
#define DB_FILE_NAME L"SqlCeHelperTest.sdf"
int max = 100;
TEST(SqlCeHelper, SelectDataAfterDelete)
{
printf("\n====After Delete.====\n");
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
sqlStr.Format(L"SELECT * FROM T1");
hr = db.ExecuteReader(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
while(!db.IsEndOfRecordSet())
{
wprintf(L"F1=[%d], F2=[%s], F3=[%s]\n", db.GetRowInt(1), db.GetRowStr(2), db.GetRowStr(3));
db.MoveNext();
}
db.CloseReader();
db.Close();
}
TEST(SqlCeHelper, DeleteData)
{
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
for(int i=0; i<max; ++i)
{
sqlStr.Format(L"DELETE FROM T1 WHERE F1=%d", i);
hr = db.ExecuteNonQuery(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
}
db.Close();
}
TEST(SqlCeHelper, SelectDataBeforeDelete)
{
printf("\n====Before Delete.====\n");
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
sqlStr.Format(L"SELECT * FROM T1");
hr = db.ExecuteReader(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
while(!db.IsEndOfRecordSet())
{
wprintf(L"F1=[%d], F2=[%s], F3=[%s]\n", db.GetRowInt(1), db.GetRowStr(2), db.GetRowStr(3));
db.MoveNext();
}
db.CloseReader();
db.Close();
}
TEST(SqlCeHelper, UpdateData)
{
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
for(int i=0; i<max; ++i)
{
SYSTEMTIME currentTime;
GetLocalTime(¤tTime);
sqlStr.Format(L"UPDATE T1 SET F2='STR%d', F3='%d-%d-%d %d:%d:%d' WHERE F1=%d",
max-i, currentTime.wYear, currentTime.wMonth, currentTime.wDay, currentTime.wHour, currentTime.wMinute, currentTime.wSecond, i);
hr = db.ExecuteNonQuery(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
}
db.Close();
}
TEST(SqlCeHelper, SelectDataBeforeUpdate)
{
printf("\n====Before Update.====\n");
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
sqlStr.Format(L"SELECT * FROM T1");
hr = db.ExecuteReader(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
while(!db.IsEndOfRecordSet())
{
wprintf(L"F1=[%d], F2=[%s], F3=[%s]\n", db.GetRowInt(1), db.GetRowStr(2), db.GetRowStr(3));
db.MoveNext();
}
db.CloseReader();
db.Close();
}
TEST(SqlCeHelper, InsertData)
{
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
for(int i=0; i<max; ++i)
{
SYSTEMTIME currentTime;
GetLocalTime(¤tTime);
sqlStr.Format(L"INSERT INTO T1 (F1, F2, F3) VALUES(%d, 'STR%d', '%d-%d-%d %d:%d:%d')",
i, i, currentTime.wYear, currentTime.wMonth, currentTime.wDay, currentTime.wHour, currentTime.wMinute, currentTime.wSecond);
hr = db.ExecuteNonQuery(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
}
db.Close();
}
TEST(SqlCeHelper, SelectDataBeforeInsert)
{
printf("\n====Before Insert.====\n");
SqlCeHelper db;
HRESULT hr = db.Open(DB_FILE_NAME);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
CString sqlStr;
sqlStr.Format(L"SELECT * FROM T1");
hr = db.ExecuteReader(sqlStr);
if(hr < 0)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
while(!db.IsEndOfRecordSet())
{
wprintf(L"F1=[%d], F2=[%s], F3=[%s]\n", db.GetRowInt(1), db.GetRowStr(2), db.GetRowStr(3));
db.MoveNext();
}
db.CloseReader();
db.Close();
}
TEST(SqlCeHelper, OpenDatabase)
{
SqlCeHelper db;
bool b = db.Open(DB_FILE_NAME);
if(!b)
{
CString cstr = db.GetErrorsMessage();
char* str = new char[cstr.GetLength()+1];
sprintf(str, "%S", cstr);
FAIL(str);
delete str;
}
//if(hr == -1)
//{
// FAIL("The database file doesn't exist.");
//}
//else if(hr == REGDB_E_CLASSNOTREG)
//{
// FAIL("SqlCe 3.5 is not installed or the sqlceoledb35.dll is not registered.");
//}
//else if(hr < 0)
//{
// FAIL(db.GetErrorsMessage().c_str());
// //FAIL("Cannot open the database.");
//}
db.Close();
}<file_sep>/7-Zip/CPP/7zip/Archive/Tar/TarHandler.cpp
// TarHandler.cpp
#include "StdAfx.h"
#include "Common/ComTry.h"
#include "Common/Defs.h"
#include "Common/NewHandler.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/ProgressUtils.h"
#include "../Common/ItemNameUtils.h"
#include "TarHandler.h"
#include "TarIn.h"
using namespace NWindows;
namespace NArchive {
namespace NTar {
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidIsDir, VT_BOOL},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidPosixAttrib, VT_UI4},
{ NULL, kpidUser, VT_BSTR},
{ NULL, kpidGroup, VT_BSTR},
{ NULL, kpidLink, VT_BSTR}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps_NO_Table
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
NCOM::CPropVariant prop;
switch(propID)
{
case kpidPhySize: if (_phySizeDefined) prop = _phySize; break;
}
prop.Detach(value);
return S_OK;
}
HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
{
UInt64 endPos = 0;
{
RINOK(stream->Seek(0, STREAM_SEEK_END, &endPos));
RINOK(stream->Seek(0, STREAM_SEEK_SET, NULL));
}
_isGood = true;
UInt64 pos = 0;
for (;;)
{
CItemEx item;
bool filled;
item.HeaderPosition = pos;
RINOK(ReadItem(stream, filled, item));
if (!filled)
break;
_items.Add(item);
RINOK(stream->Seek(item.GetPackSize(), STREAM_SEEK_CUR, &pos));
if (pos > endPos)
return S_FALSE;
if (pos == endPos)
{
_isGood = false;
break;
}
if (callback != NULL)
{
if (_items.Size() == 1)
{
RINOK(callback->SetTotal(NULL, &endPos));
}
if (_items.Size() % 100 == 0)
{
UInt64 numFiles = _items.Size();
RINOK(callback->SetCompleted(&numFiles, &pos));
}
}
}
if (_items.Size() == 0)
{
CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback;
if (!callback)
return S_FALSE;
callback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback);
if (!openVolumeCallback)
return S_FALSE;
NCOM::CPropVariant prop;
if (openVolumeCallback->GetProperty(kpidName, &prop) != S_OK)
return S_FALSE;
if (prop.vt != VT_BSTR)
return S_FALSE;
UString baseName = prop.bstrVal;
baseName = baseName.Right(4);
if (baseName.CompareNoCase(L".tar") != 0)
return S_FALSE;
}
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *openArchiveCallback)
{
COM_TRY_BEGIN
{
Close();
RINOK(Open2(stream, openArchiveCallback));
_stream = stream;
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::OpenSeq(ISequentialInStream *stream)
{
Close();
_seqStream = stream;
return S_OK;
}
STDMETHODIMP CHandler::Close()
{
_phySizeDefined = false;
_curIndex = 0;
_latestIsRead = false;
_items.Clear();
_seqStream.Release();
_stream.Release();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = (_stream ? _items.Size() : (UInt32)(Int32)-1);
return S_OK;
}
CHandler::CHandler()
{
copyCoderSpec = new NCompress::CCopyCoder();
copyCoder = copyCoderSpec;
}
HRESULT CHandler::SkipTo(UInt32 index)
{
while (_curIndex < index || !_latestIsRead)
{
if (_latestIsRead)
{
UInt64 packSize = _latestItem.GetPackSize();
RINOK(copyCoderSpec->Code(_seqStream, NULL, &packSize, &packSize, NULL));
_latestIsRead = false;
_curIndex++;
}
else
{
bool filled;
// item.HeaderPosition = pos;
RINOK(ReadItem(_seqStream, filled, _latestItem));
if (!filled)
return E_INVALIDARG;
_latestIsRead = true;
}
}
return S_OK;
}
static UString TarStringToUnicode(const AString &s)
{
return MultiByteToUnicodeString(s, CP_OEMCP);
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CItemEx *item;
if (_stream)
item = &_items[index];
else
{
if (index < _curIndex)
return E_INVALIDARG;
else
{
RINOK(SkipTo(index));
item = &_latestItem;
}
}
switch(propID)
{
case kpidPath: prop = NItemName::GetOSName2(TarStringToUnicode(item->Name)); break;
case kpidIsDir: prop = item->IsDir(); break;
case kpidSize: prop = item->Size; break;
case kpidPackSize: prop = item->GetPackSize(); break;
case kpidMTime:
if (item->MTime != 0)
{
FILETIME ft;
NTime::UnixTimeToFileTime(item->MTime, ft);
prop = ft;
}
break;
case kpidPosixAttrib: prop = item->Mode; break;
case kpidUser: prop = TarStringToUnicode(item->User); break;
case kpidGroup: prop = TarStringToUnicode(item->Group); break;
case kpidLink: prop = TarStringToUnicode(item->LinkName); break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
HRESULT CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
ISequentialInStream *stream = _seqStream;
bool seqMode = (_stream == NULL);
if (!seqMode)
stream = _stream;
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _items.Size();
if (_stream && numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
totalSize += _items[allFilesMode ? i : indices[i]].Size;
extractCallback->SetTotal(totalSize);
UInt64 totalPackSize;
totalSize = totalPackSize = 0;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
streamSpec->SetStream(stream);
CLimitedSequentialOutStream *outStreamSpec = new CLimitedSequentialOutStream;
CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
for (i = 0; i < numItems || seqMode; i++)
{
lps->InSize = totalPackSize;
lps->OutSize = totalSize;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> realOutStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
Int32 index = allFilesMode ? i : indices[i];
const CItemEx *item;
if (seqMode)
{
HRESULT res = SkipTo(index);
if (res == E_INVALIDARG)
break;
RINOK(res);
item = &_latestItem;
}
else
item = &_items[index];
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
totalSize += item->Size;
totalPackSize += item->GetPackSize();
if (item->IsDir())
{
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
bool skipMode = false;
if (!testMode && !realOutStream)
{
if (!seqMode)
continue;
skipMode = true;
askMode = NExtract::NAskMode::kSkip;
}
RINOK(extractCallback->PrepareOperation(askMode));
outStreamSpec->SetStream(realOutStream);
realOutStream.Release();
outStreamSpec->Init(skipMode ? 0 : item->Size, true);
if (!seqMode)
{
RINOK(_stream->Seek(item->GetDataPosition(), STREAM_SEEK_SET, NULL));
}
streamSpec->Init(item->GetPackSize());
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
if (seqMode)
{
_latestIsRead = false;
_curIndex++;
}
outStreamSpec->ReleaseStream();
RINOK(extractCallback->SetOperationResult(outStreamSpec->GetRem() == 0 ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kDataError));
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
COM_TRY_BEGIN
const CItemEx &item = _items[index];
return CreateLimitedInStream(_stream, item.GetDataPosition(), item.Size, stream);
COM_TRY_END
}
}}
<file_sep>/7-Zip/CPP/7zip/Archive/Iso/IsoRegister.cpp
// IsoRegister.cpp
#include "StdAfx.h"
#include "../../Common/RegisterArc.h"
#include "IsoHandler.h"
static IInArchive *CreateArc() { return new NArchive::NIso::CHandler; }
static CArcInfo g_ArcInfo =
{ L"Iso", L"iso", 0, 0xE7, { 'C', 'D', '0', '0', '1', 0x1 }, 7, false, CreateArc, 0 };
REGISTER_ARC(Iso)
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdContext.h
// PpmdContext.h
// 2009-05-30 : <NAME> : Public domain
// This code is based on <NAME>'s PPMdH code (public domain)
#ifndef __COMPRESS_PPMD_CONTEXT_H
#define __COMPRESS_PPMD_CONTEXT_H
#include "../../Common/Types.h"
#include "PpmdSubAlloc.h"
#include "RangeCoder.h"
namespace NCompress {
namespace NPpmd {
const int INT_BITS=7, PERIOD_BITS=7, TOT_BITS=INT_BITS+PERIOD_BITS,
INTERVAL=1 << INT_BITS, BIN_SCALE=1 << TOT_BITS, MAX_FREQ=124;
struct SEE2_CONTEXT
{
// SEE-contexts for PPM-contexts with masked symbols
UInt16 Summ;
Byte Shift, Count;
void init(int InitVal) { Summ = (UInt16)(InitVal << (Shift=PERIOD_BITS-4)); Count=4; }
unsigned int getMean()
{
unsigned int RetVal=(Summ >> Shift);
Summ = (UInt16)(Summ - RetVal);
return RetVal+(RetVal == 0);
}
void update()
{
if (Shift < PERIOD_BITS && --Count == 0)
{
Summ <<= 1;
Count = (Byte)(3 << Shift++);
}
}
};
struct PPM_CONTEXT
{
UInt16 NumStats; // sizeof(UInt16) > sizeof(Byte)
UInt16 SummFreq;
struct STATE
{
Byte Symbol, Freq;
UInt16 SuccessorLow;
UInt16 SuccessorHigh;
UInt32 GetSuccessor() const { return SuccessorLow | ((UInt32)SuccessorHigh << 16); }
void SetSuccessor(UInt32 v)
{
SuccessorLow = (UInt16)(v & 0xFFFF);
SuccessorHigh = (UInt16)((v >> 16) & 0xFFFF);
}
};
UInt32 Stats;
UInt32 Suffix;
PPM_CONTEXT* createChild(CSubAllocator &subAllocator, STATE* pStats, STATE& FirstState)
{
PPM_CONTEXT* pc = (PPM_CONTEXT*) subAllocator.AllocContext();
if (pc)
{
pc->NumStats = 1;
pc->oneState() = FirstState;
pc->Suffix = subAllocator.GetOffset(this);
pStats->SetSuccessor(subAllocator.GetOffsetNoCheck(pc));
}
return pc;
}
STATE& oneState() const { return (STATE&) SummFreq; }
};
/////////////////////////////////
const UInt16 InitBinEsc[] =
{0x3CDD, 0x1F3F, 0x59BF, 0x48F3, 0x64A1, 0x5ABC, 0x6632, 0x6051};
struct CInfo
{
CSubAllocator SubAllocator;
SEE2_CONTEXT SEE2Cont[25][16], DummySEE2Cont;
PPM_CONTEXT * MinContext, * MaxContext;
PPM_CONTEXT::STATE* FoundState; // found next state transition
int NumMasked, InitEsc, OrderFall, RunLength, InitRL, MaxOrder;
Byte CharMask[256], NS2Indx[256], NS2BSIndx[256], HB2Flag[256];
Byte EscCount, PrintCount, PrevSuccess, HiBitsFlag;
UInt16 BinSumm[128][64]; // binary SEE-contexts
UInt16 &GetBinSumm(const PPM_CONTEXT::STATE &rs, int numStates)
{
HiBitsFlag = HB2Flag[FoundState->Symbol];
return BinSumm[rs.Freq - 1][
PrevSuccess + NS2BSIndx[numStates - 1] +
HiBitsFlag + 2 * HB2Flag[rs.Symbol] +
((RunLength >> 26) & 0x20)];
}
PPM_CONTEXT *GetContext(UInt32 offset) const { return (PPM_CONTEXT *)SubAllocator.GetPtr(offset); }
PPM_CONTEXT *GetContextNoCheck(UInt32 offset) const { return (PPM_CONTEXT *)SubAllocator.GetPtrNoCheck(offset); }
PPM_CONTEXT::STATE *GetState(UInt32 offset) const { return (PPM_CONTEXT::STATE *)SubAllocator.GetPtr(offset); }
PPM_CONTEXT::STATE *GetStateNoCheck(UInt32 offset) const { return (PPM_CONTEXT::STATE *)SubAllocator.GetPtr(offset); }
void RestartModelRare()
{
int i, k, m;
memset(CharMask,0,sizeof(CharMask));
SubAllocator.InitSubAllocator();
InitRL = -((MaxOrder < 12) ? MaxOrder : 12) - 1;
MinContext = MaxContext = (PPM_CONTEXT*) SubAllocator.AllocContext();
MinContext->Suffix = 0;
OrderFall = MaxOrder;
MinContext->SummFreq = (UInt16)((MinContext->NumStats = 256) + 1);
FoundState = (PPM_CONTEXT::STATE*)SubAllocator.AllocUnits(256 / 2);
MinContext->Stats = SubAllocator.GetOffsetNoCheck(FoundState);
PrevSuccess = 0;
for (RunLength = InitRL, i = 0; i < 256; i++)
{
PPM_CONTEXT::STATE &state = FoundState[i];
state.Symbol = (Byte)i;
state.Freq = 1;
state.SetSuccessor(0);
}
for (i = 0; i < 128; i++)
for (k = 0; k < 8; k++)
for ( m=0; m < 64; m += 8)
BinSumm[i][k + m] = (UInt16)(BIN_SCALE - InitBinEsc[k] / (i + 2));
for (i = 0; i < 25; i++)
for (k = 0; k < 16; k++)
SEE2Cont[i][k].init(5*i+10);
}
void StartModelRare(int maxOrder)
{
int i, k, m ,Step;
EscCount=PrintCount=1;
if (maxOrder < 2)
{
memset(CharMask,0,sizeof(CharMask));
OrderFall = MaxOrder;
MinContext = MaxContext;
while (MinContext->Suffix != 0)
{
MinContext = GetContextNoCheck(MinContext->Suffix);
OrderFall--;
}
FoundState = GetState(MinContext->Stats);
MinContext = MaxContext;
}
else
{
MaxOrder = maxOrder;
RestartModelRare();
NS2BSIndx[0] = 2 * 0;
NS2BSIndx[1] = 2 * 1;
memset(NS2BSIndx + 2, 2 * 2, 9);
memset(NS2BSIndx + 11, 2 * 3, 256 - 11);
for (i = 0; i < 3; i++)
NS2Indx[i] = (Byte)i;
for (m = i, k = Step = 1; i < 256; i++)
{
NS2Indx[i] = (Byte)m;
if ( !--k )
{
k = ++Step;
m++;
}
}
memset(HB2Flag, 0, 0x40);
memset(HB2Flag + 0x40, 0x08, 0x100 - 0x40);
DummySEE2Cont.Shift = PERIOD_BITS;
}
}
PPM_CONTEXT* CreateSuccessors(bool skip, PPM_CONTEXT::STATE* p1)
{
// static UpState declaration bypasses IntelC bug
// static PPM_CONTEXT::STATE UpState;
PPM_CONTEXT::STATE UpState;
PPM_CONTEXT *pc = MinContext;
PPM_CONTEXT *UpBranch = GetContext(FoundState->GetSuccessor());
PPM_CONTEXT::STATE * p, * ps[MAX_O], ** pps = ps;
if ( !skip )
{
*pps++ = FoundState;
if ( !pc->Suffix )
goto NO_LOOP;
}
if ( p1 )
{
p = p1;
pc = GetContext(pc->Suffix);
goto LOOP_ENTRY;
}
do
{
pc = GetContext(pc->Suffix);
if (pc->NumStats != 1)
{
if ((p = GetStateNoCheck(pc->Stats))->Symbol != FoundState->Symbol)
do { p++; } while (p->Symbol != FoundState->Symbol);
}
else
p = &(pc->oneState());
LOOP_ENTRY:
if (GetContext(p->GetSuccessor()) != UpBranch)
{
pc = GetContext(p->GetSuccessor());
break;
}
*pps++ = p;
}
while ( pc->Suffix );
NO_LOOP:
if (pps == ps)
return pc;
UpState.Symbol = *(Byte*) UpBranch;
UpState.SetSuccessor(SubAllocator.GetOffset(UpBranch) + 1);
if (pc->NumStats != 1)
{
if ((p = GetStateNoCheck(pc->Stats))->Symbol != UpState.Symbol)
do { p++; } while (p->Symbol != UpState.Symbol);
unsigned int cf = p->Freq-1;
unsigned int s0 = pc->SummFreq - pc->NumStats - cf;
UpState.Freq = (Byte)(1 + ((2 * cf <= s0) ? (5 * cf > s0) :
((2 * cf + 3 * s0 - 1) / (2 * s0))));
}
else
UpState.Freq = pc->oneState().Freq;
do
{
pc = pc->createChild(SubAllocator, *--pps, UpState);
if ( !pc )
return NULL;
}
while (pps != ps);
return pc;
}
void UpdateModel()
{
PPM_CONTEXT::STATE fs = *FoundState, * p = NULL;
PPM_CONTEXT* pc, * Successor;
unsigned int ns1, ns, cf, sf, s0;
if (fs.Freq < MAX_FREQ / 4 && MinContext->Suffix != 0)
{
pc = GetContextNoCheck(MinContext->Suffix);
if (pc->NumStats != 1)
{
if ((p = GetStateNoCheck(pc->Stats))->Symbol != fs.Symbol)
{
do { p++; } while (p->Symbol != fs.Symbol);
if (p[0].Freq >= p[-1].Freq)
{
_PPMD_SWAP(p[0],p[-1]);
p--;
}
}
if (p->Freq < MAX_FREQ-9)
{
p->Freq += 2;
pc->SummFreq += 2;
}
}
else
{
p = &(pc->oneState());
p->Freq = (Byte)(p->Freq + ((p->Freq < 32) ? 1 : 0));
}
}
if ( !OrderFall )
{
MinContext = MaxContext = CreateSuccessors(true, p);
FoundState->SetSuccessor(SubAllocator.GetOffset(MinContext));
if (MinContext == 0)
goto RESTART_MODEL;
return;
}
*SubAllocator.pText++ = fs.Symbol;
Successor = (PPM_CONTEXT*) SubAllocator.pText;
if (SubAllocator.pText >= SubAllocator.UnitsStart)
goto RESTART_MODEL;
if (fs.GetSuccessor() != 0)
{
if ((Byte *)GetContext(fs.GetSuccessor()) <= SubAllocator.pText)
{
PPM_CONTEXT* cs = CreateSuccessors(false, p);
fs.SetSuccessor(SubAllocator.GetOffset(cs));
if (cs == NULL)
goto RESTART_MODEL;
}
if ( !--OrderFall )
{
Successor = GetContext(fs.GetSuccessor());
SubAllocator.pText -= (MaxContext != MinContext);
}
}
else
{
FoundState->SetSuccessor(SubAllocator.GetOffsetNoCheck(Successor));
fs.SetSuccessor(SubAllocator.GetOffsetNoCheck(MinContext));
}
s0 = MinContext->SummFreq - (ns = MinContext->NumStats) - (fs.Freq - 1);
for (pc = MaxContext; pc != MinContext; pc = GetContext(pc->Suffix))
{
if ((ns1 = pc->NumStats) != 1)
{
if ((ns1 & 1) == 0)
{
void *ppp = SubAllocator.ExpandUnits(GetState(pc->Stats), ns1 >> 1);
pc->Stats = SubAllocator.GetOffset(ppp);
if (!ppp)
goto RESTART_MODEL;
}
pc->SummFreq = (UInt16)(pc->SummFreq + (2 * ns1 < ns) + 2 * ((4 * ns1 <= ns) &
(pc->SummFreq <= 8 * ns1)));
}
else
{
p = (PPM_CONTEXT::STATE*) SubAllocator.AllocUnits(1);
if ( !p )
goto RESTART_MODEL;
*p = pc->oneState();
pc->Stats = SubAllocator.GetOffsetNoCheck(p);
if (p->Freq < MAX_FREQ / 4 - 1)
p->Freq <<= 1;
else
p->Freq = MAX_FREQ - 4;
pc->SummFreq = (UInt16)(p->Freq + InitEsc + (ns > 3));
}
cf = 2 * fs.Freq * (pc->SummFreq+6);
sf = s0 + pc->SummFreq;
if (cf < 6 * sf)
{
cf = 1 + (cf > sf)+(cf >= 4 * sf);
pc->SummFreq += 3;
}
else
{
cf = 4 + (cf >= 9 * sf) + (cf >= 12 * sf) + (cf >= 15 * sf);
pc->SummFreq = (UInt16)(pc->SummFreq + cf);
}
p = GetState(pc->Stats) + ns1;
p->SetSuccessor(SubAllocator.GetOffset(Successor));
p->Symbol = fs.Symbol;
p->Freq = (Byte)cf;
pc->NumStats = (UInt16)++ns1;
}
MaxContext = MinContext = GetContext(fs.GetSuccessor());
return;
RESTART_MODEL:
RestartModelRare();
EscCount = 0;
PrintCount = 0xFF;
}
void ClearMask()
{
EscCount = 1;
memset(CharMask, 0, sizeof(CharMask));
// if (++PrintCount == 0)
// PrintInfo(DecodedFile,EncodedFile);
}
void update1(PPM_CONTEXT::STATE* p)
{
(FoundState = p)->Freq += 4;
MinContext->SummFreq += 4;
if (p[0].Freq > p[-1].Freq)
{
_PPMD_SWAP(p[0],p[-1]);
FoundState = --p;
if (p->Freq > MAX_FREQ)
rescale();
}
}
void update2(PPM_CONTEXT::STATE* p)
{
(FoundState = p)->Freq += 4;
MinContext->SummFreq += 4;
if (p->Freq > MAX_FREQ)
rescale();
EscCount++;
RunLength = InitRL;
}
SEE2_CONTEXT* makeEscFreq2(int Diff, UInt32 &scale)
{
SEE2_CONTEXT* psee2c;
if (MinContext->NumStats != 256)
{
psee2c = SEE2Cont[NS2Indx[Diff-1]] +
(Diff < (GetContext(MinContext->Suffix))->NumStats - MinContext->NumStats) +
2 * (MinContext->SummFreq < 11 * MinContext->NumStats) +
4 * (NumMasked > Diff) +
HiBitsFlag;
scale = psee2c->getMean();
}
else
{
psee2c = &DummySEE2Cont;
scale = 1;
}
return psee2c;
}
void rescale()
{
int OldNS = MinContext->NumStats, i = MinContext->NumStats - 1, Adder, EscFreq;
PPM_CONTEXT::STATE* p1, * p;
PPM_CONTEXT::STATE *stats = GetStateNoCheck(MinContext->Stats);
for (p = FoundState; p != stats; p--)
_PPMD_SWAP(p[0], p[-1]);
stats->Freq += 4;
MinContext->SummFreq += 4;
EscFreq = MinContext->SummFreq - p->Freq;
Adder = (OrderFall != 0);
p->Freq = (Byte)((p->Freq + Adder) >> 1);
MinContext->SummFreq = p->Freq;
do
{
EscFreq -= (++p)->Freq;
p->Freq = (Byte)((p->Freq + Adder) >> 1);
MinContext->SummFreq = (UInt16)(MinContext->SummFreq + p->Freq);
if (p[0].Freq > p[-1].Freq)
{
PPM_CONTEXT::STATE tmp = *(p1 = p);
do
{
p1[0] = p1[-1];
}
while (--p1 != stats && tmp.Freq > p1[-1].Freq);
*p1 = tmp;
}
}
while ( --i );
if (p->Freq == 0)
{
do { i++; } while ((--p)->Freq == 0);
EscFreq += i;
MinContext->NumStats = (UInt16)(MinContext->NumStats - i);
if (MinContext->NumStats == 1)
{
PPM_CONTEXT::STATE tmp = *stats;
do { tmp.Freq = (Byte)(tmp.Freq - (tmp.Freq >> 1)); EscFreq >>= 1; } while (EscFreq > 1);
SubAllocator.FreeUnits(stats, (OldNS+1) >> 1);
*(FoundState = &MinContext->oneState()) = tmp; return;
}
}
EscFreq -= (EscFreq >> 1);
MinContext->SummFreq = (UInt16)(MinContext->SummFreq + EscFreq);
int n0 = (OldNS+1) >> 1, n1 = (MinContext->NumStats + 1) >> 1;
if (n0 != n1)
MinContext->Stats = SubAllocator.GetOffset(SubAllocator.ShrinkUnits(stats, n0, n1));
FoundState = GetState(MinContext->Stats);
}
void NextContext()
{
PPM_CONTEXT *c = GetContext(FoundState->GetSuccessor());
if (!OrderFall && (Byte *)c > SubAllocator.pText)
MinContext = MaxContext = c;
else
{
UpdateModel();
if (EscCount == 0)
ClearMask();
}
}
};
// Tabulated escapes for exponential symbol distribution
const Byte ExpEscape[16]={ 25,14, 9, 7, 5, 5, 4, 4, 4, 3, 3, 3, 2, 2, 2, 2 };
#define GET_MEAN(SUMM,SHIFT,ROUND) ((SUMM+(1 << (SHIFT-ROUND))) >> (SHIFT))
}}
#endif
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/PanelOperations.cpp
// PanelOperations.cpp
#include "StdAfx.h"
#include "Common/DynamicBuffer.h"
#include "Common/StringConvert.h"
#include "Windows/COM.h"
#include "Windows/FileDir.h"
#include "Windows/PropVariant.h"
#include "Windows/ResourceString.h"
#include "Windows/Thread.h"
#include "ComboDialog.h"
#include "FSFolder.h"
#include "FormatUtils.h"
#include "LangUtils.h"
#include "Panel.h"
#include "UpdateCallback100.h"
#include "resource.h"
using namespace NWindows;
using namespace NFile;
#ifndef _UNICODE
extern bool g_IsNT;
#endif
enum EFolderOpType
{
FOLDER_TYPE_CREATE_FOLDER = 0,
FOLDER_TYPE_DELETE = 1,
FOLDER_TYPE_RENAME = 2
};
class CThreadFolderOperations: public CProgressThreadVirt
{
HRESULT ProcessVirt();
public:
EFolderOpType OpType;
UString Name;
UInt32 Index;
CRecordVector<UInt32> Indices;
CMyComPtr<IFolderOperations> FolderOperations;
CMyComPtr<IProgress> UpdateCallback;
CUpdateCallback100Imp *UpdateCallbackSpec;
HRESULT Result;
CThreadFolderOperations(EFolderOpType opType): OpType(opType), Result(E_FAIL) {};
HRESULT DoOperation(CPanel &panel, const UString &progressTitle, const UString &titleError);
};
HRESULT CThreadFolderOperations::ProcessVirt()
{
NCOM::CComInitializer comInitializer;
switch(OpType)
{
case FOLDER_TYPE_CREATE_FOLDER:
Result = FolderOperations->CreateFolder(Name, UpdateCallback);
break;
case FOLDER_TYPE_DELETE:
Result = FolderOperations->Delete(&Indices.Front(), Indices.Size(), UpdateCallback);
break;
case FOLDER_TYPE_RENAME:
Result = FolderOperations->Rename(Index, Name, UpdateCallback);
break;
default:
Result = E_FAIL;
}
return Result;
};
HRESULT CThreadFolderOperations::DoOperation(CPanel &panel, const UString &progressTitle, const UString &titleError)
{
UpdateCallbackSpec = new CUpdateCallback100Imp;
UpdateCallback = UpdateCallbackSpec;
UpdateCallbackSpec->ProgressDialog = &ProgressDialog;
ProgressDialog.WaitMode = true;
ProgressDialog.Sync.SetErrorMessageTitle(titleError);
Result = S_OK;
bool usePassword = false;
UString password;
if (panel._parentFolders.Size() > 0)
{
const CFolderLink &fl = panel._parentFolders.Back();
usePassword = <PASSWORD>;
password = <PASSWORD>;
}
UpdateCallbackSpec->Init(usePassword, password);
ProgressDialog.MainWindow = panel._mainWindow; // panel.GetParent()
ProgressDialog.MainTitle = LangString(IDS_APP_TITLE, 0x03000000);
ProgressDialog.MainAddTitle = progressTitle + UString(L" ");
RINOK(Create(progressTitle, ProgressDialog.MainWindow));
return Result;
}
#ifndef _UNICODE
typedef int (WINAPI * SHFileOperationWP)(LPSHFILEOPSTRUCTW lpFileOp);
#endif
void CPanel::DeleteItems(bool toRecycleBin)
{
CPanel::CDisableTimerProcessing disableTimerProcessing2(*this);
CRecordVector<UInt32> indices;
GetOperatedItemIndices(indices);
if (indices.IsEmpty())
return;
CSelectedState state;
SaveSelectedState(state);
#ifndef UNDER_CE
// WM6 / SHFileOperationW doesn't ask user! So we use internal delete
bool useInternalDelete = false;
if (IsFSFolder() && toRecycleBin)
{
#ifndef _UNICODE
if (!g_IsNT)
{
CDynamicBuffer<CHAR> buffer;
size_t size = 0;
for (int i = 0; i < indices.Size(); i++)
{
const AString path = GetSystemString(GetFsPath() + GetItemRelPath(indices[i]));
buffer.EnsureCapacity(size + path.Length() + 1);
memmove(((CHAR *)buffer) + size, (const CHAR *)path, (path.Length() + 1) * sizeof(CHAR));
size += path.Length() + 1;
}
buffer.EnsureCapacity(size + 1);
((CHAR *)buffer)[size] = 0;
SHFILEOPSTRUCTA fo;
fo.hwnd = GetParent();
fo.wFunc = FO_DELETE;
fo.pFrom = (const CHAR *)buffer;
fo.pTo = 0;
fo.fFlags = 0;
if (toRecycleBin)
fo.fFlags |= FOF_ALLOWUNDO;
// fo.fFlags |= FOF_NOCONFIRMATION;
// fo.fFlags |= FOF_NOERRORUI;
// fo.fFlags |= FOF_SILENT;
// fo.fFlags |= FOF_WANTNUKEWARNING;
fo.fAnyOperationsAborted = FALSE;
fo.hNameMappings = 0;
fo.lpszProgressTitle = 0;
/* int res = */ ::SHFileOperationA(&fo);
}
else
#endif
{
CDynamicBuffer<WCHAR> buffer;
size_t size = 0;
int maxLen = 0;
for (int i = 0; i < indices.Size(); i++)
{
// L"\\\\?\\") doesn't work here.
const UString path = GetFsPath() + GetItemRelPath(indices[i]);
if (path.Length() > maxLen)
maxLen = path.Length();
buffer.EnsureCapacity(size + path.Length() + 1);
memmove(((WCHAR *)buffer) + size, (const WCHAR *)path, (path.Length() + 1) * sizeof(WCHAR));
size += path.Length() + 1;
}
buffer.EnsureCapacity(size + 1);
((WCHAR *)buffer)[size] = 0;
if (maxLen >= MAX_PATH)
{
if (toRecycleBin)
{
MessageBoxErrorLang(IDS_ERROR_LONG_PATH_TO_RECYCLE, 0x03020218);
return;
}
useInternalDelete = true;
}
else
{
SHFILEOPSTRUCTW fo;
fo.hwnd = GetParent();
fo.wFunc = FO_DELETE;
fo.pFrom = (const WCHAR *)buffer;
fo.pTo = 0;
fo.fFlags = 0;
if (toRecycleBin)
fo.fFlags |= FOF_ALLOWUNDO;
fo.fAnyOperationsAborted = FALSE;
fo.hNameMappings = 0;
fo.lpszProgressTitle = 0;
int res;
#ifdef _UNICODE
res = ::SHFileOperationW(&fo);
#else
SHFileOperationWP shFileOperationW = (SHFileOperationWP)
::GetProcAddress(::GetModuleHandleW(L"shell32.dll"), "SHFileOperationW");
if (shFileOperationW == 0)
return;
res = shFileOperationW(&fo);
#endif
}
}
/*
if (fo.fAnyOperationsAborted)
MessageBoxError(result, LangString(IDS_ERROR_DELETING, 0x03020217));
*/
}
else
useInternalDelete = true;
if (useInternalDelete)
#endif
DeleteItemsInternal(indices);
RefreshListCtrl(state);
}
void CPanel::MessageBoxErrorForUpdate(HRESULT errorCode, UINT resourceID, UInt32 langID)
{
if (errorCode == E_NOINTERFACE)
MessageBoxErrorLang(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208);
else
MessageBoxError(errorCode, LangString(resourceID, langID));
}
void CPanel::DeleteItemsInternal(CRecordVector<UInt32> &indices)
{
CMyComPtr<IFolderOperations> folderOperations;
if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
{
MessageBoxErrorForUpdate(E_NOINTERFACE, IDS_ERROR_DELETING, 0x03020217);
return;
}
UString title;
UString message;
if (indices.Size() == 1)
{
int index = indices[0];
const UString itemName = GetItemRelPath(index);
if (IsItemFolder(index))
{
title = LangString(IDS_CONFIRM_FOLDER_DELETE, 0x03020211);
message = MyFormatNew(IDS_WANT_TO_DELETE_FOLDER, 0x03020214, itemName);
}
else
{
title = LangString(IDS_CONFIRM_FILE_DELETE, 0x03020210);
message = MyFormatNew(IDS_WANT_TO_DELETE_FILE, 0x03020213, itemName);
}
}
else
{
title = LangString(IDS_CONFIRM_ITEMS_DELETE, 0x03020212);
message = MyFormatNew(IDS_WANT_TO_DELETE_ITEMS, 0x03020215,
NumberToString(indices.Size()));
}
if (::MessageBoxW(GetParent(), message, title, MB_OKCANCEL | MB_ICONQUESTION) != IDOK)
return;
{
CThreadFolderOperations op(FOLDER_TYPE_DELETE);
op.FolderOperations = folderOperations;
op.Indices = indices;
op.DoOperation(*this,
LangString(IDS_DELETING, 0x03020216),
LangString(IDS_ERROR_DELETING, 0x03020217));
}
RefreshTitleAlways();
}
BOOL CPanel::OnBeginLabelEdit(LV_DISPINFOW * lpnmh)
{
int realIndex = GetRealIndex(lpnmh->item);
if (realIndex == kParentIndex)
return TRUE;
CMyComPtr<IFolderOperations> folderOperations;
if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
return TRUE;
return FALSE;
}
BOOL CPanel::OnEndLabelEdit(LV_DISPINFOW * lpnmh)
{
if (lpnmh->item.pszText == NULL)
return FALSE;
CMyComPtr<IFolderOperations> folderOperations;
if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
{
MessageBoxErrorForUpdate(E_NOINTERFACE, IDS_ERROR_RENAMING, 0x03020221);
return FALSE;
}
const UString newName = lpnmh->item.pszText;
CPanel::CDisableTimerProcessing disableTimerProcessing2(*this);
SaveSelectedState(_selectedState);
int realIndex = GetRealIndex(lpnmh->item);
if (realIndex == kParentIndex)
return FALSE;
const UString prefix = GetItemPrefix(realIndex);
{
CThreadFolderOperations op(FOLDER_TYPE_RENAME);
op.FolderOperations = folderOperations;
op.Index = realIndex;
op.Name = newName;
HRESULT res = op.DoOperation(*this,
LangString(IDS_RENAMING, 0x03020220),
LangString(IDS_ERROR_RENAMING, 0x03020221));
if (res != S_OK)
return FALSE;
}
// Can't use RefreshListCtrl here.
// RefreshListCtrlSaveFocused();
_selectedState.FocusedName = prefix + newName;
_selectedState.SelectFocused = true;
// We need clear all items to disable GetText before Reload:
// number of items can change.
// _listView.DeleteAllItems();
// But seems it can still call GetText (maybe for current item)
// so we can't delete items.
_dontShowMode = true;
PostMessage(kReLoadMessage);
return TRUE;
}
void CPanel::CreateFolder()
{
CMyComPtr<IFolderOperations> folderOperations;
if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
{
MessageBoxErrorForUpdate(E_NOINTERFACE, IDS_CREATE_FOLDER_ERROR, 0x03020233);
return;
}
CPanel::CDisableTimerProcessing disableTimerProcessing2(*this);
CSelectedState state;
SaveSelectedState(state);
CComboDialog comboDialog;
comboDialog.Title = LangString(IDS_CREATE_FOLDER, 0x03020230);
comboDialog.Static = LangString(IDS_CREATE_FOLDER_NAME, 0x03020231);
comboDialog.Value = LangString(IDS_CREATE_FOLDER_DEFAULT_NAME, /*0x03020232*/ (UInt32)-1);
if (comboDialog.Create(GetParent()) == IDCANCEL)
return;
UString newName = comboDialog.Value;
{
CThreadFolderOperations op(FOLDER_TYPE_CREATE_FOLDER);
op.FolderOperations = folderOperations;
op.Name = newName;
HRESULT res = op.DoOperation(*this,
LangString(IDS_CREATE_FOLDER, 0x03020230),
LangString(IDS_CREATE_FOLDER_ERROR, 0x03020233));
if (res != S_OK)
return;
}
int pos = newName.Find(WCHAR_PATH_SEPARATOR);
if (pos >= 0)
newName = newName.Left(pos);
if (!_mySelectMode)
state.SelectedNames.Clear();
state.FocusedName = newName;
state.SelectFocused = true;
RefreshTitleAlways();
RefreshListCtrl(state);
}
void CPanel::CreateFile()
{
CMyComPtr<IFolderOperations> folderOperations;
if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
{
MessageBoxErrorForUpdate(E_NOINTERFACE, IDS_CREATE_FILE_ERROR, 0x03020243);
return;
}
CPanel::CDisableTimerProcessing disableTimerProcessing2(*this);
CSelectedState state;
SaveSelectedState(state);
CComboDialog comboDialog;
comboDialog.Title = LangString(IDS_CREATE_FILE, 0x03020240);
comboDialog.Static = LangString(IDS_CREATE_FILE_NAME, 0x03020241);
comboDialog.Value = LangString(IDS_CREATE_FILE_DEFAULT_NAME, /*0x03020242*/ (UInt32)-1);
if (comboDialog.Create(GetParent()) == IDCANCEL)
return;
UString newName = comboDialog.Value;
HRESULT result = folderOperations->CreateFile(newName, 0);
if (result != S_OK)
{
MessageBoxErrorForUpdate(result, IDS_CREATE_FILE_ERROR, 0x03020243);
return;
}
int pos = newName.Find(WCHAR_PATH_SEPARATOR);
if (pos >= 0)
newName = newName.Left(pos);
if (!_mySelectMode)
state.SelectedNames.Clear();
state.FocusedName = newName;
state.SelectFocused = true;
RefreshListCtrl(state);
}
void CPanel::RenameFile()
{
int index = _listView.GetFocusedItem();
if (index >= 0)
_listView.EditLabel(index);
}
void CPanel::ChangeComment()
{
CPanel::CDisableTimerProcessing disableTimerProcessing2(*this);
int index = _listView.GetFocusedItem();
if (index < 0)
return;
int realIndex = GetRealItemIndex(index);
if (realIndex == kParentIndex)
return;
CSelectedState state;
SaveSelectedState(state);
CMyComPtr<IFolderOperations> folderOperations;
if (_folder.QueryInterface(IID_IFolderOperations, &folderOperations) != S_OK)
{
MessageBoxErrorLang(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208);
return;
}
UString comment;
{
NCOM::CPropVariant propVariant;
if (_folder->GetProperty(realIndex, kpidComment, &propVariant) != S_OK)
return;
if (propVariant.vt == VT_BSTR)
comment = propVariant.bstrVal;
else if (propVariant.vt != VT_EMPTY)
return;
}
UString name = GetItemRelPath(realIndex);
CComboDialog comboDialog;
comboDialog.Title = name + L" " + LangString(IDS_COMMENT, 0x03020290);
comboDialog.Value = comment;
comboDialog.Static = LangString(IDS_COMMENT2, 0x03020291);
if (comboDialog.Create(GetParent()) == IDCANCEL)
return;
NCOM::CPropVariant propVariant = comboDialog.Value;
HRESULT result = folderOperations->SetProperty(realIndex, kpidComment, &propVariant, NULL);
if (result != S_OK)
{
if (result == E_NOINTERFACE)
MessageBoxErrorLang(IDS_OPERATION_IS_NOT_SUPPORTED, 0x03020208);
else
MessageBoxError(result, L"Set Comment Error");
}
RefreshListCtrl(state);
}
<file_sep>/FingerSuite/FingerSuiteCPL/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerSuiteCPL.rc
//
#define IDI_ICON1 101
#define IDI_ICON 101
#define IDI_FingerSuiteApplet 101
#define IDS_NAME 102
#define IDS_FingerSuiteApplet 102
#define IDS_DESC 103
#define IDS_Description_FingerSuiteApplet 103
#define IDI_ICON3 104
#define IDS_Task_FingerSuiteApplet 104
#define IDS_Keywords_FingerSuiteApplet 105
#define IDD_FINGERMENUCONFIG_FORM 129
#define IDD_PAGE1 129
#define IDD_PAGE2 130
#define IDD_PAGE3 131
#define IDD_PAGE4 132
#define IDD_PAGEABOUT 133
#define IDD_PAGE5 134
#define IDD_PAGE7 135
#define IDR_CONTROLPANEL 200
#define IDC_BTN_CLOSE_FINGERMENU 1000
#define IDC_BTN_START_FINGERMENU 1001
#define IDC_CB_SKIN_FINGERMENU 1001
#define IDC_CB_SKIN_FINGERMSGBOX 1002
#define IDC_AUTOSTART_MENU 1002
#define IDC_AUTOSTART_MSGBOX 1003
#define IDC_LBL_AUTOSTART_MENU 1004
#define IDC_LBL_TRANSLEVEL 1005
#define IDC_LBL_CB_SKIN_FINGERMENU 1005
#define IDC_TRANSLEVEL 1006
#define IDC_LBL_MAXCOUNT 1007
#define IDC_SPIN_TRANSLEVEL 1008
#define IDC_MAXCOUNT 1009
#define IDC_ENABLE_SIP 1010
#define IDC_CL_BKGCOLOR 1011
#define IDC_CL_TEXTCOLOR 1012
#define IDC_CL_SELTEXTCOLOR 1013
#define IDC_BTN_BKGCOLOR 1014
#define IDC_BTN_TEXTCOLOR 1015
#define IDC_BTN_SELTEXTCOLOR 1016
#define IDC_CL_DISTEXTCOLOR 1017
#define IDC_BTN_DISTEXTCOLOR 1018
#define IDC_CL_LINECOLOR 1019
#define IDC_BTN_LINECOLOR 1020
#define IDC_CB_PROCESSES 1021
#define IDC_BTN_ADDPROGRAM 1022
#define IDC_LB_PROCESSES 1023
#define IDC_BTN_REMOVEPROGRAMS 1024
#define IDC_BTN_REFRESH 1025
#define IDC_SPIN_MAXCOUNT 1026
#define IDC_LBL_MAXVELOCITY 1027
#define IDC_MAXVELOCITY 1028
#define IDC_SPIN_MAXVELOCITY 1029
#define IDC_ENABLE_TRANSPARENCY 1030
#define IDC_CL_BKGCOLORTRANSP 1031
#define IDC_BTN_BKGCOLORTRANSP 1032
#define IDC_DISABLE_BTNS 1033
#define IDC_DISABLEINTERVAL 1034
#define IDC_ENABLE_ANIMATION 1034
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 106
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1006
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/MachoHandler.cpp
// MachoHandler.cpp
#include "StdAfx.h"
#include "../../../C/CpuArch.h"
#include "Common/Buffer.h"
#include "Common/ComTry.h"
#include "Windows/PropVariantUtils.h"
#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"
#include "../Compress/CopyCoder.h"
static UInt32 Get32(const Byte *p, int be) { if (be) return GetBe32(p); return GetUi32(p); }
static UInt64 Get64(const Byte *p, int be) { if (be) return GetBe64(p); return GetUi64(p); }
using namespace NWindows;
namespace NArchive {
namespace NMacho {
#define MACH_ARCH_ABI64 (1 << 24)
#define MACH_MACHINE_386 7
#define MACH_MACHINE_ARM 12
#define MACH_MACHINE_SPARC 14
#define MACH_MACHINE_PPC 18
#define MACH_MACHINE_PPC64 (MACH_ARCH_ABI64 | MACH_MACHINE_PPC)
#define MACH_MACHINE_AMD64 (MACH_ARCH_ABI64 | MACH_MACHINE_386)
#define MACH_CMD_SEGMENT_32 1
#define MACH_CMD_SEGMENT_64 0x19
#define MACH_SECT_TYPE_MASK 0x000000FF
#define MACH_SECT_ATTR_MASK 0xFFFFFF00
#define MACH_SECT_ATTR_ZEROFILL 1
const char *g_SectTypes[] =
{
"REGULAR",
"ZEROFILL",
"CSTRINGS",
"4BYTE_LITERALS",
"8BYTE_LITERALS",
"LITERAL_POINTERS",
"NON_LAZY_SYMBOL_POINTERS",
"LAZY_SYMBOL_POINTERS",
"SYMBOL_STUBS",
"MOD_INIT_FUNC_POINTERS",
"MOD_TERM_FUNC_POINTERS",
"COALESCED",
"GB_ZEROFILL",
"INTERPOSING",
"16BYTE_LITERALS"
};
const char *g_FileTypes[] =
{
"0",
"OBJECT",
"EXECUTE",
"FVMLIB",
"CORE",
"PRELOAD",
"DYLIB",
"DYLINKER",
"BUNDLE",
"DYLIB_STUB",
"DSYM"
};
static const CUInt32PCharPair g_Flags[] =
{
{ (UInt32)1 << 31, "PURE_INSTRUCTIONS" },
{ 1 << 30, "NO_TOC" },
{ 1 << 29, "STRIP_STATIC_SYMS" },
{ 1 << 28, "NO_DEAD_STRIP" },
{ 1 << 27, "LIVE_SUPPORT" },
{ 1 << 26, "SELF_MODIFYING_CODE" },
{ 1 << 25, "DEBUG" },
{ 1 << 10, "SOME_INSTRUCTIONS" },
{ 1 << 9, "EXT_RELOC" },
{ 1 << 8, "LOC_RELOC" }
};
static const CUInt32PCharPair g_MachinePairs[] =
{
{ MACH_MACHINE_386, "x86" },
{ MACH_MACHINE_ARM, "ARM" },
{ MACH_MACHINE_SPARC, "SPARC" },
{ MACH_MACHINE_PPC, "PowerPC" },
{ MACH_MACHINE_PPC64, "PowerPC 64-bit" },
{ MACH_MACHINE_AMD64, "x64" }
};
static const int kNameSize = 16;
struct CSegment
{
char Name[kNameSize];
};
struct CSection
{
char Name[kNameSize];
char SegName[kNameSize];
UInt64 Va;
UInt64 Size;
UInt32 Pa;
UInt32 Flags;
int SegmentIndex;
UInt64 GetPackSize() const { return Flags == MACH_SECT_ATTR_ZEROFILL ? 0 : Size; }
};
class CHandler:
public IInArchive,
public CMyUnknownImp
{
CMyComPtr<IInStream> _inStream;
CObjectVector<CSegment> _segments;
CObjectVector<CSection> _sections;
bool _mode64;
bool _be;
UInt32 _machine;
UInt32 _type;
UInt32 _headersSize;
UInt64 _totalSize;
HRESULT Open2(ISequentialInStream *stream);
bool Parse(const Byte *buf, UInt32 size);
public:
MY_UNKNOWN_IMP1(IInArchive)
INTERFACE_IInArchive(;)
};
bool CHandler::Parse(const Byte *buf, UInt32 size)
{
bool mode64 = _mode64;
bool be = _be;
const Byte *bufStart = buf;
bool reduceCommands = false;
if (size < 512)
return false;
_machine = Get32(buf + 4, be);
_type = Get32(buf + 0xC, be);
UInt32 numCommands = Get32(buf + 0x10, be);
UInt32 commandsSize = Get32(buf + 0x14, be);
if (commandsSize > size)
return false;
if (commandsSize > (1 << 24) || numCommands > (1 << 18))
return false;
if (numCommands > 16)
{
reduceCommands = true;
numCommands = 16;
}
_headersSize = 0;
buf += 0x1C;
size -= 0x1C;
if (mode64)
{
buf += 4;
size -= 4;
}
_totalSize = (UInt32)(buf - bufStart);
if (commandsSize < size)
size = commandsSize;
for (UInt32 cmdIndex = 0; cmdIndex < numCommands; cmdIndex++)
{
if (size < 8)
return false;
UInt32 cmd = Get32(buf, be);
UInt32 cmdSize = Get32(buf + 4, be);
if (size < cmdSize)
return false;
if (cmd == MACH_CMD_SEGMENT_32 || cmd == MACH_CMD_SEGMENT_64)
{
UInt32 offs = (cmd == MACH_CMD_SEGMENT_64) ? 0x48 : 0x38;
if (cmdSize < offs)
break;
{
UInt64 vmAddr, vmSize, phAddr, phSize;
if (cmd == MACH_CMD_SEGMENT_64)
{
vmAddr = Get64(buf + 0x18, be);
vmSize = Get64(buf + 0x20, be);
phAddr = Get64(buf + 0x28, be);
phSize = Get64(buf + 0x30, be);
}
else
{
vmAddr = Get32(buf + 0x18, be);
vmSize = Get32(buf + 0x1C, be);
phAddr = Get32(buf + 0x20, be);
phSize = Get32(buf + 0x24, be);
}
{
UInt64 totalSize = phAddr + phSize;
if (totalSize > _totalSize)
_totalSize = totalSize;
}
}
CSegment seg;
memcpy(seg.Name, buf + 8, kNameSize);
_segments.Add(seg);
UInt32 numSections = Get32(buf + offs - 8, be);
if (numSections > (1 << 8))
return false;
while (numSections-- != 0)
{
CSection section;
UInt32 headerSize = (cmd == MACH_CMD_SEGMENT_64) ? 0x50 : 0x44;
const Byte *p = buf + offs;
if (cmdSize - offs < headerSize)
break;
if (cmd == MACH_CMD_SEGMENT_64)
{
section.Va = Get64(p + 0x20, be);
section.Size = Get64(p + 0x28, be);
section.Pa = Get32(p + 0x30, be);
section.Flags = Get32(p + 0x40, be);
}
else
{
section.Va = Get32(p + 0x20, be);
section.Size = Get32(p + 0x24, be);
section.Pa = Get32(p + 0x28, be);
section.Flags = Get32(p + 0x38, be);
}
memcpy(section.Name, p, kNameSize);
memcpy(section.SegName, p + kNameSize, kNameSize);
section.SegmentIndex = _segments.Size() - 1;
_sections.Add(section);
offs += headerSize;
}
if (offs != cmdSize)
return false;
}
buf += cmdSize;
size -= cmdSize;
}
_headersSize = (UInt32)(buf - bufStart);
return reduceCommands || (size == 0);
}
STATPROPSTG kArcProps[] =
{
{ NULL, kpidCpu, VT_BSTR},
{ NULL, kpidBit64, VT_BOOL},
{ NULL, kpidBigEndian, VT_BOOL},
{ NULL, kpidCharacts, VT_BSTR},
{ NULL, kpidPhySize, VT_UI8},
{ NULL, kpidHeadersSize, VT_UI4}
};
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidCharacts, VT_BSTR},
{ NULL, kpidOffset, VT_UI8},
{ NULL, kpidVa, VT_UI8}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
switch(propID)
{
case kpidCpu: PAIR_TO_PROP(g_MachinePairs, _machine, prop); break;
case kpidCharacts: TYPE_TO_PROP(g_FileTypes, _type, prop); break;
case kpidPhySize: prop = _totalSize; break;
case kpidHeadersSize: prop = _headersSize; break;
case kpidBit64: if (_mode64) prop = _mode64; break;
case kpidBigEndian: if (_be) prop = _be; break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
static AString GetName(const char *name)
{
char res[kNameSize + 1];
memcpy(res, name, kNameSize);
res[kNameSize] = 0;
return res;
}
static AString SectFlagsToString(UInt32 flags)
{
AString res = TypeToString(g_SectTypes, sizeof(g_SectTypes) / sizeof(g_SectTypes[0]),
flags & MACH_SECT_TYPE_MASK);
AString s = FlagsToString(g_Flags, sizeof(g_Flags) / sizeof(g_Flags[0]),
flags & MACH_SECT_ATTR_MASK);
if (!s.IsEmpty())
{
res += ' ';
res += s;
}
return res;
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
const CSection &item = _sections[index];
switch(propID)
{
case kpidPath: StringToProp(GetName(_segments[item.SegmentIndex].Name) + GetName(item.Name), prop); break;
case kpidSize: prop = (UInt64)item.Size; break;
case kpidPackSize: prop = (UInt64)item.GetPackSize(); break;
case kpidCharacts: StringToProp(SectFlagsToString(item.Flags), prop); break;
case kpidOffset: prop = item.Pa; break;
case kpidVa: prop = item.Va; break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
HRESULT CHandler::Open2(ISequentialInStream *stream)
{
const UInt32 kBufSize = 1 << 18;
const UInt32 kSigSize = 4;
CByteBuffer buffer;
buffer.SetCapacity(kBufSize);
Byte *buf = buffer;
size_t processed = kSigSize;
RINOK(ReadStream_FALSE(stream, buf, processed));
UInt32 sig = GetUi32(buf);
bool be, mode64;
switch(sig)
{
case 0xCEFAEDFE: be = true; mode64 = false; break;
case 0xCFFAEDFE: be = true; mode64 = true; break;
case 0xFEEDFACE: be = false; mode64 = false; break;
case 0xFEEDFACF: be = false; mode64 = true; break;
default: return S_FALSE;
}
processed = kBufSize - kSigSize;
RINOK(ReadStream(stream, buf + kSigSize, &processed));
_mode64 = mode64;
_be = be;
return Parse(buf, (UInt32)processed + kSigSize) ? S_OK : S_FALSE;
}
STDMETHODIMP CHandler::Open(IInStream *inStream,
const UInt64 * /* maxCheckStartPosition */,
IArchiveOpenCallback * /* openArchiveCallback */)
{
COM_TRY_BEGIN
Close();
RINOK(Open2(inStream));
_inStream = inStream;
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_inStream.Release();
_sections.Clear();
_segments.Clear();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _sections.Size();
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _sections.Size();
if (numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
totalSize += _sections[allFilesMode ? i : indices[i]].GetPackSize();
extractCallback->SetTotal(totalSize);
UInt64 currentTotalSize = 0;
UInt64 currentItemSize;
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
streamSpec->SetStream(_inStream);
for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
{
lps->InSize = lps->OutSize = currentTotalSize;
RINOK(lps->SetCur());
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
UInt32 index = allFilesMode ? i : indices[i];
const CSection &item = _sections[index];
currentItemSize = item.GetPackSize();
CMyComPtr<ISequentialOutStream> outStream;
RINOK(extractCallback->GetStream(index, &outStream, askMode));
if (!testMode && !outStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(_inStream->Seek(item.Pa, STREAM_SEEK_SET, NULL));
streamSpec->Init(currentItemSize);
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
outStream.Release();
RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kDataError));
}
return S_OK;
COM_TRY_END
}
static IInArchive *CreateArc() { return new CHandler; }
static CArcInfo g_ArcInfo =
{ L"MachO", L"", 0, 0xDF, { 0 }, 0, false, CreateArc, 0 };
REGISTER_ARC(Macho)
}}
<file_sep>/FBReaderJ/jni/LineBreak/TxtParser.h
#ifndef HW_TXTPARSER_H
#define HW_TXTPARSER_H
#include <jni.h>
#ifdef __cplusplus
extern "C"
{
#endif
JNIEXPORT void JNICALL Java_org_parser_txt_TxtParser_Parser(JNIEnv *env, jobject thiz, jobject thisParser,jstring strPath);
#ifdef __cplusplus
}
#endif
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/Wim/WimIn.h
// Archive/WimIn.h
#ifndef __ARCHIVE_WIM_IN_H
#define __ARCHIVE_WIM_IN_H
#include "Common/Buffer.h"
#include "Common/MyString.h"
#include "../../Compress/CopyCoder.h"
#include "../../Compress/LzxDecoder.h"
namespace NArchive {
namespace NWim {
namespace NXpress {
class CBitStream
{
CInBuffer m_Stream;
UInt32 m_Value;
unsigned m_BitPos;
public:
bool Create(UInt32 bufferSize) { return m_Stream.Create(bufferSize); }
void SetStream(ISequentialInStream *s) { m_Stream.SetStream(s); }
void ReleaseStream() { m_Stream.ReleaseStream(); }
void Init() { m_Stream.Init(); m_BitPos = 0; }
// UInt64 GetProcessedSize() const { return m_Stream.GetProcessedSize() - m_BitPos / 8; }
Byte DirectReadByte() { return m_Stream.ReadByte(); }
void Normalize()
{
if (m_BitPos < 16)
{
Byte b0 = m_Stream.ReadByte();
Byte b1 = m_Stream.ReadByte();
m_Value = (m_Value << 8) | b1;
m_Value = (m_Value << 8) | b0;
m_BitPos += 16;
}
}
UInt32 GetValue(unsigned numBits)
{
Normalize();
return (m_Value >> (m_BitPos - numBits)) & ((1 << numBits) - 1);
}
void MovePos(unsigned numBits) { m_BitPos -= numBits; }
UInt32 ReadBits(unsigned numBits)
{
UInt32 res = GetValue(numBits);
m_BitPos -= numBits;
return res;
}
};
const int kNumHuffmanBits = 16;
const UInt32 kMatchMinLen = 3;
const UInt32 kNumLenSlots = 16;
const UInt32 kNumPosSlots = 16;
const UInt32 kNumPosLenSlots = kNumPosSlots * kNumLenSlots;
const UInt32 kMainTableSize = 256 + kNumPosLenSlots;
class CDecoder
{
CBitStream m_InBitStream;
CLzOutWindow m_OutWindowStream;
NCompress::NHuffman::CDecoder<kNumHuffmanBits, kMainTableSize> m_MainDecoder;
HRESULT CodeSpec(UInt32 size);
HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream, UInt32 outSize);
public:
void ReleaseStreams()
{
m_OutWindowStream.ReleaseStream();
m_InBitStream.ReleaseStream();
}
HRESULT Flush() { return m_OutWindowStream.Flush(); }
HRESULT Code(ISequentialInStream *inStream, ISequentialOutStream *outStream, UInt32 outSize);
};
}
namespace NResourceFlags
{
const Byte Compressed = 4;
const Byte kMetadata = 2;
}
struct CResource
{
UInt64 PackSize;
UInt64 Offset;
UInt64 UnpackSize;
Byte Flags;
void Parse(const Byte *p);
bool IsCompressed() const { return (Flags & NResourceFlags::Compressed) != 0; }
bool IsMetadata() const { return (Flags & NResourceFlags::kMetadata) != 0; }
bool IsEmpty() const { return (UnpackSize == 0); }
};
namespace NHeaderFlags
{
const UInt32 kCompression = 2;
const UInt32 kSpanned = 8;
const UInt32 kRpFix = 0x80;
const UInt32 kXPRESS = 0x20000;
const UInt32 kLZX = 0x40000;
}
struct CHeader
{
UInt32 Flags;
UInt32 Version;
// UInt32 ChunkSize;
UInt16 PartNumber;
UInt16 NumParts;
UInt32 NumImages;
Byte Guid[16];
CResource OffsetResource;
CResource XmlResource;
CResource MetadataResource;
/*
CResource IntegrityResource;
UInt32 BootIndex;
*/
HRESULT Parse(const Byte *p);
bool IsCompressed() const { return (Flags & NHeaderFlags::kCompression) != 0; }
bool IsSupported() const { return (!IsCompressed() || (Flags & NHeaderFlags::kLZX) != 0 || (Flags & NHeaderFlags::kXPRESS) != 0 ) ; }
bool IsLzxMode() const { return (Flags & NHeaderFlags::kLZX) != 0; }
bool IsSpanned() const { return (!IsCompressed() || (Flags & NHeaderFlags::kSpanned) != 0); }
bool IsNewVersion()const { return (Version > 0x010C00); }
bool AreFromOnArchive(const CHeader &h)
{
return (memcmp(Guid, h.Guid, sizeof(Guid)) == 0) && (h.NumParts == NumParts);
}
};
const UInt32 kHashSize = 20;
const UInt32 kStreamInfoSize = 24 + 2 + 4 + kHashSize;
struct CStreamInfo
{
CResource Resource;
UInt16 PartNumber;
UInt32 RefCount;
BYTE Hash[kHashSize];
};
struct CItem
{
UString Name;
UInt32 Attrib;
// UInt32 SecurityId;
BYTE Hash[kHashSize];
FILETIME CTime;
FILETIME ATime;
FILETIME MTime;
// UInt32 ReparseTag;
// UInt64 HardLink;
// UInt16 NumStreams;
// UInt16 ShortNameLen;
int StreamIndex;
bool HasMetadata;
CItem(): HasMetadata(true), StreamIndex(-1) {}
bool isDir() const { return HasMetadata && ((Attrib & 0x10) != 0); }
bool HasStream() const
{
for (int i = 0; i < kHashSize; i++)
if (Hash[i] != 0)
return true;
return false;
}
};
struct CDatabase
{
CRecordVector<CStreamInfo> Streams;
CObjectVector<CItem> Items;
UInt64 GetUnpackSize() const
{
UInt64 res = 0;
for (int i = 0; i < Streams.Size(); i++)
res += Streams[i].Resource.UnpackSize;
return res;
}
UInt64 GetPackSize() const
{
UInt64 res = 0;
for (int i = 0; i < Streams.Size(); i++)
res += Streams[i].Resource.PackSize;
return res;
}
void Clear()
{
Streams.Clear();
Items.Clear();
}
};
HRESULT ReadHeader(IInStream *inStream, CHeader &header);
HRESULT OpenArchive(IInStream *inStream, const CHeader &header, CByteBuffer &xml, CDatabase &database);
HRESULT SortDatabase(CDatabase &database);
class CUnpacker
{
NCompress::CCopyCoder *copyCoderSpec;
CMyComPtr<ICompressCoder> copyCoder;
NCompress::NLzx::CDecoder *lzxDecoderSpec;
CMyComPtr<ICompressCoder> lzxDecoder;
NXpress::CDecoder xpressDecoder;
CByteBuffer sizesBuf;
HRESULT Unpack(IInStream *inStream, const CResource &res, bool lzxMode,
ISequentialOutStream *outStream, ICompressProgressInfo *progress);
public:
HRESULT Unpack(IInStream *inStream, const CResource &res, bool lzxMode,
ISequentialOutStream *outStream, ICompressProgressInfo *progress, Byte *digest);
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/Tar/TarUpdate.cpp
// TarUpdate.cpp
#include "StdAfx.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/ProgressUtils.h"
#include "../../Compress/CopyCoder.h"
#include "TarOut.h"
#include "TarUpdate.h"
namespace NArchive {
namespace NTar {
HRESULT UpdateArchive(IInStream *inStream, ISequentialOutStream *outStream,
const CObjectVector<NArchive::NTar::CItemEx> &inputItems,
const CObjectVector<CUpdateItem> &updateItems,
IArchiveUpdateCallback *updateCallback)
{
COutArchive outArchive;
outArchive.Create(outStream);
UInt64 complexity = 0;
int i;
for(i = 0; i < updateItems.Size(); i++)
{
const CUpdateItem &ui = updateItems[i];
if (ui.NewData)
complexity += ui.Size;
else
complexity += inputItems[ui.IndexInArchive].GetFullSize();
}
RINOK(updateCallback->SetTotal(complexity));
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder;
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(updateCallback, true);
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<CLimitedSequentialInStream> inStreamLimited(streamSpec);
streamSpec->SetStream(inStream);
complexity = 0;
for(i = 0; i < updateItems.Size(); i++)
{
lps->InSize = lps->OutSize = complexity;
RINOK(lps->SetCur());
const CUpdateItem &ui = updateItems[i];
CItem item;
if (ui.NewProps)
{
item.Mode = ui.Mode;
item.Name = ui.Name;
item.User = ui.User;
item.Group = ui.Group;
if (ui.IsDir)
{
item.LinkFlag = NFileHeader::NLinkFlag::kDirectory;
item.Size = 0;
}
else
{
item.LinkFlag = NFileHeader::NLinkFlag::kNormal;
item.Size = ui.Size;
}
item.MTime = ui.Time;
item.DeviceMajorDefined = false;
item.DeviceMinorDefined = false;
item.UID = 0;
item.GID = 0;
memmove(item.Magic, NFileHeader::NMagic::kEmpty, 8);
}
else
item = inputItems[ui.IndexInArchive];
if (ui.NewData)
{
item.Size = ui.Size;
if (item.Size == (UInt64)(Int64)-1)
return E_INVALIDARG;
}
else
item.Size = inputItems[ui.IndexInArchive].Size;
if (ui.NewData)
{
CMyComPtr<ISequentialInStream> fileInStream;
HRESULT res = updateCallback->GetStream(ui.IndexInClient, &fileInStream);
if (res != S_FALSE)
{
RINOK(res);
RINOK(outArchive.WriteHeader(item));
if (!ui.IsDir)
{
RINOK(copyCoder->Code(fileInStream, outStream, NULL, NULL, progress));
if (copyCoderSpec->TotalSize != item.Size)
return E_FAIL;
RINOK(outArchive.FillDataResidual(item.Size));
}
}
complexity += ui.Size;
RINOK(updateCallback->SetOperationResult(NArchive::NUpdate::NOperationResult::kOK));
}
else
{
const CItemEx &existItemInfo = inputItems[ui.IndexInArchive];
UInt64 size;
if (ui.NewProps)
{
RINOK(outArchive.WriteHeader(item));
RINOK(inStream->Seek(existItemInfo.GetDataPosition(), STREAM_SEEK_SET, NULL));
size = existItemInfo.Size;
}
else
{
RINOK(inStream->Seek(existItemInfo.HeaderPosition, STREAM_SEEK_SET, NULL));
size = existItemInfo.GetFullSize();
}
streamSpec->Init(size);
RINOK(copyCoder->Code(inStreamLimited, outStream, NULL, NULL, progress));
if (copyCoderSpec->TotalSize != size)
return E_FAIL;
RINOK(outArchive.FillDataResidual(existItemInfo.Size));
complexity += size;
}
}
return outArchive.WriteFinishHeader();
}
}}
<file_sep>/FingerSuite/FingerNotificationRES/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerNotificationRES.rc
//
#define IDS_NO_NEW_NOTIFICATIONS 102
#define IDS_VOLUME 103
#define IDS_BATTERY 104
#define IDR_MAINFRAME 128
#define ID_MENU_SHOWORIGINAL 40003
#define ID_MENU_ABOUT 40004
#define ID_MENU_EXIT 40006
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40009
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/SQLCEHelper/Source/Currency.h
#pragma once
class CCurrency
{
private:
CY m_cy;
public:
CCurrency(const CY& cy) : m_cy(cy) {}
CCurrency(const CCurrency& cy) : m_cy(cy) {}
CCurrency& operator=(const CY& cy);
CCurrency& operator=(const CCurrency& cy);
bool operator==(const CCurrency& cy) const { return m_cy.int64 == cy.m_cy.int64; }
bool operator!=(const CCurrency& cy) const { return m_cy.int64 != cy.m_cy.int64; }
bool operator< (const CCurrency& cy) const { return m_cy.int64 > cy.m_cy.int64; }
bool operator> (const CCurrency& cy) const { return m_cy.int64 < cy.m_cy.int64; }
bool operator<=(const CCurrency& cy) const { return m_cy.int64 <= cy.m_cy.int64; }
bool operator>=(const CCurrency& cy) const { return m_cy.int64 >= cy.m_cy.int64; }
bool operator! () const { return !m_cy.int64; }
CCurrency operator+(const CCurrency& cy) const;
CCurrency operator-(const CCurrency& cy) const;
CCurrency operator-() const;
CCurrency operator*(int nMultiplier) const;
CCurrency operator/(int nDivider) const;
const CCurrency& operator+=(const CCurrency& cy) { m_cy.int64 += cy.m_cy.int64; return *this; }
const CCurrency& operator-=(const CCurrency& cy) { m_cy.int64 -= cy.m_cy.int64; return *this; }
const CCurrency& operator*=(int nMultiplier) { m_cy.int64 *= nMultiplier; return *this; }
const CCurrency& operator/=(int nDivider) { m_cy.int64 /= nDivider; return *this; }
operator CY() const { return m_cy; }
operator double() const { return ((double)m_cy.int64) / 10000; }
operator float() const { return ((float)m_cy.int64) / 10000; }
enum NumberFormat
{
None,
Number,
Currency
};
CString Format(NumberFormat fmt = None, LCID lcid = LOCALE_SYSTEM_DEFAULT);
};
inline CCurrency& CCurrency::operator=(const CY &cy)
{
m_cy = cy;
return *this;
}
inline CCurrency& CCurrency::operator=(const CCurrency &cy)
{
if(this != &cy)
m_cy = cy.m_cy;
return *this;
}
inline CCurrency CCurrency::operator +(const CCurrency& cy) const
{
CY val;
val.int64 = m_cy.int64 + cy.m_cy.int64;
return val;
}
inline CCurrency CCurrency::operator -(const CCurrency& cy) const
{
CY val;
val.int64 = m_cy.int64 - cy.m_cy.int64;
return val;
}
inline CCurrency CCurrency::operator *(int nMultiplier) const
{
CY val;
val.int64 = m_cy.int64 * nMultiplier;
return val;
}
inline CCurrency CCurrency::operator /(int nDivider) const
{
CY val;
val.int64 = m_cy.int64 / nDivider;
return val;
}
// CCurrency::operator-
//
// Unary opertor -
//
inline CCurrency CCurrency::operator-() const
{
CY val;
val.int64 = -m_cy.int64;
return val;
}<file_sep>/SQLCEHelper/Source/Currency.cpp
#include "stdafx.h"
#include "Currency.h"
CString CCurrency::Format(NumberFormat fmt, LCID lcid)
{
TCHAR szNum[32]; // Must hold between 922337203685477.5807 and -922337203685477.5808
TCHAR* psz = szNum + 31; // Set psz to last char
__int64 ii = m_cy.int64 < 0 ? -m_cy.int64 : m_cy.int64;
int nDec = 4; // Four decimals max
*psz = 0; // Set terminating null
do
{
--psz; // Move back
if(nDec-- == 0)
*psz = _T('.'); // Decimal point
else
{
unsigned lsd = (unsigned)(ii % 10); // Get least significant
// digit
ii /= 10; // Prepare for next most
// significant digit
*psz = _T('0') + lsd; // Place the digit
}
} while(ii != 0);
// Check if we need to add trailing zeroes
if(nDec >= 0)
{
while(nDec-- > 0)
*--psz = _T('0');
*--psz = _T('.');
}
if(m_cy.int64 < 0)
*--psz = _T('-');
if(fmt == Number)
{
TCHAR szFmt[32];
GetNumberFormat(LOCALE_USER_DEFAULT, NULL, psz, NULL, szFmt, 32);
return CString(szFmt);
}
if(fmt == Currency)
{
TCHAR szFmt[32];
GetCurrencyFormat(LOCALE_USER_DEFAULT, NULL, psz, NULL, szFmt, 32);
return CString(szFmt);
}
return CString(psz);
}
<file_sep>/FingerSuite/FingerMsgboxRES/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerMsgboxRES.rc
//
#define IDR_MAINFRAME 128
#define IDS_OK 129
#define IDS_CANCEL 130
#define IDS_YES 131
#define IDS_MENU_ABOUT 132
#define IDS_MENU_EXIT 133
#define IDS_SOFTKEY_CLOSE 134
#define IDS_NO 136
#define IDS_ABORT 137
#define IDS_RETRY 138
#define IDS_IGNORE 139
#define ID_MENU_SHOWORIGINAL 32774
#define ID_MENU_EXIT 32776
#define ID_MENU_ABOUT 32779
#define ID_MENU_ADDTOEXCLUSIONLIST 40001
#define ID_MENU_ADDTOWNDEXCLUSIONLIST 40002
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40002
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/FingerSuite/FingerMsgBox/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerMsgBox.rc
//
#define IDS_LVK_EXIT 98
#define IDS_RVK_MENU 99
#define IDR_MAINFRAME 128
#define IDS_OK 129
#define IDS_CANCEL 130
#define IDS_YES 131
#define IDS_MENU_ABOUT 132
#define IDS_MENU_EXIT 133
#define IDS_SOFTKEY_CLOSE 134
#define IDS_UNKNOWN_ERROR 135
#define IDS_NO 136
#define IDS_ABORT 137
#define IDS_RETRY 138
#define IDS_IGNORE 139
#define IDR_MENU1 202
#define FM_IDW_MENU_BAR 0xE803
#define ID_MENU_SHOWORIGINAL 32774
#define ID_MENU_EXIT 32776
#define ID_MENU_ABOUT 32779
#define ID_MENU_ADDTOEXCLUSIONLIST 40001
#define ID_MENU_ADDTOWNDEXCLUSIONLIST 40002
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 203
#define _APS_NEXT_COMMAND_VALUE 32775
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/PanelListNotify.cpp
// PanelListNotify.cpp
#include "StdAfx.h"
#include "resource.h"
#include "Common/IntToString.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/PropVariantConversions.h"
#include "../Common/PropIDUtils.h"
#include "../../PropID.h"
#include "Panel.h"
#include "FormatUtils.h"
using namespace NWindows;
/*
static UString ConvertSizeToStringShort(UInt64 value)
{
wchar_t s[32];
wchar_t c, c2 = L'B';
if (value < (UInt64)10000)
{
c = L'B';
c2 = L'\0';
}
else if (value < ((UInt64)10000 << 10))
{
value >>= 10;
c = L'K';
}
else if (value < ((UInt64)10000 << 20))
{
value >>= 20;
c = L'M';
}
else
{
value >>= 30;
c = L'G';
}
ConvertUInt64ToString(value, s);
int p = MyStringLen(s);
s[p++] = L' ';
s[p++] = c;
s[p++] = c2;
s[p++] = L'\0';
return s;
}
*/
UString ConvertSizeToString(UInt64 value)
{
wchar_t s[32];
ConvertUInt64ToString(value, s);
int i = MyStringLen(s);
int pos = sizeof(s) / sizeof(s[0]);
s[--pos] = L'\0';
while (i > 3)
{
s[--pos] = s[--i];
s[--pos] = s[--i];
s[--pos] = s[--i];
s[--pos] = L' ';
}
while (i > 0)
s[--pos] = s[--i];
return s + pos;
}
LRESULT CPanel::SetItemText(LVITEMW &item)
{
if (_dontShowMode)
return 0;
UINT32 realIndex = GetRealIndex(item);
/*
if ((item.mask & LVIF_IMAGE) != 0)
{
bool defined = false;
CComPtr<IFolderGetSystemIconIndex> folderGetSystemIconIndex;
_folder.QueryInterface(&folderGetSystemIconIndex);
if (folderGetSystemIconIndex)
{
folderGetSystemIconIndex->GetSystemIconIndex(index, &item.iImage);
defined = (item.iImage > 0);
}
if (!defined)
{
NCOM::CPropVariant prop;
_folder->GetProperty(index, kpidAttrib, &prop);
UINT32 attrib = 0;
if (prop.vt == VT_UI4)
attrib = prop.ulVal;
else if (IsItemFolder(index))
attrib |= FILE_ATTRIBUTE_DIRECTORY;
if (_currentFolderPrefix.IsEmpty())
throw 1;
else
item.iImage = _extToIconMap.GetIconIndex(attrib, GetSystemString(GetItemName(index)));
}
// item.iImage = 1;
}
*/
if ((item.mask & LVIF_TEXT) == 0)
return 0;
if (realIndex == kParentIndex)
return 0;
UString s;
UINT32 subItemIndex = item.iSubItem;
PROPID propID = _visibleProperties[subItemIndex].ID;
/*
{
NCOM::CPropVariant property;
if (propID == kpidType)
string = GetFileType(index);
else
{
HRESULT result = m_ArchiveFolder->GetProperty(index, propID, &property);
if (result != S_OK)
{
// PrintMessage("GetPropertyValue error");
return 0;
}
string = ConvertPropertyToString(property, propID, false);
}
}
*/
// const NFind::CFileInfo &aFileInfo = m_Files[index];
NCOM::CPropVariant prop;
/*
bool needRead = true;
if (propID == kpidSize)
{
CComPtr<IFolderGetItemFullSize> getItemFullSize;
if (_folder.QueryInterface(&getItemFullSize) == S_OK)
{
if (getItemFullSize->GetItemFullSize(index, &prop) == S_OK)
needRead = false;
}
}
if (needRead)
*/
if (_folder->GetProperty(realIndex, propID, &prop) != S_OK)
throw 2723407;
if ((prop.vt == VT_UI8 || prop.vt == VT_UI4) && (
propID == kpidSize ||
propID == kpidPackSize ||
propID == kpidNumSubDirs ||
propID == kpidNumSubFiles ||
propID == kpidPosition ||
propID == kpidNumBlocks ||
propID == kpidClusterSize ||
propID == kpidTotalSize ||
propID == kpidFreeSpace
))
s = ConvertSizeToString(ConvertPropVariantToUInt64(prop));
else
{
s = ConvertPropertyToString(prop, propID, false);
s.Replace(wchar_t(0xA), L' ');
s.Replace(wchar_t(0xD), L' ');
}
int size = item.cchTextMax;
if (size > 0)
{
if (s.Length() + 1 > size)
s = s.Left(size - 1);
MyStringCopy(item.pszText, (const wchar_t *)s);
}
return 0;
}
#ifndef UNDER_CE
extern DWORD g_ComCtl32Version;
#endif
void CPanel::OnItemChanged(NMLISTVIEW *item)
{
int index = (int)item->lParam;
if (index == kParentIndex)
return;
bool oldSelected = (item->uOldState & LVIS_SELECTED) != 0;
bool newSelected = (item->uNewState & LVIS_SELECTED) != 0;
// Don't change this code. It works only with such check
if (oldSelected != newSelected)
_selectedStatusVector[index] = newSelected;
}
extern bool g_LVN_ITEMACTIVATE_Support;
void CPanel::OnNotifyActivateItems()
{
// bool leftCtrl = (::GetKeyState(VK_LCONTROL) & 0x8000) != 0;
// bool rightCtrl = (::GetKeyState(VK_RCONTROL) & 0x8000) != 0;
bool alt = (::GetKeyState(VK_MENU) & 0x8000) != 0;
bool ctrl = (::GetKeyState(VK_CONTROL) & 0x8000) != 0;
bool shift = (::GetKeyState(VK_SHIFT) & 0x8000) != 0;
if (!shift && alt && !ctrl)
Properties();
else
OpenSelectedItems(!shift || alt || ctrl);
}
bool CPanel::OnNotifyList(LPNMHDR header, LRESULT &result)
{
switch(header->code)
{
case LVN_ITEMCHANGED:
{
if (_enableItemChangeNotify)
{
if (!_mySelectMode)
OnItemChanged((LPNMLISTVIEW)header);
RefreshStatusBar();
}
return false;
}
/*
case LVN_ODSTATECHANGED:
{
break;
}
*/
case LVN_GETDISPINFOW:
{
LV_DISPINFOW *dispInfo = (LV_DISPINFOW *)header;
//is the sub-item information being requested?
if ((dispInfo->item.mask & LVIF_TEXT) != 0 ||
(dispInfo->item.mask & LVIF_IMAGE) != 0)
SetItemText(dispInfo->item);
return false;
}
case LVN_KEYDOWN:
{
bool boolResult = OnKeyDown(LPNMLVKEYDOWN(header), result);
RefreshStatusBar();
return boolResult;
}
case LVN_COLUMNCLICK:
OnColumnClick(LPNMLISTVIEW(header));
return false;
case LVN_ITEMACTIVATE:
if (g_LVN_ITEMACTIVATE_Support)
{
OnNotifyActivateItems();
return false;
}
break;
case NM_DBLCLK:
case NM_RETURN:
if (!g_LVN_ITEMACTIVATE_Support)
{
OnNotifyActivateItems();
return false;
}
break;
case NM_RCLICK:
RefreshStatusBar();
break;
/*
return OnRightClick((LPNMITEMACTIVATE)header, result);
*/
/*
case NM_CLICK:
SendRefreshStatusBarMessage();
return 0;
// TODO : Handler default action...
return 0;
case LVN_ITEMCHANGED:
{
NMLISTVIEW *pNMLV = (NMLISTVIEW *) lpnmh;
SelChange(pNMLV);
return TRUE;
}
case NM_SETFOCUS:
return onSetFocus(NULL);
case NM_KILLFOCUS:
return onKillFocus(NULL);
*/
case NM_CLICK:
{
// we need SetFocusToList, if we drag-select items from other panel.
SetFocusToList();
RefreshStatusBar();
if (_mySelectMode)
#ifndef UNDER_CE
if (g_ComCtl32Version >= MAKELONG(71, 4))
#endif
OnLeftClick((MY_NMLISTVIEW_NMITEMACTIVATE *)header);
return false;
}
case LVN_BEGINLABELEDITW:
result = OnBeginLabelEdit((LV_DISPINFOW *)header);
return true;
case LVN_ENDLABELEDITW:
result = OnEndLabelEdit((LV_DISPINFOW *)header);
return true;
case NM_CUSTOMDRAW:
{
if (_mySelectMode)
return OnCustomDraw((LPNMLVCUSTOMDRAW)header, result);
break;
}
case LVN_BEGINDRAG:
{
OnDrag((LPNMLISTVIEW)header);
RefreshStatusBar();
break;
}
// case LVN_BEGINRDRAG:
}
return false;
}
bool CPanel::OnCustomDraw(LPNMLVCUSTOMDRAW lplvcd, LRESULT &result)
{
switch(lplvcd->nmcd.dwDrawStage)
{
case CDDS_PREPAINT :
result = CDRF_NOTIFYITEMDRAW;
return true;
case CDDS_ITEMPREPAINT:
/*
SelectObject(lplvcd->nmcd.hdc,
GetFontForItem(lplvcd->nmcd.dwItemSpec,
lplvcd->nmcd.lItemlParam) );
lplvcd->clrText = GetColorForItem(lplvcd->nmcd.dwItemSpec,
lplvcd->nmcd.lItemlParam);
lplvcd->clrTextBk = GetBkColorForItem(lplvcd->nmcd.dwItemSpec,
lplvcd->nmcd.lItemlParam);
*/
int realIndex = (int)lplvcd->nmcd.lItemlParam;
bool selected = false;
if (realIndex != kParentIndex)
selected = _selectedStatusVector[realIndex];
if (selected)
lplvcd->clrTextBk = RGB(255, 192, 192);
// lplvcd->clrText = RGB(255, 0, 128);
else
lplvcd->clrTextBk = _listView.GetBkColor();
// lplvcd->clrText = RGB(0, 0, 0);
// result = CDRF_NEWFONT;
result = CDRF_NOTIFYITEMDRAW;
return true;
// return false;
// return true;
/*
case CDDS_SUBITEM | CDDS_ITEMPREPAINT:
if (lplvcd->iSubItem == 0)
{
// lplvcd->clrText = RGB(255, 0, 0);
lplvcd->clrTextBk = RGB(192, 192, 192);
}
else
{
lplvcd->clrText = RGB(0, 0, 0);
lplvcd->clrTextBk = RGB(255, 255, 255);
}
return true;
*/
/* At this point, you can change the background colors for the item
and any subitems and return CDRF_NEWFONT. If the list-view control
is in report mode, you can simply return CDRF_NOTIFYSUBITEMREDRAW
to customize the item's subitems individually */
}
return false;
}
void CPanel::OnRefreshStatusBar()
{
CRecordVector<UINT32> indices;
GetOperatedItemIndices(indices);
_statusBar.SetText(0, MyFormatNew(IDS_N_SELECTED_ITEMS, 0x02000301, NumberToString(indices.Size())));
UString selectSizeString;
if (indices.Size() > 0)
{
UInt64 totalSize = 0;
for (int i = 0; i < indices.Size(); i++)
totalSize += GetItemSize(indices[i]);
selectSizeString = ConvertSizeToString(totalSize);
}
_statusBar.SetText(1, selectSizeString);
int focusedItem = _listView.GetFocusedItem();
UString sizeString;
UString dateString;
if (focusedItem >= 0 && _listView.GetSelectedCount() > 0)
{
int realIndex = GetRealItemIndex(focusedItem);
if (realIndex != kParentIndex)
{
sizeString = ConvertSizeToString(GetItemSize(realIndex));
NCOM::CPropVariant prop;
if (_folder->GetProperty(realIndex, kpidMTime, &prop) == S_OK)
dateString = ConvertPropertyToString(prop, kpidMTime, false);
}
}
_statusBar.SetText(2, sizeString);
_statusBar.SetText(3, dateString);
// _statusBar.SetText(4, nameString);
// _statusBar2.SetText(1, MyFormatNew(L"{0} bytes", NumberToStringW(totalSize)));
}
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/PropertyName.cpp
// PropertyName.cpp
#include "StdAfx.h"
#include "Common/IntToString.h"
#include "Windows/ResourceString.h"
#include "../../PropID.h"
#include "LangUtils.h"
#include "PropertyName.h"
#include "resource.h"
#include "PropertyNameRes.h"
struct CPropertyIDNamePair
{
PROPID PropID;
UINT ResourceID;
UInt32 LangID;
};
static CPropertyIDNamePair kPropertyIDNamePairs[] =
{
{ kpidPath, IDS_PROP_PATH, 0x02000203 },
{ kpidName, IDS_PROP_NAME, 0x02000204 },
{ kpidExtension, IDS_PROP_EXTENSION, 0x02000205 },
{ kpidIsDir, IDS_PROP_IS_FOLDER, 0x02000206},
{ kpidSize, IDS_PROP_SIZE, 0x02000207},
{ kpidPackSize, IDS_PROP_PACKED_SIZE, 0x02000208 },
{ kpidAttrib, IDS_PROP_ATTRIBUTES, 0x02000209 },
{ kpidCTime, IDS_PROP_CTIME, 0x0200020A },
{ kpidATime, IDS_PROP_ATIME, 0x0200020B },
{ kpidMTime, IDS_PROP_MTIME, 0x0200020C },
{ kpidSolid, IDS_PROP_SOLID, 0x0200020D },
{ kpidCommented, IDS_PROP_C0MMENTED, 0x0200020E },
{ kpidEncrypted, IDS_PROP_ENCRYPTED, 0x0200020F },
{ kpidSplitBefore, IDS_PROP_SPLIT_BEFORE, 0x02000210 },
{ kpidSplitAfter, IDS_PROP_SPLIT_AFTER, 0x02000211 },
{ kpidDictionarySize, IDS_PROP_DICTIONARY_SIZE, 0x02000212 },
{ kpidCRC, IDS_PROP_CRC, 0x02000213 },
{ kpidType, IDS_PROP_FILE_TYPE, 0x02000214},
{ kpidIsAnti, IDS_PROP_ANTI, 0x02000215 },
{ kpidMethod, IDS_PROP_METHOD, 0x02000216 },
{ kpidHostOS, IDS_PROP_HOST_OS, 0x02000217 },
{ kpidFileSystem, IDS_PROP_FILE_SYSTEM, 0x02000218},
{ kpidUser, IDS_PROP_USER, 0x02000219},
{ kpidGroup, IDS_PROP_GROUP, 0x0200021A},
{ kpidBlock, IDS_PROP_BLOCK, 0x0200021B },
{ kpidComment, IDS_PROP_COMMENT, 0x0200021C },
{ kpidPosition, IDS_PROP_POSITION, 0x0200021D },
{ kpidPrefix, IDS_PROP_PREFIX, 0x0200021E },
{ kpidNumSubDirs, IDS_PROP_FOLDERS, 0x0200021F },
{ kpidNumSubFiles, IDS_PROP_FILES, 0x02000220 },
{ kpidUnpackVer, IDS_PROP_VERSION, 0x02000221},
{ kpidVolume, IDS_PROP_VOLUME, 0x02000222},
{ kpidIsVolume, IDS_PROP_IS_VOLUME, 0x02000223},
{ kpidOffset, IDS_PROP_OFFSET, 0x02000224},
{ kpidLinks, IDS_PROP_LINKS, 0x02000225},
{ kpidNumBlocks, IDS_PROP_NUM_BLOCKS, 0x02000226},
{ kpidNumVolumes, IDS_PROP_NUM_VOLUMES, 0x02000227},
{ kpidBit64, IDS_PROP_BIT64, 0x02000229},
{ kpidBigEndian, IDS_PROP_BIG_ENDIAN, 0x0200022A},
{ kpidCpu, IDS_PROP_CPU, 0x0200022B},
{ kpidPhySize, IDS_PROP_PHY_SIZE, 0x0200022C},
{ kpidHeadersSize, IDS_PROP_HEADERS_SIZE, 0x0200022D},
{ kpidChecksum, IDS_PROP_CHECKSUM, 0x0200022E},
{ kpidCharacts, IDS_PROP_CHARACTS, 0x0200022F},
{ kpidVa, IDS_PROP_VA, 0x02000230},
{ kpidId, IDS_PROP_ID, 0x02000231 },
{ kpidShortName, IDS_PROP_SHORT_NAME, 0x02000232 },
{ kpidCreatorApp, IDS_PROP_CREATOR_APP, 0x02000233 },
{ kpidSectorSize, IDS_PROP_SECTOR_SIZE, 0x02000234 },
{ kpidPosixAttrib, IDS_PROP_POSIX_ATTRIB, 0x02000235 },
{ kpidLink, IDS_PROP_LINK, 0x02000236 },
{ kpidTotalSize, IDS_PROP_TOTAL_SIZE, 0x03031100 },
{ kpidFreeSpace, IDS_PROP_FREE_SPACE, 0x03031101 },
{ kpidClusterSize, IDS_PROP_CLUSTER_SIZE, 0x03031102},
{ kpidVolumeName, IDS_PROP_VOLUME_NAME, 0x03031103 },
{ kpidLocalName, IDS_PROP_LOCAL_NAME, 0x03031200 },
{ kpidProvider, IDS_PROP_PROVIDER, 0x03031201 }
};
int FindProperty(PROPID propID)
{
for (int i = 0; i < sizeof(kPropertyIDNamePairs) / sizeof(kPropertyIDNamePairs[0]); i++)
if (kPropertyIDNamePairs[i].PropID == propID)
return i;
return -1;
}
UString GetNameOfProperty(PROPID propID, const wchar_t *name)
{
int index = FindProperty(propID);
if (index < 0)
{
if (name)
return name;
wchar_t s[16];
ConvertUInt32ToString(propID, s);
return s;
}
const CPropertyIDNamePair &pair = kPropertyIDNamePairs[index];
return LangString(pair.ResourceID, pair.LangID);
}
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/ClassDefs.cpp
// ClassDefs.cpp
#include "StdAfx.h"
#include "Common/MyInitGuid.h"
#include "PluginInterface.h"
#include "../Agent/Agent.h"
DEFINE_GUID(CLSID_CZipContextMenu,
0x23170F69, 0x40C1, 0x278A, 0x10, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00);
<file_sep>/7-Zip/CPP/7zip/Archive/Zip/ZipOut.cpp
// ZipOut.cpp
#include "StdAfx.h"
#include "../../Common/OffsetStream.h"
#include "ZipOut.h"
namespace NArchive {
namespace NZip {
void COutArchive::Create(IOutStream *outStream)
{
if (!m_OutBuffer.Create(1 << 16))
throw CSystemException(E_OUTOFMEMORY);
m_Stream = outStream;
m_OutBuffer.SetStream(outStream);
m_OutBuffer.Init();
m_BasePosition = 0;
}
void COutArchive::MoveBasePosition(UInt64 distanceToMove)
{
m_BasePosition += distanceToMove; // test overflow
}
void COutArchive::PrepareWriteCompressedDataZip64(UInt16 fileNameLength, bool isZip64, bool aesEncryption)
{
m_IsZip64 = isZip64;
m_ExtraSize = isZip64 ? (4 + 8 + 8) : 0;
if (aesEncryption)
m_ExtraSize += 4 + 7;
m_LocalFileHeaderSize = 4 + NFileHeader::kLocalBlockSize + fileNameLength + m_ExtraSize;
}
void COutArchive::PrepareWriteCompressedData(UInt16 fileNameLength, UInt64 unPackSize, bool aesEncryption)
{
// We test it to 0xF8000000 to support case when compressed size
// can be larger than uncompressed size.
PrepareWriteCompressedDataZip64(fileNameLength, unPackSize >= 0xF8000000, aesEncryption);
}
void COutArchive::PrepareWriteCompressedData2(UInt16 fileNameLength, UInt64 unPackSize, UInt64 packSize, bool aesEncryption)
{
bool isUnPack64 = unPackSize >= 0xFFFFFFFF;
bool isPack64 = packSize >= 0xFFFFFFFF;
bool isZip64 = isPack64 || isUnPack64;
PrepareWriteCompressedDataZip64(fileNameLength, isZip64, aesEncryption);
}
void COutArchive::WriteBytes(const void *buffer, UInt32 size)
{
m_OutBuffer.WriteBytes(buffer, size);
m_BasePosition += size;
}
void COutArchive::WriteByte(Byte b)
{
WriteBytes(&b, 1);
}
void COutArchive::WriteUInt16(UInt16 value)
{
for (int i = 0; i < 2; i++)
{
WriteByte((Byte)value);
value >>= 8;
}
}
void COutArchive::WriteUInt32(UInt32 value)
{
for (int i = 0; i < 4; i++)
{
WriteByte((Byte)value);
value >>= 8;
}
}
void COutArchive::WriteUInt64(UInt64 value)
{
for (int i = 0; i < 8; i++)
{
WriteByte((Byte)value);
value >>= 8;
}
}
void COutArchive::WriteExtra(const CExtraBlock &extra)
{
if (extra.SubBlocks.Size() != 0)
{
for (int i = 0; i < extra.SubBlocks.Size(); i++)
{
const CExtraSubBlock &subBlock = extra.SubBlocks[i];
WriteUInt16(subBlock.ID);
WriteUInt16((UInt16)subBlock.Data.GetCapacity());
WriteBytes(subBlock.Data, (UInt32)subBlock.Data.GetCapacity());
}
}
}
void COutArchive::SeekTo(UInt64 offset)
{
HRESULT res = m_Stream->Seek(offset, STREAM_SEEK_SET, NULL);
if (res != S_OK)
throw CSystemException(res);
}
void COutArchive::WriteLocalHeader(const CLocalItem &item)
{
SeekTo(m_BasePosition);
bool isZip64 = m_IsZip64 || item.PackSize >= 0xFFFFFFFF || item.UnPackSize >= 0xFFFFFFFF;
WriteUInt32(NSignature::kLocalFileHeader);
{
Byte ver = item.ExtractVersion.Version;
if (isZip64 && ver < NFileHeader::NCompressionMethod::kExtractVersion_Zip64)
ver = NFileHeader::NCompressionMethod::kExtractVersion_Zip64;
WriteByte(ver);
}
WriteByte(item.ExtractVersion.HostOS);
WriteUInt16(item.Flags);
WriteUInt16(item.CompressionMethod);
WriteUInt32(item.Time);
WriteUInt32(item.FileCRC);
WriteUInt32(isZip64 ? 0xFFFFFFFF: (UInt32)item.PackSize);
WriteUInt32(isZip64 ? 0xFFFFFFFF: (UInt32)item.UnPackSize);
WriteUInt16((UInt16)item.Name.Length());
{
UInt16 localExtraSize = (UInt16)((isZip64 ? (4 + 16): 0) + item.LocalExtra.GetSize());
if (localExtraSize > m_ExtraSize)
throw CSystemException(E_FAIL);
}
WriteUInt16((UInt16)m_ExtraSize); // test it;
WriteBytes((const char *)item.Name, item.Name.Length());
UInt32 extraPos = 0;
if (isZip64)
{
extraPos += 4 + 16;
WriteUInt16(NFileHeader::NExtraID::kZip64);
WriteUInt16(16);
WriteUInt64(item.UnPackSize);
WriteUInt64(item.PackSize);
}
WriteExtra(item.LocalExtra);
extraPos += (UInt32)item.LocalExtra.GetSize();
for (; extraPos < m_ExtraSize; extraPos++)
WriteByte(0);
m_OutBuffer.FlushWithCheck();
MoveBasePosition(item.PackSize);
SeekTo(m_BasePosition);
}
void COutArchive::WriteCentralHeader(const CItem &item)
{
bool isUnPack64 = item.UnPackSize >= 0xFFFFFFFF;
bool isPack64 = item.PackSize >= 0xFFFFFFFF;
bool isPosition64 = item.LocalHeaderPosition >= 0xFFFFFFFF;
bool isZip64 = isPack64 || isUnPack64 || isPosition64;
WriteUInt32(NSignature::kCentralFileHeader);
WriteByte(item.MadeByVersion.Version);
WriteByte(item.MadeByVersion.HostOS);
{
Byte ver = item.ExtractVersion.Version;
if (isZip64 && ver < NFileHeader::NCompressionMethod::kExtractVersion_Zip64)
ver = NFileHeader::NCompressionMethod::kExtractVersion_Zip64;
WriteByte(ver);
}
WriteByte(item.ExtractVersion.HostOS);
WriteUInt16(item.Flags);
WriteUInt16(item.CompressionMethod);
WriteUInt32(item.Time);
WriteUInt32(item.FileCRC);
WriteUInt32(isPack64 ? 0xFFFFFFFF: (UInt32)item.PackSize);
WriteUInt32(isUnPack64 ? 0xFFFFFFFF: (UInt32)item.UnPackSize);
WriteUInt16((UInt16)item.Name.Length());
UInt16 zip64ExtraSize = (UInt16)((isUnPack64 ? 8: 0) + (isPack64 ? 8: 0) + (isPosition64 ? 8: 0));
const UInt16 kNtfsExtraSize = 4 + 2 + 2 + (3 * 8);
UInt16 centralExtraSize = (UInt16)(isZip64 ? (4 + zip64ExtraSize) : 0) + (item.NtfsTimeIsDefined ? (4 + kNtfsExtraSize) : 0);
centralExtraSize = (UInt16)(centralExtraSize + item.CentralExtra.GetSize());
WriteUInt16(centralExtraSize); // test it;
WriteUInt16((UInt16)item.Comment.GetCapacity());
WriteUInt16(0); // DiskNumberStart;
WriteUInt16(item.InternalAttributes);
WriteUInt32(item.ExternalAttributes);
WriteUInt32(isPosition64 ? 0xFFFFFFFF: (UInt32)item.LocalHeaderPosition);
WriteBytes((const char *)item.Name, item.Name.Length());
if (isZip64)
{
WriteUInt16(NFileHeader::NExtraID::kZip64);
WriteUInt16(zip64ExtraSize);
if(isUnPack64)
WriteUInt64(item.UnPackSize);
if(isPack64)
WriteUInt64(item.PackSize);
if(isPosition64)
WriteUInt64(item.LocalHeaderPosition);
}
if (item.NtfsTimeIsDefined)
{
WriteUInt16(NFileHeader::NExtraID::kNTFS);
WriteUInt16(kNtfsExtraSize);
WriteUInt32(0); // reserved
WriteUInt16(NFileHeader::NNtfsExtra::kTagTime);
WriteUInt16(8 * 3);
WriteUInt32(item.NtfsMTime.dwLowDateTime);
WriteUInt32(item.NtfsMTime.dwHighDateTime);
WriteUInt32(item.NtfsATime.dwLowDateTime);
WriteUInt32(item.NtfsATime.dwHighDateTime);
WriteUInt32(item.NtfsCTime.dwLowDateTime);
WriteUInt32(item.NtfsCTime.dwHighDateTime);
}
WriteExtra(item.CentralExtra);
if (item.Comment.GetCapacity() > 0)
WriteBytes(item.Comment, (UInt32)item.Comment.GetCapacity());
}
void COutArchive::WriteCentralDir(const CObjectVector<CItem> &items, const CByteBuffer &comment)
{
SeekTo(m_BasePosition);
UInt64 cdOffset = GetCurrentPosition();
for(int i = 0; i < items.Size(); i++)
WriteCentralHeader(items[i]);
UInt64 cd64EndOffset = GetCurrentPosition();
UInt64 cdSize = cd64EndOffset - cdOffset;
bool cdOffset64 = cdOffset >= 0xFFFFFFFF;
bool cdSize64 = cdSize >= 0xFFFFFFFF;
bool items64 = items.Size() >= 0xFFFF;
bool isZip64 = (cdOffset64 || cdSize64 || items64);
if (isZip64)
{
WriteUInt32(NSignature::kZip64EndOfCentralDir);
WriteUInt64(kZip64EcdSize); // ThisDiskNumber = 0;
WriteUInt16(45); // version
WriteUInt16(45); // version
WriteUInt32(0); // ThisDiskNumber = 0;
WriteUInt32(0); // StartCentralDirectoryDiskNumber;;
WriteUInt64((UInt64)items.Size());
WriteUInt64((UInt64)items.Size());
WriteUInt64((UInt64)cdSize);
WriteUInt64((UInt64)cdOffset);
WriteUInt32(NSignature::kZip64EndOfCentralDirLocator);
WriteUInt32(0); // number of the disk with the start of the zip64 end of central directory
WriteUInt64(cd64EndOffset);
WriteUInt32(1); // total number of disks
}
WriteUInt32(NSignature::kEndOfCentralDir);
WriteUInt16(0); // ThisDiskNumber = 0;
WriteUInt16(0); // StartCentralDirectoryDiskNumber;
WriteUInt16((UInt16)(items64 ? 0xFFFF: items.Size()));
WriteUInt16((UInt16)(items64 ? 0xFFFF: items.Size()));
WriteUInt32(cdSize64 ? 0xFFFFFFFF: (UInt32)cdSize);
WriteUInt32(cdOffset64 ? 0xFFFFFFFF: (UInt32)cdOffset);
UInt16 commentSize = (UInt16)comment.GetCapacity();
WriteUInt16(commentSize);
if (commentSize > 0)
WriteBytes((const Byte *)comment, commentSize);
m_OutBuffer.FlushWithCheck();
}
void COutArchive::CreateStreamForCompressing(IOutStream **outStream)
{
COffsetOutStream *streamSpec = new COffsetOutStream;
CMyComPtr<IOutStream> tempStream(streamSpec);
streamSpec->Init(m_Stream, m_BasePosition + m_LocalFileHeaderSize);
*outStream = tempStream.Detach();
}
void COutArchive::SeekToPackedDataPosition()
{
SeekTo(m_BasePosition + m_LocalFileHeaderSize);
}
void COutArchive::CreateStreamForCopying(ISequentialOutStream **outStream)
{
CMyComPtr<ISequentialOutStream> tempStream(m_Stream);
*outStream = tempStream.Detach();
}
}}
<file_sep>/SQLCEHelper/Source/Table.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
CTable::CTable(CSession& session, LPCTSTR pszTableName)
: m_session (session),
m_strName (pszTableName)
{
}
// CTable::~CTable
//
// Destructor
//
CTable::~CTable()
{
}
// CTable::Open
//
// Open a table cursor using the optional index name
//
HRESULT CTable::Open(ULONG cPropSets, DBPROPSET rgPropSets[], LPCTSTR pszIndexName, CRowset &rowset)
{
HRESULT hr;
DBID dbidTable,
dbidIndex;
DBID* pIndexID = NULL;
CComPtr<IRowset> spRowset;
CComPtr<IUnknown> spUnknown(m_session);
CComPtr<IOpenRowset> spOpenRowset;
hr = spUnknown->QueryInterface(IID_IOpenRowset, (void**)&spOpenRowset);
if(FAILED(hr))
return hr;
dbidTable.eKind = DBKIND_NAME;
dbidTable.uName.pwszName = (LPOLESTR)GetName();
if(pszIndexName != NULL)
{
dbidIndex.eKind = DBKIND_NAME;
dbidIndex.uName.pwszName = (LPOLESTR)pszIndexName;
pIndexID = &dbidIndex;
}
// Get the IRowset interface
hr = spOpenRowset->OpenRowset(NULL, &dbidTable, pIndexID, IID_IRowset, cPropSets, rgPropSets, (IUnknown**)&spRowset);
if(FAILED(hr))
return hr;
hr = rowset.Open(spRowset);
return hr;
}
//-------------------------------------------------------------------------
//
// CTableDefinition class
//
//-------------------------------------------------------------------------
CTableDefinition::CTableDefinition()
: m_nColumns (0),
m_nPropSets (0),
m_nConstraints (0),
m_pColumns (NULL),
m_pConstraints (NULL),
m_pStrings (NULL),
m_pPropSets (NULL)
{
}
CTableDefinition::~CTableDefinition()
{
Clear();
}
// CTableDefinition::Clear
//
// Clears the stored table definition data
//
void CTableDefinition::Clear()
{
DBCOLUMNDESC* pColCur;
DBCONSTRAINTDESC* pConCur;
DBPROPSET* pSetCur;
ULONG i, j;
// Free the column items
for(pColCur = m_pColumns, i = 0; i < m_nColumns; ++i, ++pColCur)
{
if(pColCur->pTypeInfo != NULL)
CoTaskMemFree(pColCur->pTypeInfo);
if(pColCur->pclsid != NULL)
CoTaskMemFree(pColCur->pclsid);
CDbMemory::Free(pColCur->dbcid);
for(j = 0; j < pColCur->cPropertySets; ++j)
CDbMemory::Free(&pColCur->rgPropertySets[j]);
if(pColCur->rgPropertySets != NULL)
CoTaskMemFree(pColCur->rgPropertySets);
}
// Free the constraint items
for(pConCur = m_pConstraints, i = 0; i < m_nConstraints; ++i, ++pConCur)
{
for(j = 0; j < pConCur->cColumns; ++j)
CDbMemory::Free(pConCur->rgColumnList[j]);
if(pConCur->cColumns)
CoTaskMemFree(pConCur->rgColumnList);
for(j = 0; j < pConCur->cForeignKeyColumns; ++j)
CDbMemory::Free(pConCur->rgForeignKeyColumnList[j]);
if(pConCur->cForeignKeyColumns)
CoTaskMemFree(pConCur->rgForeignKeyColumnList);
CDbMemory::Free(*pConCur->pConstraintID);
if(pConCur->pReferencedTableID)
CDbMemory::Free(*pConCur->pReferencedTableID);
}
// Free the property sets
for(pSetCur = m_pPropSets, i = 0; i < m_nPropSets; ++i, ++pSetCur)
CDbMemory::Free(pSetCur);
// Free the column array
if(m_pColumns != NULL)
CoTaskMemFree(m_pColumns);
m_pColumns = NULL;
// Free the constraints array
if(m_pConstraints != NULL)
CoTaskMemFree(m_pConstraints);
m_pConstraints = NULL;
// Free the property sets array
if(m_pPropSets != NULL)
CoTaskMemFree(m_pPropSets);
m_pPropSets = NULL;
// Free the strings memory
if(m_pStrings != NULL)
CoTaskMemFree(m_pStrings);
m_pStrings = NULL;
}
// CTableDefinition::GetDefinition
//
// Retrieves the table definition for a given table name
//
HRESULT CTableDefinition::GetDefinition(CSession& session, LPCTSTR pszTableName)
{
CComPtr<ITableCreation> spTableCreation;
CComPtr<IUnknown> spUnknown(session);
HRESULT hr;
DBID dbidTable;
hr = spUnknown->QueryInterface(IID_ITableCreation, (void**)&spTableCreation);
if(FAILED(hr))
return hr;
Clear();
// Set the table name as the DBID
dbidTable.eKind = DBKIND_NAME;
dbidTable.uName.pwszName = (LPOLESTR)pszTableName;
// Get the table definition
hr = spTableCreation->GetTableDefinition(&dbidTable,
&m_nColumns, &m_pColumns,
&m_nPropSets, &m_pPropSets,
&m_nConstraints, &m_pConstraints,
&m_pStrings);
return hr;
}
// CTableDefinition::FillColumnArray
//
// Populates a column list from the table definition
//
bool CTableDefinition::FillColumnArray(CColumnArray& columns)
{
ULONG i;
size_t c, nColumns = columns.GetCount();
// Clear the column array
for(c = 0; c < nColumns; ++c)
delete columns[c];
columns.RemoveAll();
if(m_nColumns == 0)
return true;
for(i = 0; i < m_nColumns; ++i)
{
CColumn* pColumn = new CColumn(m_pColumns + i, i + 1);
if(pColumn == NULL)
return false;
columns.Add(pColumn);
}
return true;
}
// CTableDefinition::FillForeignKeyArray
//
// Populates a foreign key array from the table definition
//
bool CTableDefinition::FillForeignKeyArray(CForeignKeyArray& foreignKeys)
{
ULONG i;
size_t c, n = foreignKeys.GetCount();
// Clear the foreign key array
for(c = 0; c < n; ++c)
delete foreignKeys[c];
foreignKeys.RemoveAll();
for(i = 0; i < m_nConstraints; ++i)
{
if(m_pConstraints[i].ConstraintType == DBCONSTRAINTTYPE_FOREIGNKEY)
{
CForeignKey* pForeignKey = new CForeignKey(m_pConstraints + i);
if(pForeignKey == NULL)
return false;
foreignKeys.Add(pForeignKey);
}
}
return true;
}
// CTableDefinition::FillUniqueArray
//
// Fills an index array with the UNIQUE constraints
//
bool CTableDefinition::FillUniqueArray(CIndexArray& uniques)
{
ULONG i;
size_t c, n = uniques.GetCount();
// Clear the unique constraint array
for(c = 0; c < n; ++c)
delete uniques[c];
uniques.RemoveAll();
for(i = 0; i < m_nConstraints; ++i)
{
if(m_pConstraints[i].ConstraintType == DBCONSTRAINTTYPE_UNIQUE)
{
CIndex* pIndex = new CIndex(m_pConstraints + i);
if(pIndex == NULL)
return false;
uniques.Add(pIndex);
}
}
return true;
}
CIndex* CTableDefinition::GetPrimaryKey()
{
ULONG i;
for(i = 0; i < m_nConstraints; ++i)
{
if(m_pConstraints[i].ConstraintType == DBCONSTRAINTTYPE_PRIMARYKEY)
{
CIndex* pKey = new CIndex(m_pConstraints + i);
return pKey;
}
}
return NULL;
}
<file_sep>/FingerSuite/FingerMenuDLL/hook/sysdecls.h
/********************************************************************
Module : SpyEngine.h - part of CeApiSpyDll implementation
Copyright (c) 2003-2005 ForwardLab,Inc.
See readme.txt for terms and conditions.
Purpose: Contains redefinitions for some CE internal
structures and undocumented APIs
This file was compiled using eMbedded Visual C++ 4.0
with Pocket PC 2003 and Smartphone 2003 SDKs,
Visual Studio 2005 Beta 2 with Pocket PC 2005, Smartphone 2005 SDKs
********************************************************************/
#ifndef _SYS_DECLS_H_
#define _SYS_DECLS_H_
/******** Beginning of undocumented functions declarations *******/
extern "C"
{
//The following functions exported from coredll.dll are documented in
//Platform Builder help and declared in
//PUBLIC\COMMON\OAK\INC\pkfuncs.h,
//but not in SDK, so declare them here:
DWORD __stdcall SetProcPermissions(DWORD);
LPVOID __stdcall MapCallerPtr(LPVOID ptr, DWORD dwLen);
LPVOID __stdcall MapPtrToProcess (LPVOID lpv, HANDLE hProc);
LPVOID __stdcall UnMapPtr(LPVOID lpv);
HANDLE __stdcall GetOwnerProcess (void);
HANDLE __stdcall GetCallerProcess (void);
BOOL __stdcall SetKMode(BOOL fMode);
BOOL __stdcall IsAPIReady(DWORD hAPI);
//The following are undocumented structures declared in
//PUBLIC\COMMON\OAK\INC\pkfuncs.h, which we have to redeclare here.
//WARNING: undocumented structures and functions may change in the
//future.
struct CALLBACKINFO
{
HANDLE m_hDestinationProcessHandle;
FARPROC m_pFunction;
PVOID m_pFirstArgument;
};
//The following undocumented functions exported from coredll.dll
//and declared in PUBLIC\COMMON\OAK\INC\pkfuncs.h,
//but not in SDK, so declare them here:
//WARNING: undocumented structures and functions may change in the
//future.
HANDLE __stdcall CreateAPISet(char acName[4], USHORT cFunctions,
const PFNVOID *ppfnMethods, const DWORD *pdwSig);
BOOL __stdcall RegisterAPISet(HANDLE hASet, DWORD dwSetID);
int __stdcall QueryAPISetID(char *pName);
FARPROC __stdcall GetAPIAddress(int setId, int iMethod);
HLOCAL __stdcall LocalAllocInProcess(UINT uFlags, UINT uBytes,
HPROCESS hProc);
HANDLE __stdcall GetProcFromPtr(LPVOID p);
DWORD __stdcall PerformCallBack4(CALLBACKINFO *pcbi,
DWORD dw1, DWORD dw2, DWORD dw3);
BOOL __stdcall GetRomFileInfo(DWORD type,
LPWIN32_FIND_DATA lpfd, DWORD count);
DWORD __stdcall GetProcessIndexFromID(HANDLE hProc);
LPBYTE __stdcall THCreateSnapshot(DWORD dwFlags, DWORD dwProcID);
//The following are API handles from PUBLIC\COMMON\OAK\INC\psyscall.h
//(in addition to SH_* handles defined in SDK kfuncs.h file).
#define HT_EVENT 4
#define HT_MUTEX 5
#define HT_APISET 6
#define HT_FILE 7
#define HT_FIND 8
#define HT_DBFILE 9
#define HT_DBFIND 10
#define HT_SOCKET 11
#define HT_INTERFACE 12
#define HT_SEMAPHORE 13
#define HT_FSMAP 14
#define HT_WNETENUM 15
//The following are some methods in the SH_WIN32 table.
//The full list is in psyscall.h.
#define W32_LoadLibraryW 8 //Disappeared in CE 5.0. Use W32_LoadLibraryExW
#define W32_GetRomFileInfo 32
#define W32_CreateProc 53
#define W32_CeGetCurrentTrust 85
#define W32_PerformCallBack 113
#define W32_DebugNotify 118
#define W32_LoadLibraryExW 148
//The following are some methods in the SH_FILESYS_APIS table.
#define FILESYS_CreateFile 9
//The following are some methods in the SH_WMGR table.
#define WMGR_TrackPopupMenuEx 63
#define WMGR_DrawIconEx 79
#define WMGR_MessageBoxW 50
//The following are some methods in the SH_SHELL table. (defined in kfuncs.h and C:\WINCE600\PRIVATE\SHELL\SHELLPSL\HAVEAYGSHELL\api.cpp)
#define SHELL_SHNotificationAddII 55
#define SHELL_SHNotificationUpdateII 56
#define SHELL_SHNotificationRemoveII 57
#define SHELL_SHNotificationGetDataII 58
}//extern "C"
/******** End of undocumented functions declarations *************/
/******** Beginning of kernel data structure declarations ********/
//The key for accessing CE kernel data structure (KDataStruct) is
//PUserKData. PUserKData is defined in kfuncs.h in SDK as 0xFFFFC800
//on ARM and 0x00005800 on other CPUs. It is used in the same header
//to define macros GetCurrentThreadId and GetCurrentProcessId, which
//directly access the kernel data structures.
//Several kernel data structures are accessed using predefined
//offsets from PUserKData. For example, SYSHANDLE_OFFSET (defined in
//kfuncs.h), gives access to an array of system handles, KINFO_OFFSET
//(defined in PUBLIC\COMMON\OAK\INC\pkfuncs.h) gives access to
//UserKInfo array. About 30 indexes in this array are defined in
//pkfuncs.h (KINX_*) to provide access to such kernel data structures
//as process array, module list, kernel heap, etc.
//Here we are only interested in KINX_APISETS and KINX_API_MASK.
//KINX_APISETS slot holds a pointer to an array of system API sets
//(SystemAPISets).
//KINX_API_MASK slot is a bit mask of installed APIs.
#define KINFO_OFFSET 0x300
#define KINX_API_MASK 18
#define KINX_APISETS 24
#define UserKInfo ((long *)(PUserKData+KINFO_OFFSET))
//I will not bother redeclaring this large structure.
//I will only define offsets to 2 fields used in DumpApis():
#define PROCESS_NUM_OFFSET 0 //process number (index of the slot)
#define PROCESS_NAME_OFFSET 0x20 //pointer to the process name
//pointer to struct Process declared in Kernel.h.
typedef struct Process PROCESS;
typedef PROCESS *PPROCESS;
//Also declare structure CINFO, which holds an information
//about an API (originally declared in
//PRIVATE\WINCEOS\COREOS\NK\INC\Kernel.h).
struct CINFO
{
char m_szApiName[4];//used in CreateAPISet and QueryAPISetID
BYTE m_byDispatchType;//kernel vs user mode,
//handle-based vs direct.
BYTE m_byApiHandle;//ID of the API, such as
//SH_WIN32, SH_SHELL, etc.
WORD m_wNumMethods;//number of methods listed in array
//m_ppMethods
PFNVOID* m_ppMethods; //array of pointers to methods
DWORD * m_pdwMethodSignatures;//DWORD-encoded methods arguments
PPROCESS m_pProcessServer;//pointer to a process,
//which serves this API.
};
//pkfuncs.h defines a lot of signature generation macros for methods
//with different number of arguments. The purpose of signatures is to
//figure out which arguments are pointers, so the dispatcher may
//properly map them. We only need to redefine a single macro
//FNSIG0(), which means that no arguments will be mapped.
#define FNSIG0() 0
//psyscall.h defined macros for calling API methods,
//such as IMPLICIT_CALL
#if defined(x86)
#define FIRST_METHOD 0xFFFFFE00
#define APICALL_SCALE 2
#elif defined(ARM)
#define FIRST_METHOD 0xF0010000
#define APICALL_SCALE 4
#elif defined(SHx)
#define FIRST_METHOD 0xFFFFFE01
#define APICALL_SCALE 2
#else
#error "Unknown CPU type"
#endif
#define HANDLE_SHIFT 8
#define IMPLICIT_CALL(ApiID, MethodIdx) \
(FIRST_METHOD - ((ApiID)<<HANDLE_SHIFT | (MethodIdx))*APICALL_SCALE)
/******** End of kernel data structure declarations **************/
#endif //SYS_DECLS<file_sep>/FingerSuite/FingerMenuCTRL/MenuWindow.h
// WTLApp1View.h : interface of the CWTLApp1View class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#ifndef __FNGRSCRL_H__
#error menu.h requires fngrscrl.h to be included first
#endif
#define IDT_TIMER_MENU_ANIMATION 10110
#define TMR_MENU_ANIMATION 10
#define BORDER_WIDTH 10
#define UM_MINIMIZE WM_USER + 2
#define UM_SETNEWMENU WM_USER + 4
#define UM_GETDESTWND WM_USER + 5
class CMenuWindow : public CWindowImpl<CMenuWindow>, public CFingerScrollImpl<CMenuWindow, true, true>
{
public:
DECLARE_WND_CLASS(NULL)
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
CMenuWindow ()
{
m_idxDPadSelected = -1;
}
void DoPaint(CDCHandle dc)
{
// must be implemented in a derived class
RECT rc; GetClientRect(&rc);
SIZE imgSize;
imgSize.cx = m_imgSubmenuImage.GetWidth();
imgSize.cy = m_imgSubmenuImage.GetHeight();
// font
CFont oldFont = dc.SelectFont(m_fText);
for (int i = 0; i < m_menuItems.GetSize(); i++)
{
MENUINFO mi = (MENUINFO)m_menuItems[i];
COLORREF clText;
COLORREF clBkg = m_clBkg;
if ((i == m_idxSelected) || (i == m_idxDPadSelected))
{
clText = m_clSelText;
}
else
{
clText = m_clText;
}
if (mi.mii.fState & MF_GRAYED)
{
clText = m_clDisabledText;
}
RECT rcItem = {0, i * m_itemHeight, rc.right, (i + 1) * m_itemHeight };
// draw rectangle without borders
CBrush br; br.CreateSolidBrush(clBkg);
CBrush brOld = dc.SelectBrush(br);
CPen pen; pen.CreatePen(PS_NULL, 1, RGB(255,255,255));
CPen penOld = dc.SelectPen(pen);
dc.Rectangle(&rcItem);
dc.SelectPen(penOld);
dc.SelectBrush(brOld);
if ((i == m_idxSelected) && !(mi.mii.fState & MF_GRAYED))
{
m_imgSelectionImage.Draw(dc, rcItem);
}
// draw dpad selection
if ( i == m_idxDPadSelected)
{
m_imgDPadCursorImage.Draw(dc, rcItem);
}
// draw bottom line
if (m_menuItems[i].bFollowSeparator)
{
// solid line 1px
CPen pen2; pen2.CreatePen(PS_SOLID, 1, m_clLine);
CPen penOld2 = dc.SelectPen(pen2);
dc.MoveTo(rcItem.left, rcItem.bottom - 1);
dc.LineTo(rcItem.right, rcItem.bottom - 1);
dc.SelectPen(penOld2);
}
else
{
// dotted line 1px
CPen pen2; pen2.CreatePen(PS_DASH, 1, m_clLine);
CPen penOld2 = dc.SelectPen(pen2);
dc.MoveTo(rcItem.left, rcItem.bottom - 1);
dc.LineTo(rcItem.right, rcItem.bottom - 1);
dc.SelectPen(penOld2);
}
// draw text
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(clText);
dc.DrawText(m_menuItems[i].text, -1, &rcItem, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
if (mi.mii.fType & MFT_RADIOCHECK)
{
if (mi.mii.fState & MFS_CHECKED)
{
RECT rcImg = {rcItem.right - imgSize.cx, rcItem.top, rcItem.right, rcItem.top + imgSize.cy};
m_imgRadioCheckedImage.Draw(dc, rcImg);
}
else
{
RECT rcImg = {rcItem.right - imgSize.cx, rcItem.top, rcItem.right, rcItem.top + imgSize.cy};
m_imgRadioUncheckedImage.Draw(dc, rcImg);
}
}
else
{
// draw check mark
if (mi.mii.fState & MFS_CHECKED)
{
RECT rcImg = {rcItem.right - imgSize.cx, rcItem.top, rcItem.right, rcItem.top + imgSize.cy};
m_imgCheckedImage.Draw(dc, rcImg);
}
}
// draw sub menu icon
if (mi.mii.hSubMenu != NULL)
{
RECT rcImg = {rcItem.right - imgSize.cx, rcItem.top, rcItem.right, rcItem.top + imgSize.cy};
m_imgSubmenuImage.Draw(dc, rcImg);
}
if (mi.mii.fType & MFT_OWNERDRAW)
{
CDC dcTemp; dcTemp.CreateCompatibleDC(dc);
DRAWITEMSTRUCT dis;
ZeroMemory(&dis, sizeof(DRAWITEMSTRUCT));
dis.CtlType = ODT_MENU;
dis.itemID = mi.mii.wID;
dis.itemAction = ODA_DRAWENTIRE;
//dis.itemState = ODS_SELECTED; // TODO
dis.hwndItem = (HWND)mi.hOwnerMenu;
dis.hDC = dc;
CopyRect(&dis.rcItem, &rcItem);
InflateRect(&dis.rcItem, 0, -8 * m_scaleFactor);
dis.itemData = mi.mii.dwItemData;
//LOG(L"Avvio draw....");
LRESULT lResult = SendMessageRemote(mi.hDestWnd, WM_DRAWITEM, 0, (LPARAM)&dis, sizeof(DRAWITEMSTRUCT), 50);
if (lResult == 0)
{
GetParent().GetParent().PostMessage(WM_COMMAND, ID_MENU_SHOWORIGINAL, 0);
return;
}
//LOG(L"......completato\n");
}
}
dc.SelectFont(oldFont);
// draw scroll bar
if (!m_bAnimating)
{
int totalHeight = m_menuItems.GetSize() * m_itemHeight;
if (rc.bottom < totalHeight)
{
int height = (int)(((float)rc.bottom / (float)totalHeight) * rc.bottom);
int top = (int)(((float)GetOffset() / (float)totalHeight) * rc.bottom);
RECT rcScrollbar;
rcScrollbar.right = rc.right;
rcScrollbar.left = rcScrollbar.right - 3 * m_scaleFactor;
rcScrollbar.top = top + GetOffset();
rcScrollbar.bottom = rcScrollbar.top + height;
dc.FillSolidRect(&rcScrollbar, m_clScrollbar);
}
}
}
typedef CWindowImpl<CMenuWindow> winbaseClass;
typedef CFingerScrollImpl<CMenuWindow, true, true> scrollbaseClass;
BEGIN_MSG_MAP(CMenuWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
CHAIN_MSG_MAP(scrollbaseClass)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
RECT rc; GetClientRect(&rc);
SetFingerScrollRegion(m_menuItems.GetSize() * m_itemHeight, rc.bottom);
}
bHandled = FALSE;
return 0;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
m_xPos = LOWORD(lParam);
m_yPos = HIWORD(lParam);
m_bMouseIsDown = TRUE;
m_idxSelected = (GetOffset() + m_yPos) / m_itemHeight;
m_idxDPadSelected = -1;
if ((m_idxSelected >= 0) && (m_idxSelected < m_menuItems.GetSize()))
{
InvalidateRect(NULL, FALSE);
UpdateWindow();
}
else
m_idxSelected = -1;
bHandled = FALSE; // very important
return 0;
}
LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
int y = HIWORD(lParam);
if (abs(y - m_yPos) > GetThreshold())
{
if (m_idxSelected != -1)
{
m_idxSelected = -1;
InvalidateRect(NULL, FALSE);
UpdateWindow();
}
}
m_yPos = HIWORD(lParam);
bHandled = FALSE; // very important
return 0;
}
LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
/*
if (m_bMouseIsDown)
{
// back gesture recognition
int xPosNew = LOWORD(lParam);
if ((m_xPos - xPosNew) > 100 * m_scaleFactor)
{
// back gesture recognized
if (Back())
{
bHandled = FALSE; // very important
return 0;
}
}
}
*/
m_bMouseIsDown = FALSE;
// normal mode
if (m_idxSelected != -1)
{
MENUINFO mi = (MENUINFO)m_menuItems[m_idxSelected];
if (!(mi.mii.fState & MF_GRAYED))
{
if (mi.mii.hSubMenu != NULL)
{
// manage submenu
LPMENU pMu = NULL;
for (int i = 0; i < m_menus.GetSize(); i++)
{
if (m_menus[i].hMenu == mi.mii.hSubMenu)
{
pMu = &m_menus[i];
break;
}
}
if (pMu == NULL)
{
MENU m;
m.hMenu = mi.mii.hSubMenu;
m.bInitMenuSent = FALSE;
m.hPrevMenu = mi.hOwnerMenu;
m_menus.Add(m);
}
GetParent().GetParent().SendMessage(UM_SETNEWMENU, (WPARAM)mi.mii.hSubMenu);
}
else
{
GetParent().GetParent().SendMessage(UM_MINIMIZE, (WPARAM)mi.mii.wID, 0);
}
}
}
bHandled = FALSE; // very important
return 0;
}
public:
COLORREF m_clBkg;
COLORREF m_clText;
COLORREF m_clSelText;
COLORREF m_clDisabledText;
COLORREF m_clLine;
COLORREF m_clScrollbar;
CFontHandle m_fText;
int m_itemHeight;
int m_scaleFactor;
BOOL m_bAnimating;
CxImage m_imgSubmenuImage;
CxImage m_imgCheckedImage;
CxImage m_imgRadioCheckedImage;
CxImage m_imgRadioUncheckedImage;
CxImage m_imgSelectionImage;
CxImage m_imgDPadCursorImage;
int m_idxDPadSelected;
int m_xPos;
int m_yPos;
int m_idxSelected;
protected:
HRGN m_hRgn;
BOOL m_bMouseIsDown;
};
class CWrapMenuWindow : public CWindowImpl<CWrapMenuWindow>
{
public:
CMenuWindow m_menu;
DECLARE_WND_CLASS(NULL)
CWrapMenuWindow ()
{
m_nMaxMenuItemCount = 1000;
m_bMouseIsDown = FALSE;
}
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
void SetMaxMenuItemCount(int value)
{
m_nMaxMenuItemCount = value;
}
void SetScaleFactor(int value)
{
m_scaleFactor = value;
m_menu.m_scaleFactor = value;
m_menu.SetThreshold(5 * m_scaleFactor);
}
int GetScaleFactor()
{
return m_scaleFactor;
}
void SetItemHeight(int value)
{
m_itemHeight = value; //* m_scaleFactor;
m_menu.m_itemHeight = value; // * m_scaleFactor;
}
void SetButtonHeight(int value)
{
m_buttonHeight = value;
}
int GetItemHeight()
{
return m_itemHeight;
}
/*
void SetUsedRect(int value)
{
m_nUsedRects = value * m_scaleFactor;
}
*/
BOOL Show()
{
ModifyShape();
StartAnimation();
return TRUE;
}
BEGIN_MSG_MAP(CWrapMenuWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
//MESSAGE_HANDLER(UM_STARTANIM, OnStartAnim)
MESSAGE_HANDLER(UM_SCRL_NOTIFY, OnScrlNotify)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
ModifyTopShape();
// menu
m_menu.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE |WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
RECT rc; GetClientRect(&rc);
if ((m_menuItems.GetSize() > m_nMaxMenuItemCount) && (!m_bNoButtons))
{
rc.top += m_buttonHeight;
rc.bottom -= m_buttonHeight;
m_bButtonsVisible = TRUE;
}
m_menu.MoveWindow(&rc, TRUE);
return 0;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
RECT rc; GetClientRect(&rc);
CBufferedPaintDC dc(m_hWnd, 0);
if (m_bButtonsVisible)
{
RECT rcItem; CopyRect(&rcItem, &rc);
rcItem.bottom = m_buttonHeight;
RECT rcArrow; CopyRect(&rcArrow, &rcItem);
int w = m_bmpBtnArrowUp.GetWidth();
int h = m_bmpBtnArrowUp.GetHeight();
int dx = (w - rcItem.right)/2;
int dy = (h - rcItem.bottom)/2;
InflateRect(&rcArrow, dx, dy);
rcArrow.right = rcArrow.left + w;
rcArrow.bottom = rcArrow.top + h;
if (m_bBtnUpDisabled)
{
m_bmpBtnUpDisabled.Draw(dc, rcItem);
}
else if (m_bBtnUpPressed)
{
m_bmpBtnUpPressed.Draw(dc, rcItem);
// draw arrow
m_bmpBtnArrowUp.Draw(dc, rcArrow);
}
else
{
m_bmpBtnUp.Draw(dc, rcItem);
// draw arrow
m_bmpBtnArrowUp.Draw(dc, rcArrow);
}
CopyRect(&rcItem, &rc);
rcItem.top = rcItem.bottom - m_buttonHeight;
CopyRect(&rcArrow, &rcItem);
w = m_bmpBtnArrowDown.GetWidth();
h = m_bmpBtnArrowDown.GetHeight();
dx = (w - rcItem.right)/2;
dy = (h - (rcItem.bottom - rcItem.top))/2;
InflateRect(&rcArrow, dx, dy);
rcArrow.right = rcArrow.left + w;
rcArrow.bottom = rcArrow.top + h;
if (m_bBtnDownDisabled)
{
m_bmpBtnDownDisabled.Draw(dc, rcItem);
}
else if (m_bBtnDownPressed)
{
m_bmpBtnDownPressed.Draw(dc, rcItem);
// draw arrow
m_bmpBtnArrowDown.Draw(dc, rcArrow);
}
else
{
m_bmpBtnDown.Draw(dc, rcItem);
// draw arrow
m_bmpBtnArrowDown.Draw(dc, rcArrow);
}
}
return 0;
}
LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if (wParam == IDT_TIMER_MENU_ANIMATION)
{
m_iStep = m_iStep / 2;
//int iVisibleItems = min(m_nMaxMenuItemCount, m_menu.GetMenuItemCount());
//MoveWindow(&m_rect, TRUE);
RECT animRect; CopyRect(&animRect, &m_animRect);
animRect.top = animRect.top + m_iStep;
MoveWindow(&animRect, TRUE);
if (m_iStep == 0)
{
KillTimer(IDT_TIMER_MENU_ANIMATION);
m_bAnimating = FALSE;
m_menu.m_bAnimating = FALSE;
m_iStep = 0;
}
bHandled = TRUE;
return 0;
}
bHandled = FALSE;
return 0;
}
//LRESULT OnStartAnim(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
//{
// ModifyShape();
// StartAnimation();
// return 0;
//}
LRESULT OnScrlNotify(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if (!m_bAnimating)
{
BOOL bUpdate = FALSE;
int offset = (int)wParam;
if (offset == 0)
{
bUpdate = (m_bBtnUpDisabled != TRUE);
m_bBtnUpDisabled = TRUE;
}
if (offset == m_menu.GetScrollableAreaHeight())
{
bUpdate = (m_bBtnDownDisabled != TRUE);
m_bBtnDownDisabled = TRUE;
}
if ((offset > 0) && (offset < m_menu.GetScrollableAreaHeight()))
{
bUpdate = (m_bBtnUpDisabled != FALSE) || (m_bBtnDownDisabled != FALSE);
m_bBtnUpDisabled = FALSE;
m_bBtnDownDisabled = FALSE;
}
if (bUpdate)
{
InvalidateRect(NULL, TRUE);
UpdateWindow();
}
}
return 0;
}
LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
RECT rc; GetClientRect(&rc);
UINT yPos = HIWORD(lParam);
m_menu.m_idxDPadSelected = -1;
m_bMouseIsDown = TRUE;
if ((yPos < m_itemHeight) && (!(m_bBtnUpDisabled)))
{
m_bBtnUpPressed = TRUE;
RECT rcBtn; CopyRect(&rcBtn, &rc);
rcBtn.bottom = m_itemHeight;
InvalidateRect(&rcBtn, FALSE);
UpdateWindow();
}
if ((yPos > (rc.bottom - m_itemHeight)) && (!(m_bBtnDownDisabled)))
{
m_bBtnDownPressed = TRUE;
RECT rcBtn; CopyRect(&rcBtn, &rc);
rcBtn.top = rc.bottom - m_itemHeight;
InvalidateRect(&rcBtn, FALSE);
UpdateWindow();
}
return 0;
}
LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
RECT rc; GetClientRect(&rc);
UINT yPos = HIWORD(lParam);
if (m_bMouseIsDown)
{
if ((yPos < m_itemHeight) && (!(m_bBtnUpDisabled)))
{
m_bBtnUpPressed = FALSE;
int d = (m_menu.GetOffset() - 3 * m_itemHeight) - ( (m_menu.GetOffset() - 3 * m_itemHeight) % m_itemHeight );
m_menu.ScrollTo(d);
RECT rcBtn; CopyRect(&rcBtn, &rc);
rcBtn.bottom = m_itemHeight;
InvalidateRect(&rcBtn, FALSE);
UpdateWindow();
}
if ((yPos > (rc.bottom - m_itemHeight)) && (!(m_bBtnDownDisabled)))
{
m_bBtnDownPressed = FALSE;
int d = (m_menu.GetOffset() + 3 * m_itemHeight) - ( (m_menu.GetOffset() + 3 * m_itemHeight) % m_itemHeight );
m_menu.ScrollTo(d);
RECT rcBtn; CopyRect(&rcBtn, &rc);
rcBtn.top = rc.bottom - m_itemHeight;
InvalidateRect(&rcBtn, FALSE);
UpdateWindow();
}
}
m_bMouseIsDown = FALSE;
return 0;
}
LRESULT OnKeyDown(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
static int nKeyRepeatCount = 0;
int nVirtKey = (int)wParam;
BOOL bUpdate = FALSE;
BOOL bRepeating = (lParam & (1 << 30)) != 0;
if (bRepeating)
{
nKeyRepeatCount++;
if (nKeyRepeatCount % 5 != 0)
return 0;
}
else
{
nKeyRepeatCount = 0;
}
switch (nVirtKey)
{
case VK_LEFT:
GetParent().SendMessage(WM_COMMAND, (WPARAM)ID_BACK);
break;
case VK_RIGHT:
case VK_RETURN:
if ((m_menu.m_idxDPadSelected >= 0) && (m_menu.m_idxDPadSelected < m_menuItems.GetSize()))
{
m_menu.m_idxSelected = m_menu.m_idxDPadSelected;
m_menu.SendMessage(WM_LBUTTONUP, 0, MAKELPARAM(m_menu.m_xPos, m_menu.m_yPos) ); //(LPARAM)m_menu.m_xPos);
}
else
{
// as requested select first item
m_menu.m_idxDPadSelected = 0;
m_menu.m_idxSelected = m_menu.m_idxDPadSelected;
m_menu.SendMessage(WM_LBUTTONUP, 0, MAKELPARAM(0, m_menu.m_yPos) );
}
break;
case VK_UP:
if ((m_menu.m_idxDPadSelected >= 0) && (m_menu.m_idxDPadSelected < m_menuItems.GetSize()))
{
bUpdate = TRUE;
m_menu.m_idxDPadSelected --;
if (m_menu.m_idxDPadSelected < (m_menuItems.GetSize() - 3))
{
int d = (m_menu.GetOffset() - m_itemHeight) - ( (m_menu.GetOffset() - m_itemHeight) % m_itemHeight );
m_menu.ScrollTo(d);
}
}
else
{
// mi metto sull'ultimo visibile
bUpdate = TRUE;
m_menu.ScrollTo((m_menuItems.GetSize() - 1) * m_itemHeight);
m_menu.m_idxDPadSelected = m_menuItems.GetSize() - 1;
}
break;
case VK_DOWN:
if ((m_menu.m_idxDPadSelected >= 0) && (m_menu.m_idxDPadSelected < m_menuItems.GetSize()))
{
bUpdate = TRUE;
m_menu.m_idxDPadSelected ++;
if (m_menu.m_idxDPadSelected > 2)
{
int d = (m_menu.GetOffset() + m_itemHeight) - ( (m_menu.GetOffset() + m_itemHeight) % m_itemHeight );
m_menu.ScrollTo(d);
}
}
else
{
// mi metto sul primo visibile
bUpdate = TRUE;
m_menu.ScrollTo(0);
m_menu.m_idxDPadSelected = 0;
}
break;
}
if (bUpdate)
{
m_menu.m_idxDPadSelected = min(m_menu.m_idxDPadSelected, m_menuItems.GetSize() - 1);
m_menu.m_idxDPadSelected = max(m_menu.m_idxDPadSelected, 0);
m_menu.Invalidate(FALSE);
m_menu.UpdateWindow();
}
return 0;
}
//HBITMAP m_bmpBtnUp;
//HBITMAP m_bmpBtnUpPressed;
//HBITMAP m_bmpBtnUpDisabled;
//HBITMAP m_bmpBtnDown;
//HBITMAP m_bmpBtnDownPressed;
//HBITMAP m_bmpBtnDownDisabled;
CxImage m_bmpBtnUp;
CxImage m_bmpBtnUpPressed;
CxImage m_bmpBtnUpDisabled;
CxImage m_bmpBtnDown;
CxImage m_bmpBtnDownPressed;
CxImage m_bmpBtnDownDisabled;
CxImage m_bmpBtnArrowUp;
CxImage m_bmpBtnArrowDown;
DWORD m_iMaxVisibleItemCount;
BOOL m_bNoButtons;
BOOL m_bEnableAnimation;
void ModifyTopShape()
{
int nUsedRects = 3 * m_scaleFactor;
m_heightHrgnTop = nUsedRects;
if (m_hrgnTop != NULL)
{
DeleteObject(m_hrgnTop);
m_hrgnTop = NULL;
}
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor;
RGNDATA *pRgnData;
RECT *pRect;
DWORD dwTemp = sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT);
pRgnData = (RGNDATA*)malloc(dwTemp);
pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRgnData->rdh.iType = RDH_RECTANGLES;
pRgnData->rdh.nCount = nUsedRects;
pRgnData->rdh.nRgnSize = 0;
pRgnData->rdh.rcBound.left = pRgnData->rdh.rcBound.top=0;
pRgnData->rdh.rcBound.right = iWidth;
pRgnData->rdh.rcBound.bottom = nUsedRects;
/*
for (int i = 0; i < nUsedRects; i++)
{
pRect=&(((RECT *)&pRgnData->Buffer)[i]);
pRect->top = i;
pRect->bottom = i + 1;
pRect->left = nUsedRects - i;
pRect->right = iWidth - (nUsedRects - i);
}
*/
if (nUsedRects == 3)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 2;
pRect->right = iWidth - 2;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 1;
pRect->right = iWidth - 1;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 0;
pRect->right = iWidth;
}
else if (nUsedRects == 6)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 5;
pRect->right = iWidth - 5;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 3;
pRect->right = iWidth - 3;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 2;
pRect->right = iWidth - 2;
// 4th
pRect = &(((RECT *)&pRgnData->Buffer)[3]);
pRect->top = 3;
pRect->bottom = 4;
pRect->left = 1;
pRect->right = iWidth - 1;
// 5th
pRect = &(((RECT *)&pRgnData->Buffer)[4]);
pRect->top = 4;
pRect->bottom = 5;
pRect->left = 1;
pRect->right = iWidth - 1;
// 6th
pRect = &(((RECT *)&pRgnData->Buffer)[5]);
pRect->top = 5;
pRect->bottom = 6;
pRect->left = 0;
pRect->right = iWidth;
}
m_hrgnTop = ExtCreateRegion(NULL, dwTemp, pRgnData);
free(pRgnData);
}
public:
//int m_nUsedRects; //6 for VGA
int m_itemHeight;
int m_buttonHeight;
RECT m_animRect;
BOOL m_bAnimating;
int m_iStep;
BOOL m_bButtonsVisible;
int m_nMaxMenuItemCount;
BOOL m_bBtnUpDisabled;
BOOL m_bBtnUpPressed;
BOOL m_bBtnDownDisabled;
BOOL m_bBtnDownPressed;
int m_scaleFactor;
int m_height;
BOOL m_bMouseIsDown;
HRGN m_hrgnTop;
int m_heightHrgnTop;
void ModifyShape()
{
m_height = 0;
BOOL bButtonsVisible = FALSE;
if ((m_menuItems.GetSize() > m_nMaxMenuItemCount) && (!m_bNoButtons))
{
bButtonsVisible = TRUE;
}
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor;
int nMaxMenuItemCount = (rcParent.bottom - rcParent.top) / m_itemHeight;
m_nMaxMenuItemCount = min( m_iMaxVisibleItemCount, nMaxMenuItemCount );
int nMenuItemCount = m_menuItems.GetSize();
int nItems = (nMenuItemCount == 0) ? 2 : nMenuItemCount;
int iVisibleItems = min(m_nMaxMenuItemCount, nItems);
HRGN hrgnBottom = NULL;
if (bButtonsVisible)
{
hrgnBottom = ::CreateRectRgn(0, 0, iWidth, m_buttonHeight - m_heightHrgnTop);
m_height += m_buttonHeight;
}
else
{
hrgnBottom = ::CreateRectRgn(0, 0, iWidth, m_itemHeight - m_heightHrgnTop);
m_height += m_itemHeight;
}
::OffsetRgn(hrgnBottom, 0, m_heightHrgnTop);
CombineRgn(hrgnBottom, m_hrgnTop, hrgnBottom, RGN_OR);
HRGN hrgnFinal = NULL;
if (bButtonsVisible)
{
hrgnFinal = CreateRectRgn(0, m_buttonHeight, iWidth, (iVisibleItems - 1) * m_itemHeight + m_buttonHeight);
}
else
{
hrgnFinal = CreateRectRgn(0, m_itemHeight, iWidth, iVisibleItems * m_itemHeight);
}
m_height += (iVisibleItems - 1) * m_itemHeight;
int res = CombineRgn(hrgnFinal, hrgnBottom, hrgnFinal, RGN_OR);
if (res > 0)
{
SetWindowRgn(hrgnFinal, FALSE);
}
}
void StartAnimation()
{
// window position
m_bAnimating = (m_bEnableAnimation) ? TRUE : FALSE;
m_menu.m_bAnimating = (m_bEnableAnimation) ? TRUE : FALSE;
m_iStep = (m_bEnableAnimation) ? m_itemHeight / 3 : 0;
RECT rcParent; GetParent().GetClientRect(&rcParent);
m_animRect.left = BORDER_WIDTH * m_scaleFactor;
m_animRect.right = rcParent.right - BORDER_WIDTH * m_scaleFactor;
m_animRect.top = rcParent.bottom - m_height;
m_animRect.bottom = rcParent.bottom;
RECT animRect; CopyRect(&animRect, &m_animRect);
animRect.top = animRect.top + m_iStep;
MoveWindow(&animRect, TRUE);
m_bBtnDownDisabled = FALSE;
m_bBtnUpDisabled = TRUE;
m_bBtnDownPressed = FALSE;
m_bBtnUpPressed = FALSE;
if (m_bEnableAnimation)
SetTimer(IDT_TIMER_MENU_ANIMATION, TMR_MENU_ANIMATION);
}
};
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdType.h
// PpmdType.h
// 2009-05-30 : <NAME> : Public domain
// This code is based on <NAME>'s PPMdH code (public domain)
#ifndef __COMPRESS_PPMD_TYPE_H
#define __COMPRESS_PPMD_TYPE_H
const int kMaxOrderCompress = 32;
const int MAX_O = 255; /* maximum allowed model order */
template <class T>
inline void _PPMD_SWAP(T& t1,T& t2) { T tmp = t1; t1 = t2; t2 = tmp; }
#endif
<file_sep>/FingerSuite/Common/ext/RegionBuilder.cpp
//////////////////////////////////////////////////////////////////////////
// CRegionBuilder - fast HRGN creation for WinCE/PocketPC/Win32
// coded by dzolee - http://dzolee.blogspot.com
//////////////////////////////////////////////////////////////////////////
#include "StdAfx.h"
#include "RegionBuilder.h"
//////////////////////////////////////////////////////////////////////////
CRegionBuilder::CRegionBuilder()
{
}
//////////////////////////////////////////////////////////////////////////
CRegionBuilder::~CRegionBuilder()
{
}
//////////////////////////////////////////////////////////////////////////
RegionBuilderError CRegionBuilder::BuildRegion(HBITMAP hBmp, HRGN *pDest)
{
register LONG x, y, lW;
register DWORD *pCurrentDW, dwCurrent, nCurrentBit;
RegionBuilderError retval;
BITMAP bmp;
BITMAPINFO *pBmpInfo;
void *pBits;
HBITMAP hDIB;
LONG lH, nTotalDWsPerRow, nUsedBits, nUsedRects, nCurrentRect, start_x;
HDC dcDisplay, dcSrc, dcDest;
HGDIOBJ hSrcOldObj, hDestOldObj;
DWORD dwTemp;
bool bNotTransparent;
HRGN hRgn;
RGNDATA *pRgnData;
RECT *pRect;
//zero result
*pDest=NULL;
//get bitmap dimensions
if(GetObject(hBmp, sizeof(BITMAP), &bmp) == 0)
{
return rbeGDIError;
}
lW=bmp.bmWidth;
lH=bmp.bmHeight;
//alloc buffer for bmp header plus 2 colors (black and white)
pBmpInfo=(BITMAPINFO *)malloc(sizeof(BITMAPINFOHEADER) + 2 * sizeof(RGBQUAD));
//if failed to alloc...
if(pBmpInfo == NULL)
{
return rbeNoMem;
}
//size of structure included in structure
pBmpInfo->bmiHeader.biSize=sizeof(BITMAPINFOHEADER);
//copy dimensions
pBmpInfo->bmiHeader.biWidth=lW;
pBmpInfo->bmiHeader.biHeight=lH;
//always one plane
pBmpInfo->bmiHeader.biPlanes=1;
//monochrome
pBmpInfo->bmiHeader.biBitCount=1;
//colors stored as RGBQUADs
pBmpInfo->bmiHeader.biCompression=BI_RGB;
//number of bytes. each scanline is padded to a multiple of 4 -- courtesy of <NAME>
pBmpInfo->bmiHeader.biSizeImage = (DWORD)(((lW+7) & 0xfffffff8) * lH/8);
//dummy values
pBmpInfo->bmiHeader.biXPelsPerMeter=1000000;
pBmpInfo->bmiHeader.biYPelsPerMeter=1000000;
//2 colors used: black and white
pBmpInfo->bmiHeader.biClrUsed=2;
pBmpInfo->bmiHeader.biClrImportant=2;
//now the RGBQUAD table: first entry is "black", second entry is "white".
pBmpInfo->bmiColors[0].rgbBlue=pBmpInfo->bmiColors[0].rgbGreen=pBmpInfo->bmiColors[0].rgbRed=pBmpInfo->bmiColors[0].rgbReserved=0;
pBmpInfo->bmiColors[1].rgbBlue=pBmpInfo->bmiColors[1].rgbGreen=pBmpInfo->bmiColors[1].rgbRed=pBmpInfo->bmiColors[1].rgbReserved=255;
//create bitmap
hDIB=CreateDIBSection(NULL, pBmpInfo, DIB_RGB_COLORS, &pBits, NULL, 0);
//free unused mem
free(pBmpInfo);
if(hDIB == NULL)
{
//error
return rbeGDIError;
}
//get a DC to the display
dcDisplay=::GetDC(NULL);
if(dcDisplay == NULL)
{
//failed
DeleteObject(hDIB);
return rbeGDIError;
}
//create compatible DCs for source (input) and destination (monochrome) bitmap
dcSrc=CreateCompatibleDC(dcDisplay);
//failed to create DC?
if(dcSrc == NULL)
{
//clean up
DeleteObject(hDIB);
::ReleaseDC(NULL, dcDisplay);
return rbeGDIError;
}
dcDest=CreateCompatibleDC(dcDisplay);
//release display DC as soon as it is not needed anymore
::ReleaseDC(NULL, dcDisplay);
if(dcDest == NULL)
{
DeleteDC(dcSrc);
DeleteObject(hDIB);
return rbeGDIError;
}
//select source and destination bitmaps into DCs
hSrcOldObj=SelectObject(dcSrc, hBmp);
hDestOldObj=SelectObject(dcDest, hDIB);
retval=rbeGDIError;
//copy source bitmap to destination (monochrome)
if(TRUE == ::BitBlt(dcDest, 0, 0, lW, lH, dcSrc, 0, 0, SRCCOPY))
{
//copy ok - now we have bits at pBits
//first calculate the number of RECTs required
//calculate DWORDs per row
if(lW > 32)
{
nTotalDWsPerRow=lW / 32;
//if number of pixels does not exactly fit into DWORD boundary
if(lW % 32 != 0)
{
//one more DWORD needed to store row
nTotalDWsPerRow++;
}
}
else
{
//simple case, DWORD count is 1
nTotalDWsPerRow=1;
}
//for every row (backwards scan because image is flipped)
nUsedBits=nUsedRects=0;
bNotTransparent=false;
for(y=lH-1; y>=0; y--)
{
//pointer to first DWORD in row
pCurrentDW=((DWORD *)pBits + y * nTotalDWsPerRow);
nCurrentBit=0;
start_x=0;
for(x=0; x<lW; x++)
{
if(nCurrentBit == 0)
{
//we can access the buffer by DWORDs but the result needs to be bswapped
dwCurrent=ByteSwap(*pCurrentDW);
}
if(dwCurrent & 0x80000000)
{
//bit 1
nUsedBits++;
if(bNotTransparent == false)
{
//start line
bNotTransparent=true;
start_x=x;
}
}
else
{
if(bNotTransparent == true)
{
//if was in a line, end line
bNotTransparent=false;
nUsedRects++;
}
}
dwCurrent<<=1;
//next bit
nCurrentBit++;
if(nCurrentBit == 32)
{
nCurrentBit=0;
pCurrentDW++;
}
//end of row reached?
if(x == lW-1)
{
if(bNotTransparent == true)
{
//finish line
bNotTransparent=false;
nUsedRects++;
}
}
}//for x
}//for y
//alloc mem for region data
dwTemp=sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT);
pRgnData=(RGNDATA *)malloc(dwTemp);
if(pRgnData == NULL)
{
//clean up and exit
SelectObject(dcSrc, hSrcOldObj);
SelectObject(dcDest, hDestOldObj);
DeleteObject(hDIB);
DeleteDC(dcSrc);
DeleteDC(dcDest);
return rbeGDIError;
}
//now build array of RECTs for region
bNotTransparent=false;
nCurrentRect=0;
for(y=lH-1; y>=0; y--)
{
//pointer to first DWORD in row
pCurrentDW=((DWORD *)pBits + y * nTotalDWsPerRow);
nCurrentBit=0;
start_x=0;
for(x=0; x<lW; x++)
{
if(nCurrentBit == 0)
{
//we can access the buffer by DWORDs but the result needs to be bswapped
dwCurrent=ByteSwap(*pCurrentDW);
}
if(dwCurrent & 0x80000000)
{
//bit 1
nUsedBits++;
if(bNotTransparent == false)
{
bNotTransparent=true;
start_x=x;
}
}
else
{
if(bNotTransparent == true)
{
bNotTransparent=false;
pRect=&(((RECT *)&pRgnData->Buffer)[nCurrentRect]);
pRect->left=start_x;
pRect->right=x;
pRect->top=lH-y-1;
pRect->bottom=lH-y;
nCurrentRect++;
}
}
dwCurrent<<=1;
//next bit
nCurrentBit++;
if(nCurrentBit == 32)
{
nCurrentBit=0;
pCurrentDW++;
}
//end of row reached?
if(x == lW-1)
{
if(bNotTransparent == true)
{
//finish line
bNotTransparent=false;
pRect=&(((RECT *)&pRgnData->Buffer)[nCurrentRect]);
pRect->left=start_x;
pRect->right=x;
pRect->top=lH-y-1;
pRect->bottom=lH-y;
nCurrentRect++;
}
}
}//for x
}//for y
//last step: region creation
//build region data header
pRgnData->rdh.dwSize=sizeof(RGNDATAHEADER);
pRgnData->rdh.iType=RDH_RECTANGLES;
pRgnData->rdh.nCount=nCurrentRect;
pRgnData->rdh.nRgnSize=nCurrentRect * sizeof(RECT);
pRgnData->rdh.rcBound.left=pRgnData->rdh.rcBound.top=0;
pRgnData->rdh.rcBound.right=lW;
pRgnData->rdh.rcBound.bottom=lH;
//create region
hRgn=ExtCreateRegion(NULL, sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT), pRgnData);
//free RECT data
free(pRgnData);
if(hRgn != NULL)
{
//clean up and return success
*pDest=hRgn;
retval=rbeOK;
}
}//if BitBlt succeeded
//clean up and exit
SelectObject(dcSrc, hSrcOldObj);
SelectObject(dcDest, hDestOldObj);
DeleteObject(hDIB);
DeleteDC(dcSrc);
DeleteDC(dcDest);
return retval;
}
//////////////////////////////////////////////////////////////////////////
//code from stdlib
inline DWORD CRegionBuilder::ByteSwap(DWORD dwIn)
{
DWORD j;
j = (dwIn << 24);
j += (dwIn << 8) & 0x00ff0000;
j += (dwIn >> 8) & 0x0000ff00;
j += (dwIn >> 24);
return j;
}
<file_sep>/7-Zip/CPP/7zip/Archive/Rar/RarIn.h
// RarIn.h
#ifndef __ARCHIVE_RAR_IN_H
#define __ARCHIVE_RAR_IN_H
#include "Common/DynamicBuffer.h"
#include "Common/MyCom.h"
#include "../../ICoder.h"
#include "../../IStream.h"
#include "../../Common/StreamObjects.h"
#include "../../Crypto/RarAes.h"
#include "RarHeader.h"
#include "RarItem.h"
namespace NArchive {
namespace NRar {
class CInArchiveException
{
public:
enum CCauseType
{
kUnexpectedEndOfArchive = 0,
kArchiveHeaderCRCError,
kFileHeaderCRCError,
kIncorrectArchive
}
Cause;
CInArchiveException(CCauseType cause) : Cause(cause) {}
};
class CInArchiveInfo
{
public:
UInt64 StartPosition;
UInt16 Flags;
UInt64 CommentPosition;
UInt16 CommentSize;
bool IsSolid() const { return (Flags & NHeader::NArchive::kSolid) != 0; }
bool IsCommented() const { return (Flags & NHeader::NArchive::kComment) != 0; }
bool IsVolume() const { return (Flags & NHeader::NArchive::kVolume) != 0; }
bool HaveNewVolumeName() const { return (Flags & NHeader::NArchive::kNewVolName) != 0; }
bool IsEncrypted() const { return (Flags & NHeader::NArchive::kBlockEncryption) != 0; }
};
class CInArchive
{
CMyComPtr<IInStream> m_Stream;
UInt64 m_StreamStartPosition;
UInt64 m_Position;
UInt64 m_ArchiveStartPosition;
NHeader::NArchive::CHeader360 m_ArchiveHeader;
CDynamicBuffer<char> m_NameBuffer;
CDynamicBuffer<wchar_t> _unicodeNameBuffer;
bool m_SeekOnArchiveComment;
UInt64 m_ArchiveCommentPosition;
void ReadName(CItemEx &item, int nameSize);
void ReadHeaderReal(CItemEx &item);
HRESULT ReadBytes(void *data, UInt32 size, UInt32 *aProcessedSize);
bool ReadBytesAndTestSize(void *data, UInt32 size);
void ReadBytesAndTestResult(void *data, UInt32 size);
HRESULT FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit);
HRESULT Open2(IInStream *stream, const UInt64 *searchHeaderSizeLimit);
void ThrowExceptionWithCode(CInArchiveException::CCauseType cause);
void ThrowUnexpectedEndOfArchiveException();
void AddToSeekValue(UInt64 addValue);
CDynamicBuffer<Byte> m_FileHeaderData;
NHeader::NBlock::CBlock m_BlockHeader;
NCrypto::NRar29::CDecoder *m_RarAESSpec;
CMyComPtr<ICompressFilter> m_RarAES;
Byte *m_CurData; // it must point to start of Rar::Block
UInt32 m_CurPos;
UInt32 m_PosLimit;
Byte ReadByte();
UInt16 ReadUInt16();
UInt32 ReadUInt32();
void ReadTime(Byte mask, CRarTime &rarTime);
CBuffer<Byte> m_DecryptedData;
Byte *m_DecryptedDataAligned;
UInt32 m_DecryptedDataSize;
bool m_CryptoMode;
UInt32 m_CryptoPos;
void FinishCryptoBlock()
{
if (m_CryptoMode)
while ((m_CryptoPos & 0xF) != 0)
{
m_CryptoPos++;
m_Position++;
}
}
public:
HRESULT Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit);
void Close();
HRESULT GetNextItem(CItemEx &item, ICryptoGetTextPassword *getTextPassword, bool &decryptionError);
void SkipArchiveComment();
void GetArchiveInfo(CInArchiveInfo &archiveInfo) const;
bool SeekInArchive(UInt64 position);
ISequentialInStream *CreateLimitedStream(UInt64 position, UInt64 size);
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Bundles/Fm/makefile
PROG = 7zFM.exe
CFLAGS = $(CFLAGS) -I ../../../ \
-DLANG \
-DNEW_FOLDER_INTERFACE \
-DEXTERNAL_CODECS \
!IFDEF UNDER_CE
LIBS = $(LIBS) ceshell.lib Commctrl.lib
!ELSE
LIBS = $(LIBS) comctl32.lib htmlhelp.lib comdlg32.lib Mpr.lib Gdi32.lib
CFLAGS = $(CFLAGS) -DWIN_LONG_PATH -DSUPPORT_DEVICE_FILE
!ENDIF
FM_OBJS = \
$O\App.obj \
$O\BrowseDialog.obj \
$O\ClassDefs.obj \
$O\EnumFormatEtc.obj \
$O\ExtractCallback.obj \
$O\FileFolderPluginOpen.obj \
$O\FilePlugins.obj \
$O\FM.obj \
$O\FoldersPage.obj \
$O\FormatUtils.obj \
$O\FSFolder.obj \
$O\FSFolderCopy.obj \
$O\HelpUtils.obj \
$O\LangUtils.obj \
$O\MenuPage.obj \
$O\MyLoadMenu.obj \
$O\OpenCallback.obj \
$O\OptionsDialog.obj \
$O\Panel.obj \
$O\PanelCopy.obj \
$O\PanelCrc.obj \
$O\PanelDrag.obj \
$O\PanelFolderChange.obj \
$O\PanelItemOpen.obj \
$O\PanelItems.obj \
$O\PanelKey.obj \
$O\PanelListNotify.obj \
$O\PanelMenu.obj \
$O\PanelOperations.obj \
$O\PanelSelect.obj \
$O\PanelSort.obj \
$O\PanelSplitFile.obj \
$O\ProgramLocation.obj \
$O\PropertyName.obj \
$O\RegistryAssociations.obj \
$O\RegistryPlugins.obj \
$O\RegistryUtils.obj \
$O\RootFolder.obj \
$O\SplitUtils.obj \
$O\StringUtils.obj \
$O\SysIconUtils.obj \
$O\TextPairs.obj \
$O\UpdateCallback100.obj \
$O\ViewSettings.obj \
$O\AboutDialog.obj \
$O\ComboDialog.obj \
$O\CopyDialog.obj \
$O\EditPage.obj \
$O\LangPage.obj \
$O\ListViewDialog.obj \
$O\MessagesDialog.obj \
$O\OverwriteDialog.obj \
$O\PasswordDialog.obj \
$O\PluginsPage.obj \
$O\ProgressDialog2.obj \
$O\SettingsPage.obj \
$O\SplitDialog.obj \
$O\SystemPage.obj \
COMMON_OBJS = \
$O\CommandLineParser.obj \
$O\CRC.obj \
$O\IntToString.obj \
$O\Lang.obj \
$O\ListFileUtils.obj \
$O\MyMap.obj \
$O\MyString.obj \
$O\MyVector.obj \
$O\MyXml.obj \
$O\NewHandler.obj \
$O\Random.obj \
$O\StringConvert.obj \
$O\StringToInt.obj \
$O\TextConfig.obj \
$O\UTFConvert.obj \
$O\Wildcard.obj \
WIN_OBJS = \
$O\Clipboard.obj \
$O\DLL.obj \
$O\Error.obj \
$O\FileDir.obj \
$O\FileFind.obj \
$O\FileIO.obj \
$O\FileName.obj \
$O\Memory.obj \
$O\MemoryLock.obj \
$O\Menu.obj \
$O\Process.obj \
$O\PropVariant.obj \
$O\PropVariantConversions.obj \
$O\PropVariantUtils.obj \
$O\Registry.obj \
$O\ResourceString.obj \
$O\Shell.obj \
$O\Synchronization.obj \
$O\System.obj \
$O\Time.obj \
$O\Window.obj \
!IFNDEF UNDER_CE
FM_OBJS = $(FM_OBJS) \
$O\FSDrives.obj \
$O\NetFolder.obj \
WIN_OBJS = $(WIN_OBJS) \
$O\CommonDialog.obj \
$O\FileSystem.obj \
$O\Net.obj \
$O\Security.obj \
!ENDIF
WIN_CTRL_OBJS = \
$O\ComboBox.obj \
$O\Dialog.obj \
$O\ListView.obj \
$O\PropertyPage.obj \
$O\Window2.obj \
7ZIP_COMMON_OBJS = \
$O\CreateCoder.obj \
$O\CWrappers.obj \
$O\FilePathAutoRename.obj \
$O\FileStreams.obj \
$O\FilterCoder.obj \
$O\InBuffer.obj \
$O\InOutTempBuffer.obj \
$O\LimitedStreams.obj \
$O\LockedStream.obj \
$O\MemBlocks.obj \
$O\MethodId.obj \
$O\MethodProps.obj \
$O\OffsetStream.obj \
$O\OutBuffer.obj \
$O\OutMemStream.obj \
$O\ProgressMt.obj \
$O\ProgressUtils.obj \
$O\StreamBinder.obj \
$O\StreamObjects.obj \
$O\StreamUtils.obj \
$O\VirtThread.obj \
AR_OBJS = \
$O\ArjHandler.obj \
$O\Bz2Handler.obj \
$O\CpioHandler.obj \
$O\DebHandler.obj \
$O\DeflateProps.obj \
$O\DmgHandler.obj \
$O\ElfHandler.obj \
$O\FatHandler.obj \
$O\FlvHandler.obj \
$O\GzHandler.obj \
$O\LzhHandler.obj \
$O\LzmaHandler.obj \
$O\MachoHandler.obj \
$O\MbrHandler.obj \
$O\MslzHandler.obj \
$O\MubHandler.obj \
$O\NtfsHandler.obj \
$O\PeHandler.obj \
$O\RpmHandler.obj \
$O\SplitHandler.obj \
$O\SwfHandler.obj \
$O\VhdHandler.obj \
$O\XarHandler.obj \
$O\XzHandler.obj \
$O\ZHandler.obj \
AR_COMMON_OBJS = \
$O\CoderMixer2.obj \
$O\CoderMixer2MT.obj \
$O\CrossThreadProgress.obj \
$O\DummyOutStream.obj \
$O\FindSignature.obj \
$O\InStreamWithCRC.obj \
$O\ItemNameUtils.obj \
$O\MultiStream.obj \
$O\OutStreamWithCRC.obj \
$O\OutStreamWithSha1.obj \
$O\HandlerOut.obj \
$O\ParseProperties.obj \
UI_COMMON_OBJS = \
$O\ArchiveCommandLine.obj \
$O\ArchiveExtractCallback.obj \
$O\ArchiveName.obj \
$O\ArchiveOpenCallback.obj \
$O\Bench.obj \
$O\CompressCall2.obj \
$O\DefaultName.obj \
$O\EnumDirItems.obj \
$O\Extract.obj \
$O\ExtractingFilePath.obj \
$O\LoadCodecs.obj \
$O\OpenArchive.obj \
$O\PropIDUtils.obj \
$O\SetProperties.obj \
$O\SortUtils.obj \
$O\TempFiles.obj \
$O\Update.obj \
$O\UpdateAction.obj \
$O\UpdateCallback.obj \
$O\UpdatePair.obj \
$O\UpdateProduce.obj \
$O\WorkDir.obj \
$O\ZipRegistry.obj \
AGENT_OBJS = \
$O\Agent.obj \
$O\AgentOut.obj \
$O\AgentProxy.obj \
$O\ArchiveFolder.obj \
$O\ArchiveFolderOpen.obj \
$O\ArchiveFolderOut.obj \
$O\UpdateCallbackAgent.obj \
EXPLORER_OBJS = \
$O\ContextMenu.obj \
$O\MyMessages.obj \
$O\RegistryContextMenu.obj \
GUI_OBJS = \
$O\BenchmarkDialog.obj \
$O\CompressDialog.obj \
$O\ExtractDialog.obj \
$O\ExtractGUI.obj \
$O\UpdateCallbackGUI.obj \
$O\UpdateGUI.obj \
7Z_OBJS = \
$O\7zCompressionMode.obj \
$O\7zDecode.obj \
$O\7zEncode.obj \
$O\7zExtract.obj \
$O\7zFolderInStream.obj \
$O\7zFolderOutStream.obj \
$O\7zHandler.obj \
$O\7zHandlerOut.obj \
$O\7zHeader.obj \
$O\7zIn.obj \
$O\7zOut.obj \
$O\7zProperties.obj \
$O\7zSpecStream.obj \
$O\7zUpdate.obj \
$O\7zRegister.obj \
CAB_OBJS = \
$O\CabBlockInStream.obj \
$O\CabHandler.obj \
$O\CabHeader.obj \
$O\CabIn.obj \
$O\CabRegister.obj \
CHM_OBJS = \
$O\ChmHandler.obj \
$O\ChmHeader.obj \
$O\ChmIn.obj \
$O\ChmRegister.obj \
COM_OBJS = \
$O\ComHandler.obj \
$O\ComIn.obj \
$O\ComRegister.obj \
HFS_OBJS = \
$O\HfsHandler.obj \
$O\HfsIn.obj \
$O\HfsRegister.obj \
ISO_OBJS = \
$O\IsoHandler.obj \
$O\IsoHeader.obj \
$O\IsoIn.obj \
$O\IsoRegister.obj \
NSIS_OBJS = \
$O\NsisDecode.obj \
$O\NsisHandler.obj \
$O\NsisIn.obj \
$O\NsisRegister.obj \
RAR_OBJS = \
$O\RarHandler.obj \
$O\RarHeader.obj \
$O\RarIn.obj \
$O\RarItem.obj \
$O\RarVolumeInStream.obj \
$O\RarRegister.obj \
TAR_OBJS = \
$O\TarHandler.obj \
$O\TarHandlerOut.obj \
$O\TarHeader.obj \
$O\TarIn.obj \
$O\TarOut.obj \
$O\TarUpdate.obj \
$O\TarRegister.obj \
UDF_OBJS = \
$O\UdfHandler.obj \
$O\UdfIn.obj \
$O\UdfRegister.obj \
WIM_OBJS = \
$O\WimHandler.obj \
$O\WimIn.obj \
$O\WimRegister.obj \
ZIP_OBJS = \
$O\ZipAddCommon.obj \
$O\ZipHandler.obj \
$O\ZipHandlerOut.obj \
$O\ZipHeader.obj \
$O\ZipIn.obj \
$O\ZipItem.obj \
$O\ZipOut.obj \
$O\ZipUpdate.obj \
$O\ZipRegister.obj \
COMPRESS_OBJS = \
$O\ArjDecoder1.obj \
$O\ArjDecoder2.obj \
$O\Bcj2Coder.obj \
$O\Bcj2Register.obj \
$O\BcjCoder.obj \
$O\BcjRegister.obj \
$O\BitlDecoder.obj \
$O\BranchCoder.obj \
$O\BranchMisc.obj \
$O\BranchRegister.obj \
$O\ByteSwap.obj \
$O\BZip2Crc.obj \
$O\BZip2Decoder.obj \
$O\BZip2Encoder.obj \
$O\BZip2Register.obj \
$O\CopyCoder.obj \
$O\CopyRegister.obj \
$O\Deflate64Register.obj \
$O\DeflateDecoder.obj \
$O\DeflateEncoder.obj \
$O\DeflateNsisRegister.obj \
$O\DeflateRegister.obj \
$O\DeltaFilter.obj \
$O\ImplodeDecoder.obj \
$O\ImplodeHuffmanDecoder.obj \
$O\LzhDecoder.obj \
$O\Lzma2Decoder.obj \
$O\Lzma2Encoder.obj \
$O\Lzma2Register.obj \
$O\LzmaDecoder.obj \
$O\LzmaEncoder.obj \
$O\LzmaRegister.obj \
$O\LzOutWindow.obj \
$O\Lzx86Converter.obj \
$O\LzxDecoder.obj \
$O\PpmdDecoder.obj \
$O\PpmdEncoder.obj \
$O\PpmdRegister.obj \
$O\QuantumDecoder.obj \
$O\Rar1Decoder.obj \
$O\Rar2Decoder.obj \
$O\Rar3Decoder.obj \
$O\Rar3Vm.obj \
$O\RarCodecsRegister.obj \
$O\ShrinkDecoder.obj \
$O\ZlibDecoder.obj \
$O\ZlibEncoder.obj \
$O\ZDecoder.obj \
CRYPTO_OBJS = \
$O\7zAes.obj \
$O\7zAesRegister.obj \
$O\HmacSha1.obj \
$O\MyAes.obj \
$O\Pbkdf2HmacSha1.obj \
$O\RandGen.obj \
$O\Rar20Crypto.obj \
$O\RarAes.obj \
$O\Sha1.obj \
$O\WzAes.obj \
$O\ZipCrypto.obj \
$O\ZipStrong.obj \
C_OBJS = \
$O\7zBuf2.obj \
$O\7zStream.obj \
$O\Alloc.obj \
$O\Bra.obj \
$O\Bra86.obj \
$O\BraIA64.obj \
$O\BwtSort.obj \
$O\CpuArch.obj \
$O\Delta.obj \
$O\HuffEnc.obj \
$O\LzFind.obj \
$O\LzFindMt.obj \
$O\Lzma2Dec.obj \
$O\Lzma2Enc.obj \
$O\LzmaDec.obj \
$O\LzmaEnc.obj \
$O\MtCoder.obj \
$O\Sha256.obj \
$O\Sort.obj \
$O\Threads.obj \
$O\Xz.obj \
$O\XzCrc64.obj \
$O\XzDec.obj \
$O\XzEnc.obj \
$O\XzIn.obj \
!include "../../Aes.mak"
!include "../../Crc.mak"
OBJS = \
$O\StdAfx.obj \
$(FM_OBJS)\
$(COMMON_OBJS) \
$(WIN_OBJS) \
$(WIN_CTRL_OBJS) \
$(7ZIP_COMMON_OBJS) \
$(AR_OBJS) \
$(AR_COMMON_OBJS) \
$(UI_COMMON_OBJS) \
$(AGENT_OBJS) \
$(EXPLORER_OBJS) \
$(GUI_OBJS) \
$(7Z_OBJS) \
$(CAB_OBJS) \
$(CHM_OBJS) \
$(COM_OBJS) \
$(HFS_OBJS) \
$(ISO_OBJS) \
$(NSIS_OBJS) \
$(RAR_OBJS) \
$(TAR_OBJS) \
$(UDF_OBJS) \
$(WIM_OBJS) \
$(ZIP_OBJS) \
$(COMPRESS_OBJS) \
$(CRYPTO_OBJS) \
$(C_OBJS) \
$(ASM_OBJS) \
$O\resource.res \
!include "../../../Build.mak"
$(FM_OBJS): ../../UI/FileManager/$(*B).cpp
$(COMPL)
$(COMMON_OBJS): ../../../Common/$(*B).cpp
$(COMPL)
$(WIN_OBJS): ../../../Windows/$(*B).cpp
$(COMPL)
$(WIN_CTRL_OBJS): ../../../Windows/Control/$(*B).cpp
$(COMPL)
$(7ZIP_COMMON_OBJS): ../../Common/$(*B).cpp
$(COMPL)
$(AR_OBJS): ../../Archive/$(*B).cpp
$(COMPL)
$(AR_COMMON_OBJS): ../../Archive/Common/$(*B).cpp
$(COMPL)
$(7Z_OBJS): ../../Archive/7z/$(*B).cpp
$(COMPL)
$(CAB_OBJS): ../../Archive/Cab/$(*B).cpp
$(COMPL)
$(CHM_OBJS): ../../Archive/Chm/$(*B).cpp
$(COMPL)
$(COM_OBJS): ../../Archive/Com/$(*B).cpp
$(COMPL)
$(HFS_OBJS): ../../Archive/Hfs/$(*B).cpp
$(COMPL)
$(ISO_OBJS): ../../Archive/Iso/$(*B).cpp
$(COMPL)
$(NSIS_OBJS): ../../Archive/Nsis/$(*B).cpp
$(COMPL)
$(RAR_OBJS): ../../Archive/Rar/$(*B).cpp
$(COMPL)
$(TAR_OBJS): ../../Archive/Tar/$(*B).cpp
$(COMPL)
$(UDF_OBJS): ../../Archive/Udf/$(*B).cpp
$(COMPL)
$(WIM_OBJS): ../../Archive/Wim/$(*B).cpp
$(COMPL)
$(ZIP_OBJS): ../../Archive/Zip/$(*B).cpp
$(COMPL)
$(COMPRESS_OBJS): ../../Compress/$(*B).cpp
$(COMPL_O2)
$(CRYPTO_OBJS): ../../Crypto/$(*B).cpp
$(COMPL_O2)
$(UI_COMMON_OBJS): ../../UI/Common/$(*B).cpp
$(COMPL)
$(AGENT_OBJS): ../../UI/Agent/$(*B).cpp
$(COMPL)
$(EXPLORER_OBJS): ../../UI/Explorer/$(*B).cpp
$(COMPL)
$(GUI_OBJS): ../../UI/GUI/$(*B).cpp
$(COMPL)
$(C_OBJS): ../../../../C/$(*B).c
$(COMPL_O2)
!include "../../Asm.mak"
<file_sep>/FBReaderJ/jni/LineBreak/TxtParser.cpp
#include "TxtParser.h"
#include <jni.h>
#include "../Ext_Type.h"
#include "../HanvonUtil.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
enum
{
ENCODING_UNKNOWN,
ENCODING_ASCII,
ENCODING_LATIN1,
ENCODING_UTF8,
ENCODING_UTF16BE,
ENCODING_UTF16LE,
ENCODING_UTF32BE,
ENCODING_UTF32LE,
ENCODING_UCS2, /* Native byte order assumed */
ENCODING_UCS4,
/* Native byte order assumed */
};
#define UNKNOWN_ASCII '?'
#define UNKNOWN_UNICODE 0xFFFD
enum
{
bit7 = 0x80,
bit6 = 0x40,
bit5 = 0x20,
bit4 = 0x10,
bit3 = 8,
bit2 = 4,
bit1 = 2,
bit0 = 1
};
long
Hanvoniconv(int from, int to, const unsigned char *inbuf, unsigned int inbytesleft,
unsigned char *outbuf, unsigned int outbytesleft)
{
const unsigned char *src = NULL;
const unsigned char *dst = NULL;
unsigned int srclen, dstlen;
int ch = 0;
unsigned int total = 0;
if (!inbuf)
{
/* Reset the context */
return 0;
}
if (!outbuf || !outbytesleft)
{
return 0;
}
src = inbuf;
srclen = inbytesleft;
dst = outbuf;
dstlen = outbytesleft;
total = 0;
while (srclen > 0)
{
/* Decode a character */
switch (from)
{
case ENCODING_ASCII:
{
unsigned char *p = (unsigned char *) src;
ch = (unsigned int) (p[0] & 0x7F);
++src;
--srclen;
}
break;
case ENCODING_LATIN1:
{
unsigned char *p = (unsigned char *) src;
ch = (unsigned int) p[0];
++src;
--srclen;
}
break;
case ENCODING_UTF8: /* RFC 3629 */
{
unsigned char *p = (unsigned char *) src;
unsigned char a = 0, b = 0, c = 0;
a = *p++;
src++;
--srclen;
if ((a & (bit7 | bit6 | bit5)) == (bit7 | bit6))
{ // 0x000080-0x0007ff
{
b = *p++;
src++;
--srclen;
ch = (unsigned short) (((a & (bit4 | bit3 | bit2)) >> 2)
* 0x100);
ch += (unsigned short) (((a & (bit1 | bit0)) << 6) | (b
& (bit5 | bit4 | bit3 | bit2 | bit1 | bit0)));
}
}
else if ((a & (bit7 | bit6 | bit5 | bit4)) == (bit7 | bit6 | bit5)) // 0x000800-0x00ffff
{
b = *p++;
src++;
--srclen;
c = *p++;
src++;
--srclen;
ch = (unsigned short) ((((a & (bit3 | bit2 | bit1 | bit0)) << 4)
| ((b & (bit5 | bit4 | bit3 | bit2)) >> 2)) * 0x100);
ch += (unsigned short) (((b & (bit1 | bit0)) << 6) | (c & (bit5
| bit4 | bit3 | bit2 | bit1 | bit0)));
}
else
{
ch = a;
}
}
break;
case ENCODING_UTF16BE: /* RFC 2781 */
{
unsigned char *p = (unsigned char *) src;
unsigned short W1, W2;
if (srclen >= 2)
{
W1 = ((unsigned short) p[0] << 8) | (unsigned short) p[1];
src += 2;
srclen -= 2;
if (W1 < 0xD800 || W1 > 0xDFFF)
{
ch = (unsigned int) W1;
}
else
{
if (W1 <= 0xDBFF)
{
if (srclen >= 2)
{
p = (unsigned char *) src;
W2 = ((unsigned short) p[0] << 8)
| (unsigned short) p[1];
src += 2;
srclen -= 2;
if (!(W2 < 0xDC00 || W2 > 0xDFFF))
{
ch = (((unsigned int) (W1 & 0x3FF) << 10)
| (unsigned int) (W2 & 0x3FF)) + 0x10000;
}
else
{
ch = UNKNOWN_UNICODE;
}
}
}
}
}
}
break;
case ENCODING_UTF16LE: /* RFC 2781 */
{
unsigned char *p = (unsigned char *) src;
unsigned short W1 = 0, W2 = 0;
if (srclen >= 2)
{
W1 = ((unsigned short) p[1] << 8) | (unsigned short) p[0];
src += 2;
srclen -= 2;
if (W1 < 0xD800 || W1 > 0xDFFF)
{
ch = (unsigned int) W1;
}
else
{
if (W1 <= 0xDBFF)
{
if (srclen >= 2)
{
p = (unsigned char *) src;
W2 = ((unsigned short) p[1] << 8)
| (unsigned short) p[0];
src += 2;
srclen -= 2;
if ((!W2 < 0xDC00 || W2 > 0xDFFF))
{
ch = (((unsigned int) (W1 & 0x3FF) << 10)
| (unsigned int) (W2 & 0x3FF)) + 0x10000;
}
}
else
{
src += srclen;
srclen -= srclen;
}
}
}
}
else
{
src += srclen;
srclen -= srclen;
}
}
break;
case ENCODING_UTF32BE:
{
unsigned char *p = (unsigned char *) src;
if (srclen >= 4)
{
ch = ((unsigned int) p[0] << 24) | ((unsigned int) p[1] << 16)
| ((unsigned int) p[2] << 8) | (unsigned int) p[3];
src += 4;
srclen -= 4;
}
else
{
src += srclen;
srclen -= srclen;
}
}
break;
case ENCODING_UTF32LE:
{
unsigned char *p = (unsigned char *) src;
if (srclen >= 4)
{
ch = ((unsigned int) p[3] << 24) | ((unsigned int) p[2] << 16)
| ((unsigned int) p[1] << 8) | (unsigned int) p[0];
src += 4;
srclen -= 4;
}
else
{
src += srclen;
srclen -= srclen;
}
}
break;
case ENCODING_UCS2:
{
unsigned short *p = (unsigned short *) src;
if (srclen >= 2)
{
ch = *p;
src += 2;
srclen -= 2;
}
else
{
src += srclen;
srclen -= srclen;
}
}
break;
case ENCODING_UCS4:
{
unsigned int *p = (unsigned int *) src;
if (srclen >= 4)
{
ch = *p;
src += 4;
srclen -= 4;
}
else
{
src += srclen;
srclen -= srclen;
}
}
break;
}
/* Encode a character */
switch (to)
{
case ENCODING_ASCII:
{
unsigned char *p = (unsigned char *) dst;
if (dstlen >= 1)
{
if (ch <= 0x7F)
{
*p = (unsigned char) ch;
}
else
{
}
}
++dst;
--dstlen;
}
break;
case ENCODING_LATIN1:
{
unsigned char *p = (unsigned char *) dst;
if (dstlen >= 1)
{
*p = (unsigned char) ch;
}
++dst;
--dstlen;
}
break;
case ENCODING_UTF8: /* RFC 3629 */
{
unsigned char *p = (unsigned char *) dst;
if (ch > 0x10FFFF)
{
ch = UNKNOWN_UNICODE;
}
if (ch <= 0x7F)
{
if (dstlen >= 1)
{
*p = (unsigned char) ch;
++dst;
--dstlen;
}
}
else if (ch <= 0x7FF)
{
if (dstlen >= 2)
{
p[0] = 0xC0 | (unsigned char) ((ch >> 6) & 0x1F);
p[1] = 0x80 | (unsigned char) (ch & 0x3F);
dst += 2;
dstlen -= 2;
}
}
else if (ch <= 0xFFFF)
{
if (dstlen >= 3)
{
p[0] = 0xE0 | (unsigned char) ((ch >> 12) & 0x0F);
p[1] = 0x80 | (unsigned char) ((ch >> 6) & 0x3F);
p[2] = 0x80 | (unsigned char) (ch & 0x3F);
dst += 3;
dstlen -= 3;
}
}
else if (ch <= 0x1FFFFF)
{
if (dstlen >= 4)
{
p[0] = 0xF0 | (unsigned char) ((ch >> 18) & 0x07);
p[1] = 0x80 | (unsigned char) ((ch >> 12) & 0x3F);
p[2] = 0x80 | (unsigned char) ((ch >> 6) & 0x3F);
p[3] = 0x80 | (unsigned char) (ch & 0x3F);
dst += 4;
dstlen -= 4;
}
}
else if (ch <= 0x3FFFFFF)
{
if (dstlen >= 5)
{
p[0] = 0xF8 | (unsigned char) ((ch >> 24) & 0x03);
p[1] = 0x80 | (unsigned char) ((ch >> 18) & 0x3F);
p[2] = 0x80 | (unsigned char) ((ch >> 12) & 0x3F);
p[3] = 0x80 | (unsigned char) ((ch >> 6) & 0x3F);
p[4] = 0x80 | (unsigned char) (ch & 0x3F);
dst += 5;
dstlen -= 5;
}
}
else
{
if (dstlen >= 6)
{
p[0] = 0xFC | (unsigned char) ((ch >> 30) & 0x01);
p[1] = 0x80 | (unsigned char) ((ch >> 24) & 0x3F);
p[2] = 0x80 | (unsigned char) ((ch >> 18) & 0x3F);
p[3] = 0x80 | (unsigned char) ((ch >> 12) & 0x3F);
p[4] = 0x80 | (unsigned char) ((ch >> 6) & 0x3F);
p[5] = 0x80 | (unsigned char) (ch & 0x3F);
dst += 6;
dstlen -= 6;
}
}
}
break;
case ENCODING_UTF16BE: /* RFC 2781 */
{
unsigned char *p = (unsigned char *) dst;
if (ch > 0x10FFFF)
{
ch = UNKNOWN_UNICODE;
}
if (ch < 0x10000)
{
if (dstlen >= 2)
{
p[0] = (unsigned char) (ch >> 8);
p[1] = (unsigned char) ch;
dst += 2;
dstlen -= 2;
}
}
else
{
unsigned short W1, W2;
if (dstlen >= 4)
{
ch = ch - 0x10000;
W1 = 0xD800 | (unsigned short) ((ch >> 10) & 0x3FF);
W2 = 0xDC00 | (unsigned short) (ch & 0x3FF);
p[0] = (unsigned char) (W1 >> 8);
p[1] = (unsigned char) W1;
p[2] = (unsigned char) (W2 >> 8);
p[3] = (unsigned char) W2;
dst += 4;
dstlen -= 4;
}
}
}
break;
case ENCODING_UTF16LE: /* RFC 2781 */
{
unsigned char *p = (unsigned char *) dst;
if (ch > 0x10FFFF)
{
ch = UNKNOWN_UNICODE;
}
if (ch < 0x10000)
{
if (dstlen >= 2)
{
p[1] = (unsigned char) (ch >> 8);
p[0] = (unsigned char) ch;
dst += 2;
dstlen -= 2;
}
}
else
{
unsigned short W1, W2;
if (dstlen >= 4)
{
ch = ch - 0x10000;
W1 = 0xD800 | (unsigned short) ((ch >> 10) & 0x3FF);
W2 = 0xDC00 | (unsigned short) (ch & 0x3FF);
p[1] = (unsigned char) (W1 >> 8);
p[0] = (unsigned char) W1;
p[3] = (unsigned char) (W2 >> 8);
p[2] = (unsigned char) W2;
dst += 4;
dstlen -= 4;
}
}
}
break;
case ENCODING_UTF32BE:
{
unsigned char *p = (unsigned char *) dst;
if (ch > 0x10FFFF)
{
ch = UNKNOWN_UNICODE;
}
if (dstlen >= 4)
{
p[0] = (unsigned char) (ch >> 24);
p[1] = (unsigned char) (ch >> 16);
p[2] = (unsigned char) (ch >> 8);
p[3] = (unsigned char) ch;
dst += 4;
dstlen -= 4;
}
}
break;
case ENCODING_UTF32LE:
{
unsigned char *p = (unsigned char *) dst;
if (ch > 0x10FFFF)
{
ch = UNKNOWN_UNICODE;
}
if (dstlen >= 4)
{
p[3] = (unsigned char) (ch >> 24);
p[2] = (unsigned char) (ch >> 16);
p[1] = (unsigned char) (ch >> 8);
p[0] = (unsigned char) ch;
dst += 4;
dstlen -= 4;
}
}
break;
case ENCODING_UCS2:
{
unsigned short *p = (unsigned short *) dst;
if (ch > 0xFFFF)
{
ch = UNKNOWN_UNICODE;
}
if (dstlen >= 2)
{
*p = (unsigned short) ch;
dst += 2;
dstlen -= 2;
}
}
break;
case ENCODING_UCS4:
{
unsigned int *p = (unsigned int *) dst;
if (ch > 0x7FFFFFFF)
{
ch = UNKNOWN_UNICODE;
}
if (dstlen >= 4)
{
*p = ch;
dst += 4;
dstlen -= 4;
}
}
break;
}
/* Update state */
++total;
}
return total;
}
void
Java_org_parser_txt_TxtParser_Parser(JNIEnv *env, jobject thiz,
jobject thisParser, jstring strPath)
{
LOGD("Enter TxtParser_Parser\n");
jmethodID startElementID = NULL;
jmethodID endElementID = NULL;
jmethodID characterDataID = NULL;
jclass clsParser = env->GetObjectClass(thisParser);
if (clsParser)
{
startElementID
= env->GetMethodID(clsParser, "startElementHandler", "()V");
if (!startElementID)
{
LOGD("GetMethodID startElementHandler failed\n");
}
endElementID = env->GetMethodID(clsParser, "endElementHandler", "()V");
if (!endElementID)
{
LOGD("GetMethodID endElementID failed\n");
}
characterDataID = env->GetMethodID(clsParser, "characterDataHandler",
"(Ljava/lang/String;)V");
if (!characterDataID)
{
LOGD("GetMethodID characterDataID failed\n");
}
}
else
{
LOGD("GetObjectClass failed\n");
}
if (!startElementID || !endElementID || !characterDataID)
{
return;
}
if (startElementID)
{
env->CallVoidMethod(thisParser, startElementID);
}
long nFrom = ENCODING_ASCII;
char szFilePath[MAX_PATH * 2] =
{ 0 };
long nPathLen = env->GetStringUTFLength(strPath);
LOGD("Enter 1国家\n");
env->GetStringUTFRegion(strPath, 0, nPathLen, szFilePath);
LOGD("Enter 2\n"); LOGD(szFilePath);
FILE* pFile = NULL;
long nFileOffset = 0;
unsigned short ashtUnicodeBuffer[2048] =
{ 0 };
pFile = fopen(szFilePath, "r");
if (pFile)
{
const long BUFSIZE = 2048;
unsigned char *buffer = new unsigned char[BUFSIZE];
//std::string str;
long nLength = 0;
if (startElementID)
{
env->CallVoidMethod(thisParser, startElementID);
}
do
{
nLength = fread(buffer, sizeof(char), BUFSIZE, pFile);
unsigned char *start = buffer;
if (!nFileOffset)
{
if (nLength >= 2 && (buffer[0] == 0xFF && buffer[1] == 0xFE))
{
nFrom = ENCODING_UTF16LE;
nFileOffset += 2;
}
else if (nLength >= 2 && (buffer[0] == 0xFE && buffer[1] == 0xFF))
{
nFrom = ENCODING_UTF16BE;
nFileOffset += 2;
}
else if (nLength >= 3 && (buffer[0] == 0xEF && buffer[1] == 0xBB
&& buffer[2] == 0xBF))
{
nFrom = ENCODING_UTF8;
nFileOffset += 3;
}
else if (nLength >= 4 && (buffer[0] == 0xFF && buffer[1] == 0xFE
&& buffer[2] == 0x00 && buffer[3] == 0x00))
{
nFrom = ENCODING_UTF32LE;
nFileOffset += 4;
}
else if (nLength >= 4 && (buffer[0] == 0x00 && buffer[1] == 0x00
&& buffer[2] == 0xFE && buffer[3] == 0xFF))
{
nFrom = ENCODING_UTF32BE;
nFileOffset += 4;
}
start += nFileOffset;
}
//LOGD(start);
const unsigned char *end = buffer + nLength;
for (unsigned char *ptr = start; ptr != end; ++ptr)
{
if (*ptr == '\n' || *ptr == '\r')
{
bool skipNewLine = false;
if (*ptr == '\r' && (ptr + 1) != end && *(ptr + 1) == '\n')
{
skipNewLine = true;
*ptr = '\n';
}
if (start != ptr)
{
//str.erase();
//myConverter->convert(str, start, ptr + 1);
//characterDataHandler(str);
ashtUnicodeBuffer[0] = 0;
ZeroMemory(ashtUnicodeBuffer, sizeof(ashtUnicodeBuffer));
long nLen = Hanvoniconv(nFrom, ENCODING_UTF16LE, start, ptr + 1 - start, (unsigned char*)ashtUnicodeBuffer, sizeof(ashtUnicodeBuffer) - 10);
if (nLen > 0)
{
char szCode[500] =
{ 0 };
strcpy(szCode, "guojiadeshiqijie 汉王科技");
jstring strCode = env->NewString(ashtUnicodeBuffer,
nLen / 2);
if (characterDataID)
{
env->CallVoidMethod(thisParser, characterDataID,
strCode);
}
}
//LOGD(szUnicode);
}
if (skipNewLine)
{
++ptr;
}
start = ptr + 1;
if (endElementID)
{
env->CallVoidMethod(thisParser, endElementID);
}
if (startElementID)
{
env->CallVoidMethod(thisParser, startElementID);
}
//newLineHandler();
}
else if (0/*isspace((unsigned char) *ptr)*/)
{
if (*ptr != '\t')
{
*ptr = ' ';
}
}
else
{
}
}
if (start != end)
{
//str.erase();
//myConverter->convert(str, start, end);
//characterDataHandler(str);
}
}
while (nLength == BUFSIZE);
delete[] buffer;
buffer = NULL;
//endDocumentHandler();
fclose(pFile);
pFile = NULL;
//stream.close();
}
else
{
LOGD("TxtParser_Parser:file open failed\n");
}
LOGD("Leave TxtParser_Parser\n");
}
<file_sep>/FingerSuite/FingerNotification/NotifWindow.h
// WTLApp1View.h : interface of the CWTLApp1View class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "InterceptEngine.h"
#include <initguid.h>
//#include <piedocvw.h>
#include <webvw.h>
#define IDT_TIMER_MENU_ANIMATION 10110
#define TMR_MENU_ANIMATION 10
#define BORDER_WIDTH 10
#define UM_STARTANIM WM_USER + 1
#define UM_MINIMIZE WM_USER + 2
#define IDC_HTMLVIEW 10
//#define CUSTOM_CSS _T("INPUT[type='button'] { BORDER-RIGHT: #7b8194 1px solid; PADDING-RIGHT: 4px; BACKGROUND-POSITION: left bottom; BORDER-TOP: #a5a9b6 1px solid; PADDING-LEFT: 4px; FONT-WEIGHT: bold; FONT-SIZE: 9pt! important; BACKGROUND-IMAGE: url(btn_background.gif); PADDING-BOTTOM: 4px; MARGIN: 2px; VERTICAL-ALIGN: middle; BORDER-LEFT: #a5a9b6 1px solid; COLOR: #586073! important; LINE-HEIGHT: 20px; PADDING-TOP: 4px; BORDER-BOTTOM: #7b8194 1px solid; BACKGROUND-REPEAT: repeat-x; FONT-FAMILY: Tahoma; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #ffffff; TEXT-ALIGN: center; TEXT-DECORATION: none }")
#define CUSTOM_CSS _T("INPUT[type='button'] { BORDER: none; PADDING-RIGHT: 4px; BACKGROUND-POSITION: left bottom; PADDING-LEFT: 4px; FONT-WEIGHT: bold; FONT-SIZE: 9pt! important; BACKGROUND-IMAGE: url(fngrnotif_btn_bkg.gif); PADDING-BOTTOM: 4px; MARGIN: 2px; VERTICAL-ALIGN: middle; COLOR: #000000! important; LINE-HEIGHT: 20px; PADDING-TOP: 4px; BACKGROUND-REPEAT: repeat-x; FONT-FAMILY: Tahoma; WHITE-SPACE: nowrap; BACKGROUND-COLOR: #ffffff; TEXT-ALIGN: center; TEXT-DECORATION: none }")
template <class T>
class CNotifWindow : public CWindowImpl<T, CWindow, CControlWinTraits>
{
public:
DECLARE_WND_CLASS(NULL)
CNotifWindow ()
{
}
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
void SetScaleFactor(int value)
{
m_scaleFactor = value;
}
int GetScaleFactor()
{
return m_scaleFactor;
}
void Show()
{
ModifyShape();
StartAnimation();
}
BOOL SetNotification(LPNOTIFICATIONINFO pData)
{
m_pInfo = pData;
return TRUE;
}
void DoPaint(CBufferedPaintDC /*dc*/)
{
// must be implemented in a derived class
ATLASSERT(FALSE);
}
BEGIN_MSG_MAP(CNotifWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(UM_STARTANIM, OnStartAnim)
//MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
//MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
//MESSAGE_HANDLER(WM_KEYDOWN, OnKeyDown)
FORWARD_NOTIFICATIONS()
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
ModifyTopShape();
if (m_fCaption != NULL)
{
LOGFONT lf; m_fCaption.GetLogFont(&lf);
lf.lfHeight += 7 * m_scaleFactor;
m_fCalendar.CreateFontIndirect(&lf);
}
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
return 0;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
RECT rc; GetClientRect(&rc);
CBufferedPaintDC dc(m_hWnd, 0);
RECT rcHead; CopyRect(&rcHead, &rc);
rcHead.bottom = m_imgHeader.GetHeight();
m_imgHeader.Draw(dc, rcHead);
// draw title
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(m_clCaptionText);
CFont oldFont = dc.SelectFont(m_fCaption);
UINT uFormat = DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS;
if (m_pInfo->grfFlagsOriginal & SHNF_TITLETIME)
{
WCHAR szTitle[256];
WCHAR szTime[50];
::GetTimeFormat(LOCALE_USER_DEFAULT, TIME_NOSECONDS, NULL, NULL, szTime, 12);
wsprintf(szTitle, L"%s | %s", szTime, m_pInfo->nd.pszTitle);
rcHead.left += m_imgCalendar.GetWidth();
dc.DrawText(szTitle, -1, &rcHead, uFormat);
// draw icon calendar
WCHAR szMonth[50];
WCHAR szDay[50];
::GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, L"MMM", szMonth, 50);
::GetDateFormat(LOCALE_USER_DEFAULT, 0, NULL, L"d", szDay, 50);
m_imgCalendar.Draw(dc);
RECT rcCal;
SetRect(&rcCal, 0, 0, m_imgCalendar.GetWidth(), 10 * m_scaleFactor);
CFont oldCalFont = dc.SelectFont(m_fCalendar);
dc.DrawText(szMonth, -1, &rcCal, DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS);
dc.SelectFont(oldCalFont);
SetRect(&rcCal, 0, 0, m_imgCalendar.GetWidth(), m_imgCalendar.GetHeight() - 5 * m_scaleFactor);
dc.SetTextColor(RGB(0,0,0));
dc.DrawText(szDay, -1, &rcCal, DT_CENTER | DT_BOTTOM | DT_SINGLELINE | DT_END_ELLIPSIS);
}
else
dc.DrawText(m_pInfo->nd.pszTitle, -1, &rcHead, uFormat);
dc.SelectFont(oldFont);
bHandled = FALSE;
return 0;
}
LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if (wParam == IDT_TIMER_MENU_ANIMATION)
{
m_iStep = m_iStep / 2;
RECT animRect; CopyRect(&animRect, &m_animRect);
animRect.top = animRect.top + m_iStep;
MoveWindow(&animRect, TRUE);
if (m_iStep == 0)
{
KillTimer(IDT_TIMER_MENU_ANIMATION);
m_bAnimating = FALSE;
m_iStep = 0;
}
bHandled = TRUE;
return 0;
}
bHandled = FALSE;
return 0;
}
LRESULT OnStartAnim(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
ModifyShape();
StartAnimation();
return 0;
}
void ModifyTopShape()
{
int nUsedRects = 3 * m_scaleFactor;
m_heightHrgnTop = nUsedRects;
if (m_hrgnTop != NULL)
{
DeleteObject(m_hrgnTop);
m_hrgnTop = NULL;
}
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor;
RGNDATA *pRgnData;
RECT *pRect;
DWORD dwTemp = sizeof(RGNDATAHEADER) + nUsedRects * sizeof(RECT);
pRgnData = (RGNDATA*)malloc(dwTemp);
pRgnData->rdh.dwSize = sizeof(RGNDATAHEADER);
pRgnData->rdh.iType = RDH_RECTANGLES;
pRgnData->rdh.nCount = nUsedRects;
pRgnData->rdh.nRgnSize = 0;
pRgnData->rdh.rcBound.left = pRgnData->rdh.rcBound.top = 0;
pRgnData->rdh.rcBound.right = iWidth;
pRgnData->rdh.rcBound.bottom = nUsedRects;
if (nUsedRects == 3)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 2;
pRect->right = iWidth - 2;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 1;
pRect->right = iWidth - 1;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 0;
pRect->right = iWidth;
}
else if (nUsedRects == 6)
{
// 1st
pRect = &(((RECT *)&pRgnData->Buffer)[0]);
pRect->top = 0;
pRect->bottom = 1;
pRect->left = 5;
pRect->right = iWidth - 5;
// 2nd
pRect = &(((RECT *)&pRgnData->Buffer)[1]);
pRect->top = 1;
pRect->bottom = 2;
pRect->left = 3;
pRect->right = iWidth - 3;
// 3rd
pRect = &(((RECT *)&pRgnData->Buffer)[2]);
pRect->top = 2;
pRect->bottom = 3;
pRect->left = 2;
pRect->right = iWidth - 2;
// 4th
pRect = &(((RECT *)&pRgnData->Buffer)[3]);
pRect->top = 3;
pRect->bottom = 4;
pRect->left = 1;
pRect->right = iWidth - 1;
// 5th
pRect = &(((RECT *)&pRgnData->Buffer)[4]);
pRect->top = 4;
pRect->bottom = 5;
pRect->left = 1;
pRect->right = iWidth - 1;
// 6th
pRect = &(((RECT *)&pRgnData->Buffer)[5]);
pRect->top = 5;
pRect->bottom = 6;
pRect->left = 0;
pRect->right = iWidth;
}
m_hrgnTop = ExtCreateRegion(NULL, dwTemp, pRgnData);
free(pRgnData);
}
void AddStyle()
{
}
void SubmitForm()
{
// must be implemented in a derived class
ATLASSERT(FALSE);
}
public:
RECT m_animRect;
BOOL m_bAnimating;
int m_iStep;
int m_scaleFactor;
int m_height;
BOOL m_bMouseIsDown;
HRGN m_hrgnTop;
int m_heightHrgnTop;
int m_iBodyHeight;
NOTIFICATIONINFO* m_pInfo;
COLORREF m_clCaptionText;
CFontHandle m_fCaption;
CFontHandle m_fCalendar;
CxImage m_imgCalendar;
CxImage m_imgHeader;
BOOL m_bEnableAnimation;
void ModifyShape()
{
m_height = m_iBodyHeight + m_imgHeader.GetHeight();
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor;
HRGN hrgnBottom = ::CreateRectRgn(0, 0, iWidth, m_height - m_heightHrgnTop);
::OffsetRgn(hrgnBottom, 0, m_heightHrgnTop);
CombineRgn(hrgnBottom, m_hrgnTop, hrgnBottom, RGN_OR);
SetWindowRgn(hrgnBottom, FALSE);
}
void StartAnimation()
{
int m_itemHeight = 5 * m_scaleFactor;
// window position
m_bAnimating = (m_bEnableAnimation) ? TRUE : FALSE;
m_iStep = (m_bEnableAnimation) ? m_itemHeight / 3 : 0;
RECT rcParent; GetParent().GetClientRect(&rcParent);
m_animRect.left = BORDER_WIDTH * m_scaleFactor;
m_animRect.right = rcParent.right - BORDER_WIDTH * m_scaleFactor;
m_animRect.top = rcParent.bottom - m_height;
m_animRect.bottom = rcParent.bottom;
RECT animRect; CopyRect(&animRect, &m_animRect);
animRect.top = animRect.top + m_iStep;
MoveWindow(&animRect, TRUE);
if (m_bEnableAnimation)
SetTimer(IDT_TIMER_MENU_ANIMATION, TMR_MENU_ANIMATION);
}
};
class CHTMLNotifWindow : public CNotifWindow<CHTMLNotifWindow>
{
public:
DECLARE_WND_CLASS(NULL)
typedef CNotifWindow<CHTMLNotifWindow> Super;
CHtmlCtrl m_html;
BOOL SetNotification(LPNOTIFICATIONINFO pData)
{
Super::SetNotification(pData);
m_html.Clear();
m_html.AddStyle(CUSTOM_CSS);
RECT rcParent; GetParent().GetClientRect(&rcParent);
int iWidth = rcParent.right - 2 * BORDER_WIDTH * m_scaleFactor;
m_html.ResizeClient(iWidth, 0);
m_html.SendMessage(WM_SETTEXT, 0, (LPARAM)(LPCTSTR)_T(""));
m_html.AddHTML(m_pInfo->nd.pszHTML);
m_html.EndOfSource();
m_iBodyHeight = m_html.GetLayoutHeight() + 25 * m_scaleFactor;
return TRUE;
}
void SubmitForm()
{
IDispatch* pDisp = NULL;
m_html.GetDocumentDispatch(&pDisp);
IPIEHTMLDocument *pHTMLDocument = NULL;
HRESULT hr = pDisp->QueryInterface(IID_IPIEHTMLDocument, (void**)&pHTMLDocument);
if (FAILED(hr)) {
if (hr == E_NOINTERFACE)
LOG(L"Interface doesn't exist\n");
if (hr == E_NOTIMPL)
LOG(L"Queryinterface not implemented\n");
return;
}
IPIEHTMLElementCollection *pElementCollection = NULL;
if ( pHTMLDocument->get_forms ( &pElementCollection ) == S_OK )
{
if (pElementCollection != NULL)
{
long celem = 0;
if ( pElementCollection->get_length( &celem ) == S_OK )
{
for ( long i = 0; i < celem; i++ )
{
VARIANT vtIndex;
vtIndex.vt = VT_I4;
vtIndex.lVal = i;
IDispatch* pItem = NULL;
if( pElementCollection->item( vtIndex, vtIndex, (IDispatch**)&pItem ) == S_OK )
{
IPIEHTMLFormElement* form = NULL;
if( pItem->QueryInterface(__uuidof(IPIEHTMLFormElement), (void**)&form ) == S_OK )
{
form->put_method((BSTR)L"get");
hr = form->submit();
LOG(L"Tutto OK\n");
}
}
}
}
}
}
}
BEGIN_MSG_MAP(CHTMLNotifWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(UM_STARTANIM, OnStartAnim)
CHAIN_MSG_MAP(Super)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
// html control
InitHTMLControl(ModuleHelper::GetModuleInstance());
m_html.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS, IDC_HTMLVIEW);
m_html.SetFocus();
m_html.SendMessage(WM_SETTEXT, 0, (LPARAM)(LPCTSTR)_T(""));
bHandled = FALSE;
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
RECT rc; GetClientRect(&rc);
rc.top += m_imgHeader.GetHeight();
m_html.SetWindowPos(0, &rc, SWP_NOZORDER);
bHandled = FALSE;
return 0;
}
};<file_sep>/FingerSuite/Common/atlceactivesync.h
#if !defined(AFX_ATLCEACTIVESYNC_H__20040110_01FC_0634_DA35_0080AD509054__INCLUDED_)
#define AFX_ATLCEACTIVESYNC_H__20040110_01FC_0634_DA35_0080AD509054__INCLUDED_
/////////////////////////////////////////////////////////////////////////////
// atlceactivesync - Active Sync for Win CE implementation
//
// Written by <NAME> (<EMAIL>)
// Copyright (c) 2004 <NAME>.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name is included.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability if it causes any damage to you or your
// computer whatsoever. It's free, so don't hassle me about it.
//
// Beware of bugs.
//
#pragma once
#include <cesync.h>
/////////////////////////////////////////////////////////////////////////////
// Macros
#ifndef _ASSERTE
#define _ASSERTE(x)
#endif
#define PROP_TAG(ulPropType, ulPropID) ((((ULONG)(ulPropID))<<16)|((ULONG)(ulPropType)))
#define PROP_TYPE(ulPropTag) (((ULONG)(ulPropTag))&0x0000FFFF)
#define GET_STREAM_WORD(x) x = * (LPWORD) pData; pData += sizeof(WORD); cbData -= sizeof(WORD)
#define GET_STREAM_DWORD(x) x = * (LPDWORD) pData; pData += sizeof(DWORD); cbData -= sizeof(DWORD)
#define GET_STREAM_BYTES(x, n) memcpy(x, pData, n); pData += (n); cbData -= (n)
#define PUT_STREAM_WORD(x) * (LPWORD) pData = x; pData += sizeof(WORD); cbData += sizeof(WORD)
#define PUT_STREAM_DWORD(x) * (LPDWORD) pData = x; pData += sizeof(DWORD); cbData += sizeof(DWORD)
#define PUT_STREAM_BYTES(x, n) memcpy(pData, x, n); pData += (n); cbData += (n)
/////////////////////////////////////////////////////////////////////////////
// Debug Helpers
#ifdef DEBUG
inline void _cdecl Log(LPCWSTR lpszFormat, ...)
{
// Format text
va_list args;
va_start(args, lpszFormat);
WCHAR szBuffer[256] = { 0 };
int nBuf = _vsnwprintf(szBuffer, (sizeof(szBuffer) / sizeof(WCHAR)) - 1, lpszFormat, args);
va_end(args);
// A truely crappy semaphore
static volatile bool s_bLocked = false;
DWORD dwTick = ::GetTickCount();
while( s_bLocked && ::GetTickCount() - dwTick < 1000UL ) ::Sleep(0L);
s_bLocked = true;
// Append to file
HANDLE hFile = ::CreateFile(L"\\sync.log", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);
if( hFile != INVALID_HANDLE_VALUE ) {
::SetFilePointer(hFile, 0, NULL, FILE_END);
DWORD dwWritten = 0;
::WriteFile(hFile, szBuffer, nBuf * sizeof(WCHAR), &dwWritten, NULL);
::FlushFileBuffers(hFile);
::CloseHandle(hFile);
}
s_bLocked = false;
}
#else
inline void _cdecl LogStub(LPCWSTR lpszFormat, ...) { };
#define Log 1 ? (void)0 : LogStub
#endif
/////////////////////////////////////////////////////////////////////////////
// Base Folder
class CReplFolder
{
public:
CReplFolder(){};
virtual ~CReplFolder() { };
public:
virtual LPCWSTR GetName() const = 0;
virtual BOOL Initialize(IReplObjHandler** ppObjHandler, UINT uPartnerBit) = 0;
virtual BOOL UnInitialize() = 0;
virtual HRESULT FindObjects(PFINDOBJINFO pFind) = 0;
virtual BOOL ObjectNotify(POBJNOTIFY pObjNotify) = 0;
virtual BOOL GetObjTypeInfo(POBJTYPEINFO pInfo) = 0;
virtual BOOL SyncData(PSDREQUEST psd) = 0;
};
/////////////////////////////////////////////////////////////////////////////
// Store Implementation
class CReplStore
{
public:
enum { MAX_FOLDERS = 10 };
CReplFolder* m_aFolders[MAX_FOLDERS];
int m_nFolders;
CReplStore() : m_nFolders(0)
{
}
virtual ~CReplStore()
{
for( int i = 0; i < m_nFolders; i++ ) delete m_aFolders[i];
}
virtual BOOL InitObjType(LPWSTR lpszObjType, IReplObjHandler **ppObjHandler, UINT uPartnerBit)
{
Log(L"CReplStore::InitObjType (%s)\r\n", lpszObjType == NULL ? L"<null>" : lpszObjType);
if( lpszObjType == NULL )
{
// Uninitialize
BOOL fRet = TRUE;
for( int i = 0; i < m_nFolders; i++ ) {
if( !m_aFolders[i]->UnInitialize() ) fRet = FALSE;
}
return fRet;
}
else
{
// Initialize
*ppObjHandler = NULL;
CReplFolder* pFolder = GetFolderByName(lpszObjType);
if( pFolder ) return pFolder->Initialize(ppObjHandler, uPartnerBit);
return FALSE;
}
}
virtual HRESULT FindObjects(PFINDOBJINFO pFind)
{
Log(L"CReplStore::FindObjects\r\n");
if( pFind == NULL ) return E_INVALIDARG;
CReplFolder* pFolder = GetFolderByName(pFind->szObjType);
if( pFolder ) return pFolder->FindObjects(pFind);
return E_INVALIDARG;
}
virtual BOOL ObjectNotify(POBJNOTIFY pNotify)
{
Log(L"CReplStore::ObjectNotify\r\n");
if( pNotify == NULL ) return FALSE;
CReplFolder* pFolder = GetFolderByName(pNotify->szObjType);
if( pFolder ) return pFolder->ObjectNotify(pNotify);
return FALSE;
}
virtual BOOL GetObjTypeInfo(POBJTYPEINFO pInfo)
{
Log(L"CReplStore::GetObjTypeInfo\r\n");
if( pInfo == NULL ) return FALSE;
CReplFolder* pFolder = GetFolderByName(pInfo->szObjType);
if( pFolder ) return pFolder->GetObjTypeInfo(pInfo);
return FALSE;
}
virtual BOOL ReportStatus(LPWSTR lpszObjType, UINT uCode, UINT uParam)
{
Log(L"CReplStore::ReportStatus %04X\r\n", uCode);
return TRUE;
}
virtual BOOL SyncData(PSDREQUEST psd)
{
Log(L"CReplStore::SyncData\r\n");
CReplFolder* pFolder = GetFolderByName(psd->szObjType);
if( pFolder ) return pFolder->SyncData(psd);
return FALSE;
}
CReplFolder* GetFolderByName(LPWSTR wszName) const
{
for( int i = 0; i < m_nFolders; i++ ) {
if( wcscmp(m_aFolders[i]->GetName(), wszName) == 0 ) return m_aFolders[i];
}
return NULL;
}
};
/////////////////////////////////////////////////////////////////////////////
// IReplObjHandler
template< class T >
class IReplObjHandlerImpl : public IReplObjHandler
{
public:
enum { MAX_DATASIZE = 6000 };
IReplObjHandlerImpl() : m_cRef(1)
{
}
// IUnknown
STDMETHODIMP_(ULONG) AddRef()
{
return ::InterlockedIncrement(&m_cRef);
}
STDMETHODIMP_(ULONG) Release()
{
ULONG urc;
if( (urc = ::InterlockedDecrement(&m_cRef)) == 0 ) delete this;
return urc;
}
STDMETHODIMP QueryInterface(REFIID iid, LPVOID* ppvObj)
{
*ppvObj = NULL;
return E_NOINTERFACE;
}
// IReplObjHandler
STDMETHODIMP Setup(PREPLSETUP pSetup)
{
Log(L"IReplObjHandlerImpl::Setup\r\n");
if( pSetup->fRead ) {
m_pReadSetup = pSetup;
m_dwReadPos = 0;
m_pData = (LPBYTE) ::LocalAlloc(LMEM_FIXED, MAX_DATASIZE);
if( m_pData == NULL ) return E_OUTOFMEMORY;
}
else {
m_pWriteSetup = pSetup;
m_dwWritePos = 0;
}
return NOERROR;
}
STDMETHODIMP Reset(PREPLSETUP pSetup)
{
Log(L"IReplObjHandlerImpl::Reset\r\n");
if( pSetup->fRead ) ::LocalFree(m_pData);
return NOERROR;
}
LONG m_cRef;
PREPLSETUP m_pReadSetup;
PREPLSETUP m_pWriteSetup;
DWORD m_dwReadPos;
DWORD m_dwWritePos;
LPBYTE m_pData;
};
/////////////////////////////////////////////////////////////////////////////
// CCeDatabase
class CCeDatabase
{
public:
CEGUID m_Guid;
CEOID m_Oid;
HANDLE m_Db;
bool m_bManaged;
CCeDatabase() : m_Db(INVALID_HANDLE_VALUE), m_bManaged(false)
{
CREATE_INVALIDGUID(&m_Guid);
}
CCeDatabase(CEGUID Guid) : m_Db(INVALID_HANDLE_VALUE), m_Guid(Guid), m_bManaged(false)
{
}
~CCeDatabase()
{
Close();
if( m_bManaged ) Unmount();
}
BOOL Create(LPWSTR pstrVolume, UINT uFlags = CREATE_ALWAYS)
{
_ASSERTE(pstrVolume);
_ASSERTE(CHECK_INVALIDGUID(&m_Guid));
return ::CeMountDBVol(&m_Guid, pstrVolume, uFlags);
}
BOOL MountObjectStore()
{
_ASSERTE(CHECK_INVALIDGUID(&m_Guid));
CREATE_SYSTEMGUID(&m_Guid);
m_bManaged = true;
return TRUE;
}
BOOL Mount(LPWSTR pstrVolume)
{
_ASSERTE(pstrVolume);
_ASSERTE(CHECK_INVALIDGUID(&m_Guid));
BOOL bRes = ::CeMountDBVol(&m_Guid, pstrVolume, OPEN_EXISTING);
m_bManaged = true;
return bRes;
}
void Unmount()
{
if( CHECK_INVALIDGUID(&m_Guid) ) return;
if( !CHECK_SYSTEMGUID(&m_Guid) ) ::CeUnmountDBVol(&m_Guid);
CREATE_INVALIDGUID(&m_Guid);
m_bManaged = false;
}
CEOID FindDatabase(LPWSTR pstrFile, DWORD dwType)
{
_ASSERTE(!CHECK_INVALIDGUID(&m_Guid));
// Validate we're mounted
if( CHECK_INVALIDGUID(&m_Guid) ) return 0;
// First search for the database
CEOID oid = 0;
HANDLE hFind = ::CeFindFirstDatabaseEx(&m_Guid, dwType);
if( hFind != INVALID_HANDLE_VALUE ) {
while( true ) {
CEOIDINFO oidInfo;
oid = ::CeFindNextDatabase(hFind);
if( oid == 0
|| (::CeOidGetInfoEx(&m_Guid, oid, &oidInfo)
&& oidInfo.wObjType == OBJTYPE_DATABASE
&& wcscmp(oidInfo.infDatabase.szDbaseName, pstrFile) == 0) )
{
break;
}
}
::CloseHandle(hFind);
}
return oid;
}
BOOL Open(LPWSTR pstrFile, DWORD dwType, BOOL bCreateIfNotExists = TRUE)
{
_ASSERTE(!CHECK_INVALIDGUID(&m_Guid));
// Validate we're mounted
if( CHECK_INVALIDGUID(&m_Guid) ) return FALSE;
// First search for the database
CEOID oid = FindDatabase(pstrFile, dwType);
// If not found, create a new database
if( bCreateIfNotExists && oid == 0 ) {
CEDBASEINFO info = { 0 };
info.dwFlags = CEDB_VALIDNAME | CEDB_VALIDTYPE;
::lstrcpy(info.szDbaseName, pstrFile);
info.dwDbaseType = dwType;
oid = ::CeCreateDatabaseEx(&m_Guid, &info);
}
// Finally open the database
if( oid ) {
m_Db = ::CeOpenDatabaseEx(&m_Guid, &oid, NULL, NULL, 0, NULL);
m_Oid = oid;
}
return m_Oid != 0 && m_Db != INVALID_HANDLE_VALUE;
}
BOOL Open(LPWSTR pstrFile, DWORD dwType, CEPROPID Prop, DWORD dwFlags = CEDB_AUTOINCREMENT, CENOTIFYREQUEST* pReq = NULL)
{
_ASSERTE(!CHECK_INVALIDGUID(&m_Guid));
// Validate we're mounted
if( CHECK_INVALIDGUID(&m_Guid) ) return FALSE;
// First search for the database
CEOID oid = FindDatabase(pstrFile, dwType);
// Open the database
if( oid ) {
m_Db = ::CeOpenDatabaseEx(&m_Guid, &oid, NULL, Prop, dwFlags, pReq);
m_Oid = oid;
}
return m_Oid != 0 && m_Db != INVALID_HANDLE_VALUE;
}
void Close()
{
if( m_Db != INVALID_HANDLE_VALUE ) {
::CloseHandle(m_Db);
m_Db = INVALID_HANDLE_VALUE;
}
}
BOOL DeleteDatabase()
{
_ASSERTE(!IsOpen());
_ASSERTE(!CHECK_INVALIDGUID(&m_Guid));
// Use Open() before calling this!
Close();
return ::CeDeleteDatabaseEx(&m_Guid, m_Oid);
}
BOOL IsOpen() const
{
return m_Db != INVALID_HANDLE_VALUE;
}
BOOL IsMounted() const
{
return CHECK_INVALIDGUID(&m_Guid);
}
BOOL IsVolume(CEGUID* pData, UINT cbData) const
{
// Compare data with GUID structure
if( CHECK_SYSTEMGUID(&m_Guid) ) return pData == NULL || (cbData == sizeof(CEGUID) && CHECK_SYSTEMGUID(pData));
return cbData == sizeof(CEGUID) && memcmp(pData, &m_Guid, sizeof(CEGUID)) == 0;
}
BOOL GetInfoEx(CEOIDINFO* oidInfo)
{
_ASSERTE(IsOpen());
return ::CeOidGetInfoEx(&m_Guid, m_Oid, oidInfo);
}
DWORD Seek(DWORD dwType, DWORD dwValue, DWORD* pdwIndex = NULL)
{
_ASSERTE(IsOpen());
DWORD dwTempIndex = 0;
if( pdwIndex == NULL ) pdwIndex = &dwTempIndex;
return ::CeSeekDatabase(m_Db, dwType, dwValue, pdwIndex);
}
DWORD SeekMatch(DWORD dwType, const CEPROPVAL* pValue, DWORD* pdwIndex = NULL)
{
return Seek(dwType, (DWORD) pValue, pdwIndex);
}
DWORD SeekOid(CEOID oid, DWORD* pdwIndex = NULL)
{
return Seek(CEDB_SEEK_CEOID, (DWORD) oid, pdwIndex);
}
DWORD SeekNext(DWORD* pdwIndex = NULL)
{
return Seek(CEDB_SEEK_CURRENT, 1, pdwIndex);
}
DWORD ReadRecord(LPBYTE* lplpBuffer, LPDWORD lpcbBuffer, LPWORD lpcPropID, CEPROPID* rgPropID = NULL, DWORD dwFlags = CEDB_ALLOWREALLOC)
{
_ASSERTE(IsOpen());
_ASSERTE(lplpBuffer);
_ASSERTE(lpcbBuffer);
return ::CeReadRecordProps(m_Db, dwFlags, lpcPropID, rgPropID, lplpBuffer, lpcbBuffer);
}
DWORD ReadRecord(CEPROPVAL** lplpBuffer, LPDWORD lpcbBuffer, LPWORD lpcPropID, CEPROPID* rgPropID = NULL, DWORD dwFlags = CEDB_ALLOWREALLOC)
{
_ASSERTE(IsOpen());
_ASSERTE(lplpBuffer);
_ASSERTE(lpcbBuffer);
return ::CeReadRecordProps(m_Db, dwFlags, lpcPropID, rgPropID, (LPBYTE*) lplpBuffer, lpcbBuffer);
}
DWORD UpdateRecord(CEOID oid, WORD cPropID, CEPROPVAL* rgPropVal)
{
_ASSERTE(IsOpen());
_ASSERTE(rgPropVal);
return ::CeWriteRecordProps(m_Db, oid, cPropID, rgPropVal);
}
DWORD CreateRecord(WORD cPropID, CEPROPVAL* rgPropVal)
{
_ASSERTE(IsOpen());
_ASSERTE(rgPropVal);
return ::CeWriteRecordProps(m_Db, 0, cPropID, rgPropVal);
}
BOOL DeleteRecord(CEOID oid)
{
_ASSERTE(IsOpen());
return ::CeDeleteRecord(m_Db, oid);
}
operator HANDLE() const
{
return m_Db;
}
operator CEGUID() const
{
return m_Guid;
}
operator CEOID() const
{
return m_Oid;
}
};
#endif // !defined(AFX_ATLCEACTIVESYNC_H__20040110_01FC_0634_DA35_0080AD509054__INCLUDED_)
<file_sep>/7-Zip/CPP/7zip/Archive/Udf/UdfRegister.cpp
// UdfRegister.cpp
#include "StdAfx.h"
#include "../../Common/RegisterArc.h"
#include "UdfHandler.h"
static IInArchive *CreateArc() { return new NArchive::NUdf::CHandler; }
static CArcInfo g_ArcInfo =
{ L"Udf", L"iso", 0, 0xE0, { 0, 'N', 'S', 'R', '0' }, 5, false, CreateArc, 0 };
REGISTER_ARC(Udf)
<file_sep>/FingerSuite/Common/fngrbtn.h
#ifndef __FNGRBTN_H__
#define __FNGRBTN_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error fngrscrl.h requires atlapp.h to be included first
#endif
#ifndef __ATLWIN_H__
#error fngrscrl.h requires atlwin.h to be included first
#endif
#ifndef __CXIMAGE_H
#error fngrscrl.h requires ximage.h to be included first
#endif
#define FNGRBTN_CLASS L"FingerBtn"
//#define NS_FINGERBTN (WS_CHILD | WS_CLIPSIBLINGS)
#define FNGRBTN_TYPE_TEXT 0x00
#define FNGRBTN_TYPE_STATIC 0x01
#define FNGRBTN_TYPE_DYNAMIC 0x02
#define FNGRBTN_TYPE_ICON 0x04
typedef enum enumState
{
NOT_DEFINED = -1,
NORMAL = 0,
PUSHED = 3,
FOCUSED = 6
} STATE;
inline void AddDynamicSet(CxImage arrImages[], STATE state, LPCTSTR szFileNameLeft, LPCTSTR szFileNameCenter, LPCTSTR szFileNameRight)
{
arrImages[state].Load(szFileNameLeft, CXIMAGE_FORMAT_PNG);
arrImages[state + 1].Load(szFileNameCenter, CXIMAGE_FORMAT_PNG);
arrImages[state + 2].Load(szFileNameRight, CXIMAGE_FORMAT_PNG);
}
inline void AddStaticSet(CxImage arrImages[], STATE state, LPCTSTR szFileName)
{
arrImages[state].Load(szFileName, CXIMAGE_FORMAT_PNG);
}
class CFingerButton : public CWindowImpl<CFingerButton>
{
public:
DECLARE_WND_CLASS(NULL)
typedef CWindowImpl<CFingerButton> Super;
// Constructor/Destructor
CFingerButton() :
m_fNormal(1),
m_fPressed(0),
m_fFocused(0)
{
}
~CFingerButton()
{
}
// Creation
HWND Create(HWND hParentWnd, DWORD type, BOOL bVisible, COLORREF clBkg, COLORREF clBtnText, COLORREF clBtnSelText,
LPCTSTR szText, HFONT fBtn, UINT nID)
{
SetText(szText);
m_type = type;
m_fNormal = 1;
m_fPressed = 0;
m_fFocused = 0;
m_clBkg = clBkg;
m_clBtnText = clBtnText;
m_clBtnSelText = clBtnSelText;
m_fBtn = fBtn;
m_icon = NULL;
return Super::Create(hParentWnd, rcDefault, FNGRBTN_CLASS, (bVisible ? WS_VISIBLE : 0), 0, nID);
};
HWND Create(HWND hParentWnd, DWORD type, BOOL bVisible, COLORREF clBkg, int iconSize, UINT nID)
{
m_type = type;
m_fNormal = 1;
m_fPressed = 0;
m_fFocused = 0;
m_icon = NULL;
m_iconSize = iconSize;
m_clBkg = clBkg;
return Super::Create(hParentWnd, rcDefault, FNGRBTN_CLASS, (bVisible ? WS_VISIBLE : 0), 0, nID);
};
/*
void MoveUpDownWindow(int offset)
{
RECT rc; GetWindowRect(&rc);
SetWindowPos(NULL, rc.left, rc.top + offset, 0, 0, SWP_NOZORDER | SWP_NOSIZE);
LOG(L"rc.top = %d offset = %d\n", rc.top, offset);
}
*/
void SetArrayImageSet(CxImage* arrImages)
{
m_arrImages = arrImages;
}
// Overrideables
void DoPaint(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
// paint background
dc.FillSolidRect(&rc, m_clBkg);
STATE state = NOT_DEFINED;
COLORREF clText = 0;
if (m_fNormal)
{
state = NORMAL;
clText = m_clBtnText;
}
if (m_fPressed)
{
state = PUSHED;
clText = m_clBtnSelText;
}
if (m_fFocused)
state = FOCUSED;
if (m_type & FNGRBTN_TYPE_DYNAMIC)
{
int x = m_arrImages[0].GetWidth();
int y = m_arrImages[0].GetHeight();
int iWidth = (rc.right - rc.left) - 2 * x;
m_arrImages[state].Draw(dc, 0, 0);
m_arrImages[state + 1].Draw(dc, x, 0, iWidth, y);
m_arrImages[state + 2].Draw(dc, x + iWidth, 0);
}
if (m_type & FNGRBTN_TYPE_STATIC)
{
m_arrImages[state].Draw(dc);
}
// draw icon
if ((m_type & FNGRBTN_TYPE_ICON) && (m_icon != NULL))
{
int px = (rc.right - m_iconSize) / 2;
int py = (rc.bottom - m_iconSize) / 2;
m_icon.DrawIconEx(dc, px, py, m_iconSize, m_iconSize);
}
// draw icon 2
if ((m_type & FNGRBTN_TYPE_ICON) && (m_icon2 != NULL))
{
int px = (rc.right - m_iconSize) / 2;
int py = (rc.bottom - m_iconSize) / 2;
m_icon2.DrawIconEx(dc, px, py, m_iconSize, m_iconSize);
}
if (!(m_type & FNGRBTN_TYPE_ICON))
{
CFont oldFont = dc.SelectFont(m_fBtn);
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(clText);
dc.DrawText(m_text, -1, &rc, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
dc.SelectFont(oldFont);
}
}
void SetText(LPCTSTR szText)
{
if (szText != NULL)
lstrcpy(m_text, szText);
}
void SetIcon (HICON hIcon)
{
m_icon = hIcon;
Invalidate();
UpdateWindow();
}
void SetIcon2 (HICON hIcon)
{
m_icon2 = hIcon;
//Invalidate();
//UpdateWindow();
}
// Message map and handlers
BEGIN_MSG_MAP(CBitmapButton)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
MESSAGE_HANDLER(WM_CAPTURECHANGED, OnCaptureChanged)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
return 0;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
bHandled = FALSE;
return 1;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1; // no background needed
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if(wParam != NULL)
{
DoPaint((HDC)wParam);
}
else
{
CBufferedPaintDC dc(m_hWnd, 0);
DoPaint(dc.m_hDC);
}
return 0;
}
LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
SetCapture();
if(::GetCapture() == m_hWnd)
{
m_fPressed = 1;
m_fNormal = 0;
Invalidate();
UpdateWindow();
}
return 0;
}
LRESULT OnLButtonUp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& /*bHandled*/)
{
if(::GetCapture() == m_hWnd)
{
if(m_fPressed == 1)
::SendMessage(GetParent(), WM_COMMAND, MAKEWPARAM(GetDlgCtrlID(), BN_CLICKED), (LPARAM)m_hWnd);
::ReleaseCapture();
}
return 0;
}
LRESULT OnCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
if(m_fPressed == 1)
{
m_fPressed = 0;
m_fNormal = 1;
Invalidate();
UpdateWindow();
}
bHandled = FALSE;
return 1;
}
LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
if(::GetCapture() == m_hWnd)
{
POINT ptCursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
ClientToScreen(&ptCursor);
RECT rect = { 0 };
GetWindowRect(&rect);
unsigned int uPressed = ::PtInRect(&rect, ptCursor) ? 1 : 0;
if(m_fPressed != uPressed)
{
m_fPressed = uPressed;
m_fNormal = 1;
Invalidate();
UpdateWindow();
}
}
return 1;
}
public:
CxImage* m_arrImages;
protected:
DWORD m_type;
// Internal states
unsigned m_fNormal:1;
unsigned m_fPressed:1;
unsigned m_fFocused:1;
COLORREF m_clBtnText;
COLORREF m_clBtnSelText;
COLORREF m_clBkg;
WCHAR m_text[32];
CFontHandle m_fBtn;
CIconHandle m_icon;
CIconHandle m_icon2;
int m_iconSize;
};
#endif // __FNGRBTN_H__<file_sep>/7-Zip/CPP/7zip/Archive/Tar/TarOut.cpp
// TarOut.cpp
#include "StdAfx.h"
#include "Common/IntToString.h"
#include "../../Common/StreamUtils.h"
#include "TarOut.h"
namespace NArchive {
namespace NTar {
HRESULT COutArchive::WriteBytes(const void *buffer, UInt32 size)
{
return WriteStream(m_Stream, buffer, size);
}
void COutArchive::Create(ISequentialOutStream *outStream)
{
m_Stream = outStream;
}
static AString MakeOctalString(UInt64 value)
{
char s[32];
ConvertUInt64ToString(value, s, 8);
return AString(s) + ' ';
}
static void MyStrNCpy(char *dest, const char *src, int size)
{
for (int i = 0; i < size; i++)
{
char c = src[i];
dest[i] = c;
if (c == 0)
break;
}
}
static bool MakeOctalString8(char *s, UInt32 value)
{
AString tempString = MakeOctalString(value);
const int kMaxSize = 8;
if (tempString.Length() >= kMaxSize)
return false;
int numSpaces = kMaxSize - (tempString.Length() + 1);
for(int i = 0; i < numSpaces; i++)
s[i] = ' ';
MyStringCopy(s + numSpaces, (const char *)tempString);
return true;
}
static bool MakeOctalString12(char *s, UInt64 value)
{
AString tempString = MakeOctalString(value);
const int kMaxSize = 12;
if (tempString.Length() > kMaxSize)
return false;
int numSpaces = kMaxSize - tempString.Length();
for(int i = 0; i < numSpaces; i++)
s[i] = ' ';
memmove(s + numSpaces, (const char *)tempString, tempString.Length());
return true;
}
static bool CopyString(char *dest, const AString &src, int maxSize)
{
if (src.Length() >= maxSize)
return false;
MyStringCopy(dest, (const char *)src);
return true;
}
#define RETURN_IF_NOT_TRUE(x) { if (!(x)) return E_FAIL; }
HRESULT COutArchive::WriteHeaderReal(const CItem &item)
{
char record[NFileHeader::kRecordSize];
char *cur = record;
int i;
for (i = 0; i < NFileHeader::kRecordSize; i++)
record[i] = 0;
// RETURN_IF_NOT_TRUE(CopyString(header.Name, item.Name, NFileHeader::kNameSize));
if (item.Name.Length() > NFileHeader::kNameSize)
return E_FAIL;
MyStrNCpy(cur, item.Name, NFileHeader::kNameSize);
cur += NFileHeader::kNameSize;
RETURN_IF_NOT_TRUE(MakeOctalString8(cur, item.Mode));
cur += 8;
RETURN_IF_NOT_TRUE(MakeOctalString8(cur, item.UID));
cur += 8;
RETURN_IF_NOT_TRUE(MakeOctalString8(cur, item.GID));
cur += 8;
RETURN_IF_NOT_TRUE(MakeOctalString12(cur, item.Size));
cur += 12;
RETURN_IF_NOT_TRUE(MakeOctalString12(cur, item.MTime));
cur += 12;
memmove(cur, NFileHeader::kCheckSumBlanks, 8);
cur += 8;
*cur++ = item.LinkFlag;
RETURN_IF_NOT_TRUE(CopyString(cur, item.LinkName, NFileHeader::kNameSize));
cur += NFileHeader::kNameSize;
memmove(cur, item.Magic, 8);
cur += 8;
RETURN_IF_NOT_TRUE(CopyString(cur, item.User, NFileHeader::kUserNameSize));
cur += NFileHeader::kUserNameSize;
RETURN_IF_NOT_TRUE(CopyString(cur, item.Group, NFileHeader::kGroupNameSize));
cur += NFileHeader::kGroupNameSize;
if (item.DeviceMajorDefined)
RETURN_IF_NOT_TRUE(MakeOctalString8(cur, item.DeviceMajor));
cur += 8;
if (item.DeviceMinorDefined)
RETURN_IF_NOT_TRUE(MakeOctalString8(cur, item.DeviceMinor));
cur += 8;
UInt32 checkSumReal = 0;
for(i = 0; i < NFileHeader::kRecordSize; i++)
checkSumReal += Byte(record[i]);
RETURN_IF_NOT_TRUE(MakeOctalString8(record + 148, checkSumReal));
return WriteBytes(record, NFileHeader::kRecordSize);
}
HRESULT COutArchive::WriteHeader(const CItem &item)
{
int nameSize = item.Name.Length();
if (nameSize < NFileHeader::kNameSize)
return WriteHeaderReal(item);
CItem modifiedItem = item;
int nameStreamSize = nameSize + 1;
modifiedItem.Size = nameStreamSize;
modifiedItem.LinkFlag = 'L';
modifiedItem.Name = NFileHeader::kLongLink;
modifiedItem.LinkName.Empty();
RINOK(WriteHeaderReal(modifiedItem));
RINOK(WriteBytes(item.Name, nameStreamSize));
RINOK(FillDataResidual(nameStreamSize));
modifiedItem = item;
modifiedItem.Name = item.Name.Left(NFileHeader::kNameSize - 1);
return WriteHeaderReal(modifiedItem);
}
HRESULT COutArchive::FillDataResidual(UInt64 dataSize)
{
UInt32 lastRecordSize = UInt32(dataSize & (NFileHeader::kRecordSize - 1));
if (lastRecordSize == 0)
return S_OK;
UInt32 residualSize = NFileHeader::kRecordSize - lastRecordSize;
Byte residualBytes[NFileHeader::kRecordSize];
for (UInt32 i = 0; i < residualSize; i++)
residualBytes[i] = 0;
return WriteBytes(residualBytes, residualSize);
}
HRESULT COutArchive::WriteFinishHeader()
{
Byte record[NFileHeader::kRecordSize];
int i;
for (i = 0; i < NFileHeader::kRecordSize; i++)
record[i] = 0;
for (i = 0; i < 2; i++)
{
RINOK(WriteBytes(record, NFileHeader::kRecordSize));
}
return S_OK;
}
}}
<file_sep>/FingerSuite/FingerMsgBox/skins/default/settings_fingermsgbox.ini
[general]
;CenterCaption=true
[colors]
BkgColor=255 255 255
CaptionTextColor=255 255 255
TextColor=0 0 0
ButtonTextColor=0 0 0
SelButtonTextColor=255 255 255
LineColor=160 160 160
; Font settings.
; Options (separated by comma)
; 1. font weight: must be one in "regular", "italic", "bold", "bold italic"
; 2. font height in points
; 3. font face name
[fonts]
TextFont=regular,9p,
CaptionFont=bold,10p,
ButtonFont=bold,10p,
; Sound settings
; specify full path of wav file to be played
[sounds]
DefaultSound=\Windows\Alarm2.wav
ErrorSound=
WarningSound=
InfoSound=
QuestionSound=
<file_sep>/SQLCEHelper/Source/BlobStream.cpp
#include "stdafx.h"
#include "../Include/BlobStream.h"
CBlobStream::CBlobStream()
: m_pBuffer (NULL),
m_nLength (0),
m_iPosRead (0),
m_iPosWrite (0),
m_nRef (0),
m_dbStatus (DBSTATUS_S_OK)
{
AddRef();
}
CBlobStream::~CBlobStream()
{
Clear();
}
// CBlobStream::Clear
//
// Clears the buffer
//
void CBlobStream::Clear()
{
CoTaskMemFree(m_pBuffer);
m_pBuffer = NULL;
m_nLength = 0;
m_iPosRead = 0;
m_iPosWrite = 0;
m_dbStatus = DBSTATUS_S_OK;
}
ULONG CBlobStream::AddRef()
{
return ++m_nRef;
}
// CBlobStream::Release
//
// Deletes the object when the reference count reaches zero
//
ULONG CBlobStream::Release()
{
if(m_nRef)
{
--m_nRef;
if(m_nRef == 0)
delete this;
}
return m_nRef;
}
HRESULT CBlobStream::QueryInterface(REFIID riid, void** ppv)
{
*ppv = NULL;
if(riid == IID_IUnknown)
*ppv = this;
if(riid == IID_ISequentialStream)
*ppv = this;
if(*ppv)
{
((IUnknown*) *ppv)->AddRef();
return S_OK;
}
return E_NOINTERFACE;
}
// CBlobStream::Read
//
// Reads data from the BLOB stream
//
HRESULT CBlobStream::Read(void *pv, ULONG cb, ULONG* pcbRead)
{
//
// Check parameters.
//
if(pcbRead)
*pcbRead = 0;
if(!pv)
return STG_E_INVALIDPOINTER;
if(0 == cb)
return S_OK;
//
// Calculate bytes left and bytes to read.
//
ULONG cBytesLeft = m_nLength - m_iPosRead;
ULONG cBytesRead = cb > cBytesLeft ? cBytesLeft : cb;
//
// Return bytes read to caller.
//
if(pcbRead)
*pcbRead = cBytesRead;
//
// If no more bytes to retrive return S_FALSE.
//
if(0 == cBytesLeft)
return S_OK;
//
// Copy to users buffer the number of bytes requested or remaining
//
memcpy(pv, (void*)(m_pBuffer + m_iPosRead), cBytesRead);
m_iPosRead += cBytesRead;
if(cb != cBytesRead)
return S_FALSE;
return S_OK;
}
// CBlobStream::Write
//
// Writes data to the BLOB stream
//
HRESULT CBlobStream::Write(const void *pv, ULONG cb, ULONG* pcbWritten)
{
//
// Check parameters.
//
if(!pv)
return STG_E_INVALIDPOINTER;
if(pcbWritten)
*pcbWritten = 0;
if(0 == cb)
return S_OK;
//
// Enlarge the current buffer.
//
m_nLength += cb;
//
// Grow internal buffer to new size.
//
m_pBuffer = (BYTE*)CoTaskMemRealloc(m_pBuffer, m_nLength);
//
// Check for out of memory situation.
//
if(NULL == m_pBuffer)
{
Clear();
return E_OUTOFMEMORY;
}
//
// Copy callers memory to internal bufffer and update write position.
//
memcpy((void*)(m_pBuffer + m_iPosWrite), pv, cb );
m_iPosWrite += cb;
//
// Return bytes written to caller.
//
if(pcbWritten)
*pcbWritten = cb;
return S_OK;
}
// CBlobStream::WriteFromStream
//
// Writes data to the blob stream from an open IStream
//
HRESULT CBlobStream::WriteFromStream(IStream *pStream, ULONG cb, ULONG *pcbWritten)
{
HRESULT hr;
//
// Check parameters.
//
if(!pStream)
return STG_E_INVALIDPOINTER;
if(pcbWritten)
*pcbWritten = 0;
if(0 == cb)
return S_OK;
//
// Enlarge the current buffer.
//
m_nLength += cb;
//
// Grow internal buffer to new size.
//
m_pBuffer = (BYTE*)CoTaskMemRealloc(m_pBuffer, m_nLength);
//
// Check for out of memory situation.
//
if(NULL == m_pBuffer)
{
Clear();
return E_OUTOFMEMORY;
}
hr = pStream->Read((void*)(m_pBuffer + m_iPosWrite), cb, pcbWritten);
if(SUCCEEDED(hr))
m_iPosWrite += cb;
return hr;
}
// CBlobStream::WriteFromStream
//
// Writes data to the blob stream from an open ISequentialStream
//
HRESULT CBlobStream::WriteFromStream(ISequentialStream *pStream, ULONG cb, ULONG *pcbWritten)
{
HRESULT hr;
//
// Check parameters.
//
if(!pStream)
return STG_E_INVALIDPOINTER;
if(pcbWritten)
*pcbWritten = 0;
if(0 == cb)
return S_OK;
//
// Enlarge the current buffer.
//
m_nLength += cb;
//
// Grow internal buffer to new size.
//
m_pBuffer = (BYTE*)CoTaskMemRealloc(m_pBuffer, m_nLength);
//
// Check for out of memory situation.
//
if(NULL == m_pBuffer)
{
Clear();
return E_OUTOFMEMORY;
}
hr = pStream->Read((void*)(m_pBuffer + m_iPosWrite), cb, pcbWritten);
if(SUCCEEDED(hr))
m_iPosWrite += cb;
return hr;
}
<file_sep>/FingerSuite/FingerMenuRES/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerMenuRES.rc
//
#define IDS_MENU_ADDTOEXCLUSIONLIST 130
#define IDS_MENU_SHOWORIGINAL 131
#define IDS_MENU_ABOUT 132
#define IDS_MENU_EXIT 133
#define IDS_SOFTKEY_CLOSE 134
#define IDS_MENU_ADDTOWNDEXCLUSIONLIST 136
#define IDS_SOFTKEY_BACK 205
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/FingerSuite/Common/fngrsplash.h
#pragma once
#include <atlmisc.h>
class CSplashWindow :
public CWindowImpl<CSplashWindow, CWindow, CWinTraits<WS_POPUP | WS_VISIBLE, WS_EX_TOOLWINDOW> >
{
public:
CSplashWindow(HWND hParent = NULL, UINT nIconId = IDR_MAINFRAME, LPCWCHAR lpwszMessage = NULL)
: m_hParent(hParent)
{
// Create the window rect (we will centre the window later)
int sx = ::GetSystemMetrics(SM_CXSCREEN);
int sy = ::GetSystemMetrics(SM_CYSCREEN);
// Create the window
int ix = 0;
int iy = 0;
if (nIconId != NULL)
{
m_hIcon = AtlLoadIconImage(nIconId);
ICONINFO ii;
BITMAP bmp;
GetIconInfo(m_hIcon, &ii);
GetObject(ii.hbmColor, sizeof(BITMAP), &bmp);
ix = bmp.bmWidth;
iy = bmp.bmHeight;
}
if (lpwszMessage != NULL)
StringCchCopy(m_szText, MAX_PATH, lpwszMessage);
CRect rect(0, 0, (int)(sx * 0.8), iy);
if (!Create(NULL, rect))
{
ATLTRACE(_T("Failed to create splash window\n"));
return;
}
UpdateWindow();
}
void Dismiss()
{
PostMessage(WM_CLOSE);
}
virtual void OnFinalMessage(HWND /*hWnd*/)
{
delete this;
}
BEGIN_MSG_MAP(CSplashWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CenterWindow(m_hParent);
return 0;
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM /*wParam*/,
LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CPaintDC dc(m_hWnd);
RECT rc; GetClientRect(&rc);
dc.FillSolidRect(&rc, RGB(226, 226, 226));
dc.DrawIcon(0, 0, m_hIcon);
RECT rcText;
SetRect(&rcText, (rc.bottom - rc.top), rc.top, rc.right, rc.bottom);
dc.SetBkMode(TRANSPARENT);
dc.DrawText(m_szText, -1, &rcText, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
return 0;
}
LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
// No need to paint a background
return TRUE;
}
private:
HWND m_hParent;
HICON m_hIcon;
WCHAR m_szText[MAX_PATH];
};<file_sep>/FingerSuite/Common/atlcectrls.h
#ifndef __ATLCECTRLS_H__
#define __ATLCECTRLS_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLCTRLS_H__
#error atlcectrls.h requires atlctrls.h to be included first
#endif
#ifndef _WIN32_WCE
#error atlcectrls.h compiles under Windows CE only
#endif
#if (_WIN32_WCE < 400)
#error This file requires a newer version of the platform.
#endif
#include <htmlctrl.h>
#pragma comment(lib, "htmlview.lib")
#include <richink.h>
#pragma comment(lib, "richink.lib")
#include <inkx.h>
#pragma comment(lib, "inkx.lib")
#include <voicectl.h>
#pragma comment(lib, "voicectl.lib")
#include <doclist.h>
#pragma comment(lib, "doclist.lib")
///////////////////////////////////////////////////////////////////////////////
// Classes in this file:
//
// CHtmlCtrlT<TBase> - CHtmlCtrl
// CRichInkCtrlT<TBase> - CRichInkCtrl
// CInkXCtrlT<TBase> - CInkXCtrl
// CVoiceRecorderCtrlT<TBase> - CVoiceRecorderCtrl
// CDocListCtrlT<TBase> - CDocListCtrl
// CCapEdit<TBase> - CCapEdit
// CTTStatic<TBase> - CTTStatic
// CTTButton<TBase> - CTTButton
//
namespace WTL
{
// These are wrapper classes for the Windows CE 4.2 controls
// To implement a window based on a control, use following:
// Example: Implementing a window based on a list box
//
// class CMyHtml : CWindowImpl<CMyHtml, CHtmlCtrl>
// {
// public:
// BEGIN_MSG_MAP(CMyHtml)
// // put your message handler entries here
// END_MSG_MAP()
// };
///////////////////////////////////////////////////////////////////////////////
// CHtmlCtrl
template< class TBase >
class CHtmlCtrlT : public TBase
{
public:
// Constructors
CHtmlCtrlT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CHtmlCtrlT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
DWORD dwStyle = 0, DWORD dwExStyle = 0,
ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
{
HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
ATLASSERT(hWnd!=NULL); // Did you remember to call InitHTMLControl(hInstance) ??
return hWnd;
}
// Attributes
static LPCTSTR GetWndClassName()
{
return WC_HTML;
}
void AddStyle(LPCWSTR pszStyle)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ADDSTYLE, 0, (LPARAM) pszStyle);
}
void AddText(BOOL bPlainText, LPCSTR pszText)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ADDTEXT, (WPARAM) bPlainText, (LPARAM) pszText);
}
void AddHTML(LPCSTR pszHTML)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ADDTEXT, (WPARAM) FALSE, (LPARAM) pszHTML);
}
void AddText(BOOL bPlainText, LPCWSTR pszText)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ADDTEXTW, (WPARAM) bPlainText, (LPARAM) pszText);
}
void AddHTML(LPCWSTR pszHTML)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ADDTEXTW, (WPARAM) FALSE, (LPARAM) pszHTML);
}
void Anchor(LPCSTR pszAnchor)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ANCHOR, 0, (LPARAM) pszAnchor);
}
void Anchor(LPCWSTR pszAnchor)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ANCHORW, 0, (LPARAM) pszAnchor);
}
void GetBrowserDispatch(IDispatch** ppDispatch)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(ppDispatch);
ATLASSERT(*ppDispatch==NULL);
::SendMessage(m_hWnd, DTM_BROWSERDISPATCH, 0, (LPARAM) ppDispatch);
}
void Clear()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_CLEAR, 0, 0L);
}
void EnableClearType(BOOL bEnable = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ENABLECLEARTYPE, 0, (LPARAM) bEnable);
}
void EnableContextMenu(BOOL bEnable = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ENABLECONTEXTMENU, 0, (LPARAM) bEnable);
}
void EnableScripting(BOOL bEnable = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ENABLESCRIPTING, 0, (LPARAM) bEnable);
}
void EnableShrink(BOOL bEnable = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ENABLESHRINK, 0, (LPARAM) bEnable);
}
void EndOfSource()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ENDOFSOURCE, 0, 0L);
}
void ImageFail(DWORD dwCookie)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_IMAGEFAIL, 0, (LPARAM) dwCookie);
}
int GetLayoutHeight() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DTM_LAYOUTHEIGHT, 0, 0L);
}
int GetLayoutWidth() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DTM_LAYOUTWIDTH, 0, 0L);
}
void Navigate(LPCTSTR pstrURL, UINT uFlags = 0)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrURL);
::SendMessage(m_hWnd, DTM_NAVIGATE, (WPARAM) uFlags, (LPARAM) pstrURL);
}
void SelectAll()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_SELECTALL, 0, 0L);
}
void SetImage(INLINEIMAGEINFO* pImageInfo)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pImageInfo);
::SendMessage(m_hWnd, DTM_SETIMAGE, 0, (LPARAM) pImageInfo);
}
void ZoomLevel(int iLevel)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_ZOOMLEVEL, 0, (LPARAM) iLevel);
}
void Stop()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DTM_STOP, 0, 0L);
}
void GetScriptDispatch(IDispatch** ppDispatch)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(ppDispatch);
ATLASSERT(*ppDispatch==NULL);
::SendMessage(m_hWnd, DTM_SCRIPTDISPATCH, 0, (LPARAM) ppDispatch);
}
};
typedef CHtmlCtrlT<ATL::CWindow> CHtmlCtrl;
///////////////////////////////////////////////////////////////////////////////
// CRichInkCtrl
template< class TBase >
class CRichInkCtrlT : public TBase
{
public:
// Constructors
CRichInkCtrlT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CRichInkCtrlT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
DWORD dwStyle = 0, DWORD dwExStyle = 0,
ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
{
HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
ATLASSERT(hWnd!=NULL); // Did you remember to call InitRichInkDLL() ??
return hWnd;
}
// Attributes
static LPCTSTR GetWndClassName()
{
return WC_RICHINK;
}
BOOL CanPaste(UINT uFormat = 0) const
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, EM_CANPASTE, (WPARAM) uFormat, 0L);
}
BOOL CanRedo() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, EM_CANREDO, 0, 0L);
}
BOOL CanUndo() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, EM_CANUNDO, 0, 0L);
}
void ClearAll(BOOL bRepaint = TRUE) const
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_CLEARALL, (WPARAM) bRepaint, 0L);
}
BOOL GetModify() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, EM_GETMODIFY, 0, 0L);
}
UINT GetPageStyle() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (UINT) ::SendMessage(m_hWnd, EM_GETPAGESTYLE, 0, 0L);
}
UINT GetPenMode() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (UINT) ::SendMessage(m_hWnd, EM_GETPENMODE, 0, 0L);
}
UINT GetViewStyle() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (UINT) ::SendMessage(m_hWnd, EM_GETVIEW, 0, 0L);
}
UINT GetWrapMode() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (UINT) ::SendMessage(m_hWnd, EM_GETWRAPMODE, 0, 0L);
}
UINT GetZoomPercent() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (UINT) ::SendMessage(m_hWnd, EM_GETZOOMPERCENT, 0, 0L);
}
void InsertLinks(LPWSTR lpString, int cchLength = -1)
{
ATLASSERT(::IsWindow(m_hWnd));
if( cchLength == -1 ) strLength = lstrlen(lpString);
::SendMessage(m_hWnd, EM_INSERTLINKS, (WPARAM) cchLength, (LPARAM) lpString);
}
void RedoEvent()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_REDOEVENT, 0, 0L);
}
UINT SetInkLayer(UINT uLayer)
{
ATLASSERT(::IsWindow(m_hWnd));
return (UINT) ::SendMessage(m_hWnd, EM_SETINKLAYER, (WPARAM) uLayer, 0L);
}
void SetPageStyle(UINT uStyle)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_SETPAGESTYLE, (WPARAM) uStyle, 0L);
}
void SetPenMode(UINT uMode)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_SETPENMODE, (WPARAM) uMode, 0L);
}
void SetViewStyle(UINT uStyle)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_SETVIEW, (WPARAM) uStyle, 0L);
}
void SetViewAttributes(VIEWATTRIBUTES* pAttribs)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pAttribs);
::SendMessage(m_hWnd, EM_SETVIEWATTRIBUTES, 0, (LPARAM) pAttribs);
}
void SetWrapMode(UINT uMode)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_SETWRAPMODE, (WPARAM) uMode, 0L);
}
void SetZoomPercent(UINT uPercent)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_SETZOOMPERCENT, (WPARAM) uPercent, 0L);
}
LONG StreamIn(UINT uFormat, EDITSTREAM& es)
{
ATLASSERT(::IsWindow(m_hWnd));
return (LONG) ::SendMessage(m_hWnd, EM_STREAMIN, (WPARAM) uFormat, (LPARAM) &es);
}
LONG StreamOut(UINT uFormat, EDITSTREAM& es)
{
ATLASSERT(::IsWindow(m_hWnd));
return (LONG) ::SendMessage(m_hWnd, EM_STREAMOUT, (WPARAM) uFormat, (LPARAM) &es);
}
void UndoEvent()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_UNDOEVENT, 0, 0L);
}
// Standard EM_xxx messages
DWORD GetSel() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (DWORD) ::SendMessage(m_hWnd, EM_GETSEL, 0, 0L);
}
void GetSel(int& nStartChar, int& nEndChar) const
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_GETSEL, (WPARAM) &nStartChar, (LPARAM) &nEndChar);
}
void ReplaceSel(LPCTSTR lpszNewText, BOOL bCanUndo = FALSE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_REPLACESEL, (WPARAM) bCanUndo, (LPARAM) lpszNewText);
}
void SetModify(BOOL bModified = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, EM_SETMODIFY, (WPARAM) bModified, 0L);
}
int GetTextLength() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, WM_GETTEXTLENGTH, 0, 0L);
}
// Clipboard operations
void Clear()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, WM_CLEAR, 0, 0L);
}
void Copy()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, WM_COPY, 0, 0L);
}
void Cut()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, WM_CUT, 0, 0L);
}
void Paste()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, WM_PASTE, 0, 0L);
}
};
typedef CRichInkCtrlT<ATL::CWindow> CRichInkCtrl;
///////////////////////////////////////////////////////////////////////////////
// CInkXCtrl
template< class TBase >
class CInkXCtrlT : public TBase
{
public:
// Constructors
CInkXCtrlT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CInkXCtrlT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
DWORD dwStyle = 0, DWORD dwExStyle = 0,
ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
{
HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
ATLASSERT(hWnd!=NULL); // Did you remember to call InitInkX() ??
return hWnd;
}
// Attributes
static LPCTSTR GetWndClassName()
{
return WC_INKX;
}
static UINT GetHotRecordingMessage()
{
return ::RegisterWindowMessage(szHotRecording);
}
void ClearAll()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, IM_CLEARALL, 0, 0L);
}
int GetData(BYTE* lpBuffer, INT cbBuffer) const
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(lpBuffer);
return (int) ::SendMessage(m_hWnd, IM_GETDATA, (WPARAM) cbBuffer, (LPARAM) lpBuffer);
}
int GetDataLen() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, IM_GETDATALEN, 0, 0L);
}
CRichInkCtrl GetRichInk() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (HWND) ::SendMessage(m_hWnd, IM_GETRICHINK, 0, 0L);
}
BOOL IsRecording() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, IM_RECORDING, 0, 0L);
}
void ReInit()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, IM_REINIT, 0, 0L);
}
void SetData(const BYTE* lpInkData, INT cbInkData)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(lpInkData);
::SendMessage(m_hWnd, IM_SETDATA, (WPARAM) cbInkData, (LPARAM) lpInkData);
}
void VoicePlay()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, IM_VOICE_PLAY, 0, 0L);
}
BOOL IsVoicePlaying() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, IM_VOICE_PLAYING, 0, 0L);
}
BOOL VoiceRecord()
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, IM_VOICE_RECORD, 0, 0L);
}
void VoiceStop()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, IM_VOICE_STOP, 0, 0L);
}
void ShowVoiceBar(BOOL bShow = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, IM_VOICEBAR, (WPARAM) bShow, 0L);
}
};
typedef CInkXCtrlT<ATL::CWindow> CInkXCtrl;
///////////////////////////////////////////////////////////////////////////////
// CVoiceRecorderCtrl
template< class TBase >
class CVoiceRecorderCtrlT : public TBase
{
public:
// Constructors
CVoiceRecorderCtrlT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CVoiceRecorderCtrlT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, const POINT pt, LPTSTR pstrFileName,
UINT nID, DWORD dwStyle = 0)
{
ATLASSERT(pstrFileName);
CM_VOICE_RECORDER cmvr = { 0 };
cmvr.cb = sizeof(CM_VOICE_RECORDER);
cmvr.dwStyle = dwStyle;
cmvr.xPos = pt.x;
cmvr.yPos = pt.y;
cmvr.hwndParent = hWndParent;
cmvr.id = nID;
cmvr.lpszRecordFileName = pstrFileName;
m_hWnd = VoiceRecorder_Create(&cmvr);
return m_hWnd;
}
HWND Create(LPCM_VOICE_RECORDER pAttribs)
{
ATLASSERT(pAttribs);
m_hWnd = VoiceRecorder_Create(pAttribs);
return m_hWnd;
}
// Attributes
void Record()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, VRM_RECORD, 0, 0L);
}
void Play()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, VRM_PLAY, 0, 0L);
}
void Stop()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, VRM_STOP, 0, 0L);
}
void Cancel()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, VRM_CANCEL, 0, 0L);
}
void Done()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, VRM_OK, 0, 0L);
}
};
typedef CVoiceRecorderCtrlT<ATL::CWindow> CVoiceRecorderCtrl;
///////////////////////////////////////////////////////////////////////////////
// CDocListCtrl
template< class TBase >
class CDocListCtrlT : public TBase
{
public:
// Attributes
DOCLISTCREATE m_dlc;
TCHAR m_szPath[MAX_PATH];
// Constructors
CDocListCtrlT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CDocListCtrlT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, WORD wId, LPCTSTR pszFolder = NULL, LPCTSTR pstrFilter = NULL,
WORD wFilterIndex = 0, DWORD dwFlags = DLF_SHOWEXTENSION)
{
ATLASSERT(pstrFilter); // It seems to need a filter badly!!
::ZeroMemory(&m_dlc, sizeof(DOCLISTCREATE));
::ZeroMemory(m_szPath, sizeof(m_szPath));
if( pszFolder ) ::lstrcpyn(m_szPath, pszFolder, MAX_PATH - 1);
m_dlc.dwStructSize = sizeof(DOCLISTCREATE);
m_dlc.hwndParent = hWndParent;
m_dlc.pszFolder = m_szPath;
m_dlc.pstrFilter = pstrFilter;
m_dlc.wFilterIndex = wFilterIndex;
m_dlc.wId = wId;
m_dlc.dwFlags = dwFlags;
m_hWnd = DocList_Create(&m_dlc);
return m_hWnd;
}
HWND Create(DOCLISTCREATE* pDlc)
{
m_dlc = *pDlc;
m_hWnd = DocList_Create(&m_dlc);
return m_hWnd;
}
// Attributes
void DeleteSel()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_DELETESEL, 0, 0L);
}
void DisableUpdates()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_DISABLEUPDATES, 0, 0L);
}
void EnableUpdates()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_ENABLEUPDATES, 0, 0L);
}
int GetFilterIndex() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DLM_GETFILTERINDEX, 0, 0L);
}
int GetItemCount() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DLM_GETITEMCOUNT, 0, 0L);
}
int GetNextItem(int iIndex, DWORD dwRelation = LVNI_ALL) const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DLM_GETNEXTITEM, (WPARAM) iIndex, (LPARAM) dwRelation);
}
int GetFirstItem(DWORD dwRelation = LVNI_ALL) const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DLM_GETNEXTITEM, (WPARAM) -1, (LPARAM) dwRelation);
}
BOOL GetNextWave(int* pIndex) const
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pIndex);
return (BOOL) ::SendMessage(m_hWnd, DLM_GETNEXTWAVE, 0, (LPARAM) pIndex);
}
BOOL GetPrevWave(int* pIndex) const
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pIndex);
return (BOOL) ::SendMessage(m_hWnd, DLM_GETPREVWAVE, 0, (LPARAM) pIndex);
}
int GetSelCount() const
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DLM_GETSELCOUNT, 0, 0L);
}
BOOL GetSelPathName(LPTSTR pstrPath, int cchMax) const
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrPath);
return (BOOL) ::SendMessage(m_hWnd, DLM_GETSELPATHNAME, (WPARAM) cchMax, (LPARAM) pstrPath);
}
void ReceiveIR(LPCTSTR pstrPath) const
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrPath);
::SendMessage(m_hWnd, DLM_RECEIVEIR, 0, (LPARAM) pstrPath);
}
void Refresh()
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_REFRESH, 0, 0L);
}
BOOL RenameMoveSelectedItems()
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, DLM_RENAMEMOVE, 0, 0L);
}
int SelectAll()
{
ATLASSERT(::IsWindow(m_hWnd));
return (int) ::SendMessage(m_hWnd, DLM_SELECTALL, 0, 0L);
}
HRESULT SelectItem(LPCTSTR pstrPath, BOOL bVisible = TRUE)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrPath);
return (HRESULT) ::SendMessage(m_hWnd, DLM_SELECTITEM, (WPARAM) bVisible, (LPARAM) pstrPath);
}
void SendEMail(LPCTSTR pstrAttachment)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_SENDEMAIL, 0, (LPARAM) pstrAttachment);
}
void SendIR(LPCTSTR pstrPath)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_SENDIR, 0, (LPARM) pstrPath);
}
HRESULT SetFilterIndex(int iIndex)
{
ATLASSERT(::IsWindow(m_hWnd));
return (HRESULT) ::SendMessage(m_hWnd, DLM_SETFILTERINDEX, (WPARAM) iIndex, 0L);
}
void SetFolder(LPCTSTR pstrPath)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrPath);
::SendMessage(m_hWnd, DLM_SETFOLDER, 0, (LPARAM) pstrPath);
}
BOOL SetItemState(int iIndex, const LVITEM* pItem)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pItem);
return (BOOL) ::SendMessage(m_hWnd, DLM_SETITEMSTATE, (WPARAM) iIndex, (LPARAM) pItem);
}
BOOL SetItemState(int iIndex, UINT uState, UINT uMask)
{
ATLASSERT(::IsWindow(m_hWnd));
LV_ITEM lvi = { 0 };
lvi.stateMask = uMask;
lvi.state = uState;
return (BOOL) ::SendMessage(m_hWnd, DLM_SETITEMSTATE, (WPARAM) iIndex, (LPARAM) pItem);
}
void SetOneItem(int iIndex, LPCVOID pPA)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_SETONEITEM, (WPARAM) iIndex, (LPARAM) pPA);
}
void SetSelect(int iIndex)
{
ATLASSERT(::IsWindow(m_hWnd));
::SendMessage(m_hWnd, DLM_SETSELECT, (WPARAM) iIndex, 0L);
}
void SetSelPathName(LPCTSTR pstrPath)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrPath);
::SendMessage(m_hWnd, DLM_SETSELPATHNAME, 0, (LPARAM) pstrPath);
}
BOOL SetSortOrder()
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, DLM_SETSORTORDER, 0, 0L);
}
HRESULT Update()
{
ATLASSERT(::IsWindow(m_hWnd));
return (HRESULT) ::SendMessage(m_hWnd, DLM_UPDATE, 0, 0L);
}
BOOL ValidateFolder()
{
ATLASSERT(::IsWindow(m_hWnd));
return (BOOL) ::SendMessage(m_hWnd, DLM_VALIDATEFOLDER, 0, 0L);
}
// Functions
BOOL GetFirstSelectedWaveFile(int* pIndex, LPTSTR szPath, const size_t cchPath)
{
ATLASSERT(::IsWindow(m_hWnd));
return DocList_GetFirstSelectedWaveFile(m_hWnd, pIndex, szPath, cchPath);
}
BOOL GetNextSelectedWaveFile(int* pIndex, LPTSTR szPath, const size_t cchPath)
{
ATLASSERT(::IsWindow(m_hWnd));
return DocList_GetNextSelectedWaveFile(m_hWnd, pIndex, szPath, cchPath);
}
};
typedef CDocListCtrlT<ATL::CWindow> CDocListCtrl;
///////////////////////////////////////////////////////////////////////////////
// CCapEdit
template< class TBase >
class CCapEditT : public TBase
{
public:
// Constructors
CCapEditT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CCapEditT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
DWORD dwStyle = 0, DWORD dwExStyle = 0,
ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
{
HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
ATLASSERT(hWnd!=NULL); // Did you remember to call SHInitExtraControls() ??
return hWnd;
}
// Attributes
static LPCTSTR GetWndClassName()
{
return WC_CAPEDIT;
}
};
typedef CCapEditT<WTL::CEdit> CCapEdit;
///////////////////////////////////////////////////////////////////////////////
// CTTStatic
template< class TBase >
class CTTStaticT : public TBase
{
public:
// Constructors
CTTStaticT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CTTStaticT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
DWORD dwStyle = 0, DWORD dwExStyle = 0,
ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
{
HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
ATLASSERT(hWnd!=NULL); // Did you remember to call SHInitExtraControls() ??
return hWnd;
}
// Attributes
static LPCTSTR GetWndClassName()
{
return WC_TSTATIC;
}
// Operations
int SetToolTipText(LPCTSTR pstrTipText)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrTipText);
ATLASSERT(lstrlen(pstrTipText)<=253);
LPTSTR pstr = _alloca((lstrlen(pstrTipText) + 3) * sizeof(TCHAR));
::lstrcpy(pstr, _T("~~"));
::lstrcat(pstr, pstrTipText);
return SetWindowText(pstr);
}
};
typedef CTTStaticT<WTL::CStatic> CTTStatic;
///////////////////////////////////////////////////////////////////////////////
// CTTButton
template< class TBase >
class CTTButtonT : public TBase
{
public:
// Constructors
CTTButtonT(HWND hWnd = NULL) : TBase(hWnd)
{
}
CTTButtonT< TBase >& operator =(HWND hWnd)
{
m_hWnd = hWnd;
return *this;
}
HWND Create(HWND hWndParent, ATL::_U_RECT rect = NULL, LPCTSTR szWindowName = NULL,
DWORD dwStyle = 0, DWORD dwExStyle = 0,
ATL::_U_MENUorID MenuOrID = 0U, LPVOID lpCreateParam = NULL)
{
HWND hWnd = TBase::Create(GetWndClassName(), hWndParent, rect.m_lpRect, szWindowName, dwStyle, dwExStyle, MenuOrID.m_hMenu, lpCreateParam);
ATLASSERT(hWnd!=NULL); // Did you remember to call SHInitExtraControls() ??
return hWnd;
}
// Attributes
static LPCTSTR GetWndClassName()
{
return WC_TBUTTON;
}
// Operations
int SetToolTipText(LPCTSTR pstrTipText)
{
ATLASSERT(::IsWindow(m_hWnd));
ATLASSERT(pstrTipText);
ATLASSERT(lstrlen(pstrTipText)<=253);
LPTSTR pstr = _alloca((lstrlen(pstrTipText) + 3) * sizeof(TCHAR));
::lstrcpy(pstr, _T("~~"));
::lstrcat(pstr, pstrTipText);
return SetWindowText(pstr);
}
};
typedef CTTButtonT<WTL::CButton> CTTButton;
}; // namespace
#endif // __ATLCECTRLS_H__
<file_sep>/7-Zip/CPP/7zip/Archive/Tar/TarHandlerOut.cpp
// TarHandlerOut.cpp
#include "StdAfx.h"
#include "Common/ComTry.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "TarHandler.h"
#include "TarUpdate.h"
using namespace NWindows;
namespace NArchive {
namespace NTar {
STDMETHODIMP CHandler::GetFileTimeType(UInt32 *type)
{
*type = NFileTimeType::kUnix;
return S_OK;
}
static HRESULT GetPropString(IArchiveUpdateCallback *callback, UInt32 index, PROPID propId, AString &res)
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(index, propId, &prop));
if (prop.vt == VT_BSTR)
res = UnicodeStringToMultiByte(prop.bstrVal, CP_OEMCP);
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
return S_OK;
}
STDMETHODIMP CHandler::UpdateItems(ISequentialOutStream *outStream, UInt32 numItems,
IArchiveUpdateCallback *callback)
{
COM_TRY_BEGIN
if ((_stream && !_isGood) || _seqStream)
return E_NOTIMPL;
CObjectVector<CUpdateItem> updateItems;
for (UInt32 i = 0; i < numItems; i++)
{
CUpdateItem ui;
Int32 newData;
Int32 newProps;
UInt32 indexInArchive;
if (!callback)
return E_FAIL;
RINOK(callback->GetUpdateItemInfo(i, &newData, &newProps, &indexInArchive));
ui.NewProps = IntToBool(newProps);
ui.NewData = IntToBool(newData);
ui.IndexInArchive = indexInArchive;
ui.IndexInClient = i;
if (IntToBool(newProps))
{
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(i, kpidIsDir, &prop));
if (prop.vt == VT_EMPTY)
ui.IsDir = false;
else if (prop.vt != VT_BOOL)
return E_INVALIDARG;
else
ui.IsDir = (prop.boolVal != VARIANT_FALSE);
}
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(i, kpidPosixAttrib, &prop));
if (prop.vt == VT_EMPTY)
ui.Mode = 0777 | (ui.IsDir ? 0040000 : 0100000);
else if (prop.vt != VT_UI4)
return E_INVALIDARG;
else
ui.Mode = prop.ulVal;
}
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(i, kpidMTime, &prop));
if (prop.vt == VT_EMPTY)
ui.Time = 0;
else if (prop.vt != VT_FILETIME)
return E_INVALIDARG;
else if (!NTime::FileTimeToUnixTime(prop.filetime, ui.Time))
ui.Time = 0;
}
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(i, kpidPath, &prop));
if (prop.vt == VT_BSTR)
ui.Name = UnicodeStringToMultiByte(NItemName::MakeLegalName(prop.bstrVal), CP_OEMCP);
else if (prop.vt != VT_EMPTY)
return E_INVALIDARG;
if (ui.IsDir)
ui.Name += '/';
}
RINOK(GetPropString(callback, i, kpidUser, ui.User));
RINOK(GetPropString(callback, i, kpidGroup, ui.Group));
}
if (IntToBool(newData))
{
NCOM::CPropVariant prop;
RINOK(callback->GetProperty(i, kpidSize, &prop));
if (prop.vt != VT_UI8)
return E_INVALIDARG;
ui.Size = prop.uhVal.QuadPart;
if (ui.Size >= ((UInt64)1 << 33))
return E_INVALIDARG;
}
updateItems.Add(ui);
}
return UpdateArchive(_stream, outStream, _items, updateItems, callback);
COM_TRY_END
}
}}
<file_sep>/7-Zip/CPP/7zip/Archive/Tar/TarIn.cpp
// TarIn.cpp
#include "StdAfx.h"
#include "Common/StringToInt.h"
#include "../../Common/StreamUtils.h"
#include "TarIn.h"
namespace NArchive {
namespace NTar {
static void MyStrNCpy(char *dest, const char *src, int size)
{
for (int i = 0; i < size; i++)
{
char c = src[i];
dest[i] = c;
if (c == 0)
break;
}
}
static bool OctalToNumber(const char *srcString, int size, UInt64 &res)
{
char sz[32];
MyStrNCpy(sz, srcString, size);
sz[size] = 0;
const char *end;
int i;
for (i = 0; sz[i] == ' '; i++);
res = ConvertOctStringToUInt64(sz + i, &end);
return (*end == ' ' || *end == 0);
}
static bool OctalToNumber32(const char *srcString, int size, UInt32 &res)
{
UInt64 res64;
if (!OctalToNumber(srcString, size, res64))
return false;
res = (UInt32)res64;
return (res64 <= 0xFFFFFFFF);
}
#define RIF(x) { if (!(x)) return S_FALSE; }
static bool IsRecordLast(const char *buf)
{
for (int i = 0; i < NFileHeader::kRecordSize; i++)
if (buf[i] != 0)
return false;
return true;
}
static void ReadString(const char *s, int size, AString &result)
{
char temp[NFileHeader::kRecordSize + 1];
MyStrNCpy(temp, s, size);
temp[size] = '\0';
result = temp;
}
static HRESULT GetNextItemReal(ISequentialInStream *stream, bool &filled, CItemEx &item, size_t &processedSize)
{
item.LongLinkSize = 0;
char buf[NFileHeader::kRecordSize];
char *p = buf;
filled = false;
processedSize = NFileHeader::kRecordSize;
RINOK(ReadStream(stream, buf, &processedSize));
if (processedSize == 0 || (processedSize == NFileHeader::kRecordSize && IsRecordLast(buf)))
return S_OK;
if (processedSize < NFileHeader::kRecordSize)
return S_FALSE;
ReadString(p, NFileHeader::kNameSize, item.Name); p += NFileHeader::kNameSize;
RIF(OctalToNumber32(p, 8, item.Mode)); p += 8;
if (!OctalToNumber32(p, 8, item.UID)) item.UID = 0; p += 8;
if (!OctalToNumber32(p, 8, item.GID)) item.GID = 0; p += 8;
RIF(OctalToNumber(p, 12, item.Size)); p += 12;
RIF(OctalToNumber32(p, 12, item.MTime)); p += 12;
UInt32 checkSum;
RIF(OctalToNumber32(p, 8, checkSum));
memcpy(p, NFileHeader::kCheckSumBlanks, 8); p += 8;
item.LinkFlag = *p++;
ReadString(p, NFileHeader::kNameSize, item.LinkName); p += NFileHeader::kNameSize;
memcpy(item.Magic, p, 8); p += 8;
ReadString(p, NFileHeader::kUserNameSize, item.User); p += NFileHeader::kUserNameSize;
ReadString(p, NFileHeader::kGroupNameSize, item.Group); p += NFileHeader::kGroupNameSize;
item.DeviceMajorDefined = (p[0] != 0); RIF(OctalToNumber32(p, 8, item.DeviceMajor)); p += 8;
item.DeviceMinorDefined = (p[0] != 0); RIF(OctalToNumber32(p, 8, item.DeviceMinor)); p += 8;
AString prefix;
ReadString(p, NFileHeader::kPrefixSize, prefix);
p += NFileHeader::kPrefixSize;
if (!prefix.IsEmpty() && item.IsMagic() &&
(item.LinkFlag != 'L' /* || prefix != "00000000000" */ ))
item.Name = prefix + AString('/') + item.Name;
if (item.LinkFlag == NFileHeader::NLinkFlag::kLink)
item.Size = 0;
UInt32 checkSumReal = 0;
for (int i = 0; i < NFileHeader::kRecordSize; i++)
checkSumReal += (Byte)buf[i];
if (checkSumReal != checkSum)
return S_FALSE;
filled = true;
return S_OK;
}
HRESULT ReadItem(ISequentialInStream *stream, bool &filled, CItemEx &item)
{
size_t processedSize;
RINOK(GetNextItemReal(stream, filled, item, processedSize));
if (!filled)
return S_OK;
// GNUtar extension
if (item.LinkFlag == 'L' || // NEXT file has a long name
item.LinkFlag == 'K') // NEXT file has a long linkname
{
if (item.Name.Compare(NFileHeader::kLongLink) != 0)
if (item.Name.Compare(NFileHeader::kLongLink2) != 0)
return S_FALSE;
AString fullName;
if (item.Size > (1 << 15))
return S_FALSE;
int packSize = (int)item.GetPackSize();
char *buffer = fullName.GetBuffer(packSize + 1);
RINOK(ReadStream_FALSE(stream, buffer, packSize));
processedSize += packSize;
buffer[item.Size] = '\0';
fullName.ReleaseBuffer();
UInt64 headerPosition = item.HeaderPosition;
if (item.LinkFlag == 'L')
{
size_t processedSize2;
RINOK(GetNextItemReal(stream, filled, item, processedSize2));
item.LongLinkSize = (unsigned)processedSize;
}
else
{
item.LongLinkSize = (unsigned)processedSize - NFileHeader::kRecordSize;
item.Size = 0;
}
item.Name = fullName;
item.HeaderPosition = headerPosition;
}
else if (item.LinkFlag == 'g' || item.LinkFlag == 'x' || item.LinkFlag == 'X')
{
// pax Extended Header
return S_OK;
}
else if (item.LinkFlag == NFileHeader::NLinkFlag::kDumpDir)
{
// GNU Extensions to the Archive Format
return S_OK;
}
else if (item.LinkFlag > '7' || (item.LinkFlag < '0' && item.LinkFlag != 0))
return S_FALSE;
return S_OK;
}
}}
<file_sep>/SQLCEHelper/Source/Index.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
//-------------------------------------------------------------------------
//
// CIndex - manipulates the table index schema
//
//-------------------------------------------------------------------------
// CIndex::CIndex
//
// Default constructor
//
CIndex::CIndex()
: m_bUnique (false),
m_bPrimary (false),
m_bConstraint (false)
{
}
CIndex::CIndex(LPCTSTR pszIndexName, bool bUnique, bool bPrimary)
: m_strName (pszIndexName),
m_bUnique (bUnique),
m_bPrimary (bPrimary),
m_bConstraint (false)
{
}
// CIndex::CIndex
//
// Initialize a CIndex from an OLE DB constraint description.
// This constructor is used for UNIQUE constraints.
//
CIndex::CIndex(DBCONSTRAINTDESC* pConstraintDesc)
: m_bUnique (true),
m_bPrimary (false),
m_bConstraint (false)
{
ULONG i;
ATLASSERT(pConstraintDesc != NULL);
m_strName = pConstraintDesc->pConstraintID->uName.pwszName;
m_bConstraint = pConstraintDesc->ConstraintType == DBCONSTRAINTTYPE_UNIQUE;
m_bPrimary = pConstraintDesc->ConstraintType == DBCONSTRAINTTYPE_PRIMARYKEY;
for(i = 0; i < pConstraintDesc->cColumns; ++i)
AddColumn(pConstraintDesc->rgColumnList[i].uName.pwszName, DB_COLLATION_ASC, i + 1);
}
CIndex::~CIndex()
{
size_t i, n = m_columns.GetCount();
for(i = 0; i < n; ++i)
delete m_columns[i];
}
// CIndex::AddColumn
//
// Adds a new index column to the list
//
void CIndex::AddColumn(LPCTSTR pszColumnName, short nCollation, ULONG nOrdinal)
{
CIndexColumn* pIndexColumn = new CIndexColumn(pszColumnName, nCollation, nOrdinal);
if(pIndexColumn != NULL)
m_columns.Add(pIndexColumn);
}
// CIndex::FindColumn
//
// Finds an index column given its name.
// Returns the zero-based index of the column or -1 if not found.
//
int CIndex::FindColumn(LPCTSTR pszColumnName)
{
int i, n = int(m_columns.GetCount());
for(i = 0; i < n; ++i)
{
if(wcsicmp(pszColumnName, m_columns[i]->GetName()) == 0)
return i;
}
return -1;
}
<file_sep>/7-Zip/CPP/7zip/Archive/Nsis/NsisDecode.cpp
// NsisDecode.cpp
#include "StdAfx.h"
#include "NsisDecode.h"
#include "../../Common/StreamUtils.h"
#include "../../Common/MethodId.h"
#include "../../Common/CreateCoder.h"
namespace NArchive {
namespace NNsis {
static const CMethodId k_Copy = 0x0;
static const CMethodId k_Deflate = 0x040901;
static const CMethodId k_BZip2 = 0x040902;
static const CMethodId k_LZMA = 0x030101;
static const CMethodId k_BCJ_X86 = 0x03030103;
HRESULT CDecoder::Init(
DECL_EXTERNAL_CODECS_LOC_VARS
IInStream *inStream, NMethodType::EEnum method, bool thereIsFilterFlag, bool &useFilter)
{
useFilter = false;
CObjectVector< CMyComPtr<ISequentialInStream> > inStreams;
if (_decoderInStream)
if (method != _method)
Release();
_method = method;
if (!_codecInStream)
{
CMethodId methodID;
switch (method)
{
case NMethodType::kCopy: methodID = k_Copy; break;
case NMethodType::kDeflate: methodID = k_Deflate; break;
case NMethodType::kBZip2: methodID = k_BZip2; break;
case NMethodType::kLZMA: methodID = k_LZMA; break;
default: return E_NOTIMPL;
}
CMyComPtr<ICompressCoder> coder;
RINOK(CreateCoder(
EXTERNAL_CODECS_LOC_VARS
methodID, coder, false));
if (!coder)
return E_NOTIMPL;
coder.QueryInterface(IID_ISequentialInStream, &_codecInStream);
if (!_codecInStream)
return E_NOTIMPL;
}
if (thereIsFilterFlag)
{
UInt32 processedSize;
BYTE flag;
RINOK(inStream->Read(&flag, 1, &processedSize));
if (processedSize != 1)
return E_FAIL;
if (flag > 1)
return E_NOTIMPL;
useFilter = (flag != 0);
}
if (useFilter)
{
if (!_filterInStream)
{
CMyComPtr<ICompressCoder> coder;
RINOK(CreateCoder(
EXTERNAL_CODECS_LOC_VARS
k_BCJ_X86, coder, false));
if (!coder)
return E_NOTIMPL;
coder.QueryInterface(IID_ISequentialInStream, &_filterInStream);
if (!_filterInStream)
return E_NOTIMPL;
}
CMyComPtr<ICompressSetInStream> setInStream;
_filterInStream.QueryInterface(IID_ICompressSetInStream, &setInStream);
if (!setInStream)
return E_NOTIMPL;
RINOK(setInStream->SetInStream(_codecInStream));
_decoderInStream = _filterInStream;
}
else
_decoderInStream = _codecInStream;
if (method == NMethodType::kLZMA)
{
CMyComPtr<ICompressSetDecoderProperties2> setDecoderProperties;
_codecInStream.QueryInterface(IID_ICompressSetDecoderProperties2, &setDecoderProperties);
if (setDecoderProperties)
{
static const UInt32 kPropertiesSize = 5;
BYTE properties[kPropertiesSize];
UInt32 processedSize;
RINOK(inStream->Read(properties, kPropertiesSize, &processedSize));
if (processedSize != kPropertiesSize)
return E_FAIL;
RINOK(setDecoderProperties->SetDecoderProperties2((const Byte *)properties, kPropertiesSize));
}
}
{
CMyComPtr<ICompressSetInStream> setInStream;
_codecInStream.QueryInterface(IID_ICompressSetInStream, &setInStream);
if (!setInStream)
return E_NOTIMPL;
RINOK(setInStream->SetInStream(inStream));
}
{
CMyComPtr<ICompressSetOutStreamSize> setOutStreamSize;
_codecInStream.QueryInterface(IID_ICompressSetOutStreamSize, &setOutStreamSize);
if (!setOutStreamSize)
return E_NOTIMPL;
RINOK(setOutStreamSize->SetOutStreamSize(NULL));
}
if (useFilter)
{
/*
CMyComPtr<ICompressSetOutStreamSize> setOutStreamSize;
_filterInStream.QueryInterface(IID_ICompressSetOutStreamSize, &setOutStreamSize);
if (!setOutStreamSize)
return E_NOTIMPL;
RINOK(setOutStreamSize->SetOutStreamSize(NULL));
*/
}
return S_OK;
}
HRESULT CDecoder::Read(void *data, size_t *processedSize)
{
return ReadStream(_decoderInStream, data, processedSize);;
}
}}
<file_sep>/SQLCEHelper/Source/DbPropSet.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
CDbPropSet::CDbPropSet(GUID guid)
{
guidPropertySet = guid;
cProperties = 0;
rgProperties = NULL;
}
CDbPropSet::~CDbPropSet()
{
Clear();
}
void CDbPropSet::Clear()
{
ULONG i;
for(i = 0; i < cProperties; ++i)
VariantClear(&rgProperties[i].vValue);
cProperties = 0;
CoTaskMemFree(rgProperties);
rgProperties = NULL;
}
bool CDbPropSet::AddProperty(const CDbProp &prop)
{
DBPROP* pProps = (DBPROP*)CoTaskMemRealloc(rgProperties, (cProperties + 1) * sizeof(DBPROP));
if(pProps != NULL)
{
prop.CopyTo(pProps + cProperties);
rgProperties = pProps;
++cProperties;
return true;
}
return false;
}
bool CDbPropSet::AddProperty(DBPROPID id, int propVal)
{
CDbProp prop;
prop.dwPropertyID = id;
prop.dwOptions = DBPROPOPTIONS_REQUIRED;
prop.dwStatus = DBPROPSTATUS_OK;
prop.colid = DB_NULLID;
prop.vValue.vt = VT_I4;
prop.vValue.intVal = propVal;
return AddProperty(prop);
}
bool CDbPropSet::AddProperty(DBPROPID id, bool propVal)
{
CDbProp prop;
prop.dwPropertyID = id;
prop.dwOptions = DBPROPOPTIONS_REQUIRED;
prop.dwStatus = DBPROPSTATUS_OK;
prop.colid = DB_NULLID;
prop.vValue.vt = VT_BOOL;
prop.vValue.boolVal = propVal ? VARIANT_TRUE : VARIANT_FALSE;
return AddProperty(prop);
}
bool CDbPropSet::AddProperty(DBPROPID id, LPCTSTR propVal)
{
CDbProp prop;
prop.dwPropertyID = id;
prop.dwOptions = DBPROPOPTIONS_REQUIRED;
prop.dwStatus = DBPROPSTATUS_OK;
prop.colid = DB_NULLID;
prop.vValue.vt = VT_BSTR;
prop.vValue.bstrVal = SysAllocString(propVal);
if(prop.vValue.bstrVal == NULL)
return false;
return AddProperty(prop);
}
<file_sep>/FBReaderJ/src/org/parser/txt/TxtParser.java
package org.parser.txt;
import java.io.InputStream;
import org.geometerplus.zlibrary.core.txt.ZLTxtReader;
import android.util.Log;
public final class TxtParser {
static {
System.loadLibrary("TxtParser");
}
protected String strFilePath;
protected ZLTxtReader txtReader;
///////////////////////////////////////////////////////////////////
private static native void Parser(TxtParser parser, String strPath);
/////////////////////////////////////////////////////////////////////
public TxtParser(ZLTxtReader txtReader, String strPath) {
strFilePath = new String(strPath);
this.txtReader = txtReader;
}
public void Check(int nLen) {
Parser(this, new String("123"));
}
public void doIt() {
if (strFilePath != null) {
Parser(this, strFilePath);
}
}
public void characterDataHandler(String strContent) {
Log.d("TEXT Reader:", strContent);
//byte[] bContent = tag.getBytes();
// addByteData(bContent, 0, bContent.length);
txtReader.characterDataHandler(new String(strContent));
}
public void startElementHandler() {
// startNewParagraph();
Log.d("TEXT Reader:", "startElementHandler");
txtReader.startElementHandler();
}
public void endElementHandler() {
// endParagraph();
Log.d("TEXT Reader:", "endElementHandler");
txtReader.endElementHandler();
}
}
<file_sep>/FingerSuite/FingerMenuCTRL/Commons.h
#pragma once
#define MENU_ITEM_TEXT_SIZE 1024
typedef struct tagMENUINFO
{
MENUITEMINFO mii;
WCHAR text[MENU_ITEM_TEXT_SIZE];
BOOL bFollowSeparator;
HMENU hOwnerMenu;
HWND hDestWnd;
DWORD fPosition;
} MENUINFO, *LPMENUINFO;
typedef struct tagMENU
{
HMENU hMenu;
BOOL bInitMenuSent;
HMENU hPrevMenu;
} MENU, *LPMENU;
<file_sep>/SQLCEHelper/Source/SchemaRowset.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
CSchemaRowset::CSchemaRowset(CSession& session)
: m_pSchemaRowset(NULL)
{
IUnknown* pUnknown = session;
pUnknown->QueryInterface(IID_IDBSchemaRowset, (void**)&m_pSchemaRowset);
}
CSchemaRowset::~CSchemaRowset()
{
if(m_pSchemaRowset != NULL)
{
m_pSchemaRowset->Release();
m_pSchemaRowset = NULL;
}
}
HRESULT CSchemaRowset::Open(REFGUID rguidSchema, ULONG cRestrictions, const VARIANT rgRestrictions[], CRowset &rowset)
{
HRESULT hr;
IRowset* pRowset = NULL;
ATLASSERT(m_pSchemaRowset != NULL);
hr = m_pSchemaRowset->GetRowset(NULL, rguidSchema, cRestrictions, rgRestrictions, IID_IRowset, 0, NULL, (IUnknown**)&pRowset);
if(FAILED(hr))
return hr;
hr = rowset.Open(pRowset);
return hr;
}
// CTablesRowset::Open
//
// Opens the tables rowset
//
HRESULT CTablesRowset::Open(LPCTSTR pszCatalog, LPCTSTR pszSchema, LPCTSTR pszTable, LPCTSTR pszType, CRowset &rowset)
{
HRESULT hr;
CComVariant varParam[4];
if(pszCatalog != NULL)
varParam[0] = pszCatalog;
if(pszSchema != NULL)
varParam[1] = pszSchema;
if(pszTable != NULL)
varParam[2] = pszTable;
if(pszType != NULL)
varParam[3] = pszType;
hr = CSchemaRowset::Open(DBSCHEMA_TABLES, 4, varParam, rowset);
return hr;
}
HRESULT CViewsRowset::Open(LPCTSTR pszCatalog, LPCTSTR pszSchema, LPCTSTR pszTable, CRowset &rowset)
{
HRESULT hr;
CComVariant varParam[3];
if(pszCatalog != NULL)
varParam[0] = pszCatalog;
if(pszSchema != NULL)
varParam[1] = pszSchema;
if(pszTable != NULL)
varParam[2] = pszTable;
hr = CSchemaRowset::Open(DBSCHEMA_VIEWS, 3, varParam, rowset);
return hr;
}
// CColumnsRowset::Open
//
// Opens the columns rowset with the given restrictions
//
HRESULT CColumnsRowset::Open(LPCTSTR pszTableCatalog,
LPCTSTR pszTableSchema,
LPCTSTR pszTableName,
LPCTSTR pszColumnName,
CRowset& rowset)
{
HRESULT hr;
CComVariant varParam[4];
if(pszTableCatalog != NULL)
varParam[0] = pszTableCatalog;
if(pszTableSchema != NULL)
varParam[1] = pszTableSchema;
if(pszTableName != NULL)
varParam[2] = pszTableName;
if(pszColumnName != NULL)
varParam[3] = pszColumnName;
hr = CSchemaRowset::Open(DBSCHEMA_COLUMNS, 4, varParam, rowset);
return hr;
}
// CIndexesRowset::Open
//
// Opens the indexes rowset with the given restrictions
//
HRESULT CIndexesRowset::Open(LPCTSTR pszCatalog,
LPCTSTR pszTableSchema,
LPCTSTR pszIndexName,
LPCTSTR pszType,
LPCTSTR pszTableName,
CRowset& rowset)
{
HRESULT hr;
CComVariant varParam[5];
if(pszCatalog != NULL)
varParam[0] = pszCatalog;
if(pszTableSchema != NULL)
varParam[1] = pszTableSchema;
if(pszIndexName != NULL)
varParam[2] = pszIndexName;
if(pszType != NULL)
varParam[3] = pszType;
if(pszTableName != NULL)
varParam[4] = pszTableName;
hr = CSchemaRowset::Open(DBSCHEMA_INDEXES, 5, varParam, rowset);
return hr;
}
<file_sep>/7-Zip/CPP/7zip/Archive/Zip/ZipCompressionMode.h
// CompressionMode.h
#ifndef __ZIP_COMPRESSION_MODE_H
#define __ZIP_COMPRESSION_MODE_H
#include "Common/MyString.h"
namespace NArchive {
namespace NZip {
struct CCompressionMethodMode
{
CRecordVector<Byte> MethodSequence;
UString MatchFinder;
UInt32 Algo;
UInt32 NumPasses;
UInt32 NumFastBytes;
bool NumMatchFinderCyclesDefined;
UInt32 NumMatchFinderCycles;
UInt32 DicSize;
#ifndef _7ZIP_ST
UInt32 NumThreads;
#endif
bool PasswordIsDefined;
AString Password;
bool IsAesMode;
Byte AesKeyMode;
CCompressionMethodMode():
NumMatchFinderCyclesDefined(false),
PasswordIsDefined(false),
IsAesMode(false),
AesKeyMode(3)
{}
};
}}
#endif
<file_sep>/FingerSuite/FingerMenuCTRL/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerMenu.rc
//
#define IDR_MAINFRAME 128
#define IDS_MENU_CONFIGURE 129
#define IDS_MENU_ADDTOEXCLUSIONLIST 130
#define IDS_MENU_SHOWORIGINAL 131
#define IDS_MENU_ABOUT 132
#define IDS_MENU_EXIT 133
#define IDS_SOFTKEY_CLOSE 134
#define IDS_MENU_ADDTOWNDEXCLUSIONLIST 136
#define IDS_SOFTKEY_BACK 205
#define IDS_UNKNOWN_ERROR 444
#define IDR_CHECKED 201
#define IDR_SUBMENU 202
#define ID_MENU_EXIT 32776
#define ID_MENU_CONFIGURE 32777
#define ID_MENU_ADDTOEXCLUSIONLIST 32778
#define ID_MENU_ABOUT 32779
#define ID_MENU_SHOWORIGINAL 32780
#define ID_BACK 32781
#define ID_MENU_ADDTOWNDEXCLUSIONLIST 32782
#define FM_IDW_MENU_BAR 0xE803
#define FM_IDW_BACK_MENU_BAR 0xE804
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 217
#define _APS_NEXT_COMMAND_VALUE 32780
#define _APS_NEXT_CONTROL_VALUE 1003
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/FingerSuite/FingerNotification/NotifListWindow.h
// WTLApp1View.h : interface of the CWTLApp1View class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include <Connmgr_status.h>
//#include "snapi.h"
#ifndef __FNGRSCRL_H__
#error menu.h requires fngrscrl.h to be included first
#endif
#define UM_SELECTNOTIF WM_USER + 98
#define UM_STATENOTIF WM_USER + 99
#define UM_MINIMIZE WM_USER + 100
#define UM_ACTIVATEMINIMIZETIMER WM_USER + 101
#define UM_STOPMINIMIZETIMER WM_USER + 102
#define IDT_AUTOMINIMIZE 100001
// Which values to refresh
//#define TB_BLUETOOTH_MASK 0x10
//#define TB_TIME_MASK 0x04
//#define TB_CONNECTIONS_MASK 0x40
#define TB_BATTERY_MASK 0x08
#define TB_VOLUME_MASK 0x20
#define TB_SIGNAL_MASK 0x01
#define TB_OPERATOR_MASK 0x02
#define TB_PHONE_STATUS_MASK 0x80
#define TB_CELLSYSTEMCONNECTED_MASK 0x0100
#define TB_PHONEACTIVECALLCOUNT_MASK 0x0200
#define SN_RINGMODE_ROOT HKEY_CURRENT_USER
#define SN_RINGMODE_PATH TEXT("ControlPanel\\Notifications\\ShellOverrides")
#define SN_RINGMODE_VALUE TEXT("Mode")
#define SN_RINGMODE_SOUND 0
#define SN_RINGMODE_VIBRATE 1
#define SN_RINGMODE_MUTE 2
#define BTN_ICON_SIZE 16
#define IDC_BTN_VOLUME 10001
#define IDC_BTN_BATTERY 10002
#define IDC_BTN_CELLULAR 10003
class CListWindow : public CWindowImpl<CListWindow>, public CFingerScrollImpl<CListWindow, true, false>
{
public:
DECLARE_WND_CLASS(NULL)
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
CListWindow()
{
}
void DoPaint(CDCHandle dc)
{
int cx = 32 * m_scaleFactor;
int cy = 32 * m_scaleFactor;
RECT rc; GetClientRect(&rc);
// background
dc.FillSolidRect(&rc, m_clBkg);
CFont oldFont = dc.SelectFont(m_fText);
if (g_pNotifications.GetSize() == 0)
{
RECT rcText; CopyRect(&rcText, &rc);
// draw text
rcText.top = rcText.top + 5 * m_scaleFactor;
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(m_clText);
dc.DrawText( LoadResourceString(IDS_NO_NEW_NOTIFICATIONS), -1, &rcText, DT_CENTER | DT_TOP | DT_SINGLELINE | DT_END_ELLIPSIS);
}
for (int i = 0; i < g_pNotifications.GetSize(); i++)
{
RECT rcItem = {0, i * m_itemHeight, rc.right, (i + 1) * m_itemHeight};
LPNOTIFICATIONINFO pInfo = g_pNotifications[i];
// background
//dc.FillSolidRect(&rcItem, m_clBkg);
if (i == m_idxSelected)
{
m_imgSelection.Draw(dc, rcItem);
}
// draw icon
RECT rcImg = {0, rcItem.top + (m_itemHeight - cy)/2, cx, rcItem.bottom - (m_itemHeight - cy)/2};
OffsetRect(&rcImg, 2 * m_scaleFactor, 0);
//m_imgIconBkg.Draw(dc, rcImg);
InflateRect(&rcImg, -2 * m_scaleFactor, -2 * m_scaleFactor);
CIconHandle icon = pInfo->nd.hicon;
icon.DrawIconEx(dc, rcImg.left, rcImg.top, (rcImg.right - rcImg.left), (rcImg.bottom - rcImg.top));
// draw text
RECT rcText; CopyRect(&rcText, &rcItem);
rcText.left = cx + 16 * m_scaleFactor;
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(m_clText);
dc.DrawText(pInfo->nd.pszTitle, -1, &rcText, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
// dotted line 1px
CPen pen2; pen2.CreatePen(PS_DASH, 1, m_clLine);
CPen penOld2 = dc.SelectPen(pen2);
dc.MoveTo(rcItem.left, rcItem.bottom - 1);
dc.LineTo(rcItem.right, rcItem.bottom - 1);
dc.SelectPen(penOld2);
}
dc.SelectFont(oldFont);
}
void DoScroll(int yOffset)
{
//LOG(L"offset = %d\n", -yOffset);
//ScrollWindowEx(0, -yOffset, SW_SCROLLCHILDREN | SW_INVALIDATE);
//m_btnBattery.MoveUpDownWindow(yOffset);
}
void AddIcon(CString key, CString path)
{
CxImage img;
img.Load(path, CXIMAGE_FORMAT_PNG);
m_icons.Add(key, img);
}
typedef CFingerScrollImpl<CListWindow, true, false> scrollbaseClass;
BEGIN_MSG_MAP(CListWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
//MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBackground)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
CHAIN_MSG_MAP(scrollbaseClass)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
m_itemHeight = m_imgSelection.GetHeight();
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
RECT rc; GetClientRect(&rc);
SetFingerScrollRegion(g_pNotifications.GetSize() * m_itemHeight, rc.bottom);
}
return 0;
}
LRESULT OnEraseBackground(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnLButtonDown(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
// gesture recognize
SHRGINFO shrg;
shrg.cbSize = sizeof(shrg);
shrg.hwndClient = GetParent().GetParent();
shrg.ptDown.x = LOWORD(lParam);
shrg.ptDown.y = GetOffset() + HIWORD(lParam);
shrg.dwFlags = SHRG_RETURNCMD;
if (SHRecognizeGesture(&shrg) == GN_CONTEXTMENU)
{
GetParent().SendMessage(UM_STOPMINIMIZETIMER);
HMENU hMenu = ::AtlLoadMenu(IDR_MAINFRAME);
HMENU hSubMenu = GetSubMenu(hMenu, 0);
BOOL bRes = TrackPopupMenuEx(hSubMenu, TPM_LEFTALIGN, LOWORD(lParam), GetOffset() + HIWORD(lParam), GetParent().GetParent(), NULL);
GetParent().SendMessage(UM_ACTIVATEMINIMIZETIMER);
return 0;
//GetParent().GetParent().PostMessage(UM_MINIMIZE);
}
m_xPos = LOWORD(lParam);
m_yPos = HIWORD(lParam);
m_bMouseIsDown = TRUE;
m_idxSelected = (GetOffset() + m_yPos) / m_itemHeight;
m_idxDPadSelected = -1;
if ((m_idxSelected >= 0) && (m_idxSelected < g_pNotifications.GetSize()))
{
InvalidateRect(NULL, FALSE);
UpdateWindow();
}
else
m_idxSelected = -1;
bHandled = FALSE; // very important
return 0;
}
LRESULT OnMouseMove(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
int y = HIWORD(lParam);
if (abs(y - m_yPos) > GetThreshold())
{
if (m_idxSelected != -1)
{
m_idxSelected = -1;
InvalidateRect(NULL, FALSE);
UpdateWindow();
}
}
m_yPos = HIWORD(lParam);
GetParent().PostMessage(UM_ACTIVATEMINIMIZETIMER);
bHandled = FALSE; // very important
return 0;
}
LRESULT OnLButtonUp(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
m_bMouseIsDown = FALSE;
// normal mode
if (m_idxSelected != -1)
{
GetParent().GetParent().SendMessage(UM_SELECTNOTIF, (WPARAM)m_idxSelected, 0);
}
bHandled = FALSE; // very important
return 0;
}
private:
int m_xPos;
int m_yPos;
int m_idxSelected;
int m_idxDPadSelected;
BOOL m_bMouseIsDown;
CSimpleMap<CString, CxImage> m_icons;
public:
int m_itemHeight;
CxImage m_imgSelection;
CFontHandle m_fText;
int m_scaleFactor;
COLORREF m_clText;
COLORREF m_clLine;
COLORREF m_clBkg;
};
class CNotifListWindow : public CWindowImpl<CNotifListWindow>, public COffscreenDraw<CNotifListWindow>
{
public:
DECLARE_WND_CLASS(NULL)
CListWindow m_notiflist;
BOOL PreTranslateMessage(MSG* pMsg)
{
pMsg;
return FALSE;
}
CNotifListWindow()
{
}
void Show()
{
//m_notiflist.m_idxSelected = -1;
RECT rc; GetParent().GetClientRect(&rc);
MoveWindow(&rc, TRUE);
ActivateMinimizeTimer();
}
void DoPaint(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
SIZE imgSize;
imgSize.cx = m_imgIconBkg.GetWidth();
imgSize.cy = m_imgIconBkg.GetHeight();
RECT rcHHTaskTar; ::GetClientRect(::FindWindow(L"HHTaskBar", NULL), &rcHHTaskTar);
int hTaskBar = rcHHTaskTar.bottom - rcHHTaskTar.top;
// HEADER
RECT rcHeader;
int h = m_arrStaticImages[0].GetHeight();
int w = m_arrStaticImages[0].GetWidth();
CPen pen; pen.CreatePen(PS_SOLID, 1, m_clLine);
CPen oldPen = dc.SelectPen(pen);
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(m_clText);
// title
CFont oldFont = dc.SelectFont(m_fTitleText);
dc.DrawText( LoadResourceString(IDR_MAINFRAME), -1, &rcHHTaskTar, DT_CENTER | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
dc.SelectFont(oldFont);
// volume
SetRect(&rcHeader, 0, hTaskBar, rc.right, hTaskBar + h);
dc.FillSolidRect(&rcHeader, m_clBkgHeader);
dc.MoveTo(rcHeader.left, rcHeader.bottom );
dc.LineTo(rcHeader.right, rcHeader.bottom );
rcHeader.left += 10 * m_scaleFactor;
oldFont = dc.SelectFont(m_fHeaderText);
dc.DrawText(LoadResourceString(IDS_VOLUME), -1, &rcHeader, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
// battery
SetRect(&rcHeader, 0, hTaskBar + h + 1, rc.right, hTaskBar + h + 1 + h);
dc.FillSolidRect(&rcHeader, m_clBkgHeader);
dc.MoveTo(rcHeader.left, rcHeader.bottom );
dc.LineTo(rcHeader.right, rcHeader.bottom );
//InflateRect(&rcHeader, -10 * m_scaleFactor, 0);
rcHeader.left += 10 * m_scaleFactor;
dc.DrawText(LoadResourceString(IDS_BATTERY), -1, &rcHeader, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
rcHeader.right -= (w + 5 * m_scaleFactor);
WCHAR text[50];
wsprintf(text, L"%d%%", m_nBatteryPercent);
if (m_nBatteryPercent != BATTERY_PERCENTAGE_UNKNOWN)
dc.DrawText(text, -1, &rcHeader, DT_RIGHT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
// cellular
SetRect(&rcHeader, 0, hTaskBar + h + 1 + h + 1 + 1, rc.right, hTaskBar + h + 1 + h + 1 + h);
dc.FillSolidRect(&rcHeader, m_clBkgHeader);
dc.MoveTo(rcHeader.left, rcHeader.bottom );
dc.LineTo(rcHeader.right, rcHeader.bottom );
rcHeader.left += 10 * m_scaleFactor;
dc.DrawText(m_szCarrier, -1, &rcHeader, DT_LEFT | DT_VCENTER | DT_SINGLELINE | DT_END_ELLIPSIS);
dc.SelectPen(oldPen);
dc.SelectFont(oldFont);
}
typedef CWindowImpl<CNotifListWindow> winbaseClass;
typedef COffscreenDraw<CNotifListWindow> offscreenbaseClass;
BEGIN_MSG_MAP(CNotifListWindow)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(UM_STATENOTIF, OnStateNotif)
MESSAGE_HANDLER(UM_ACTIVATEMINIMIZETIMER, OnActivateMinimizeTimer)
MESSAGE_HANDLER(UM_STOPMINIMIZETIMER, OnStopMinimizeTimer)
CHAIN_MSG_MAP(offscreenbaseClass)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
m_notiflist.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
m_btnVolume.Create(m_hWnd, FNGRBTN_TYPE_STATIC | FNGRBTN_TYPE_ICON, TRUE, m_clBkgHeader, BTN_ICON_SIZE * m_scaleFactor, IDC_BTN_VOLUME);
m_btnBattery.Create(m_hWnd, FNGRBTN_TYPE_STATIC | FNGRBTN_TYPE_ICON, TRUE, m_clBkgHeader, BTN_ICON_SIZE * m_scaleFactor, IDC_BTN_BATTERY);
m_btnCellular.Create(m_hWnd, FNGRBTN_TYPE_STATIC | FNGRBTN_TYPE_ICON, TRUE, m_clBkgHeader, BTN_ICON_SIZE * m_scaleFactor, IDC_BTN_CELLULAR);
m_btnVolume.SetArrayImageSet(m_arrStaticImages);
m_btnBattery.SetArrayImageSet(m_arrStaticImages);
m_btnCellular.SetArrayImageSet(m_arrStaticImages);
// notifications
// Speaker / Volume
HRESULT hr = ::RegistryNotifyWindow( SN_RINGMODE_ROOT,
SN_RINGMODE_PATH,
SN_RINGMODE_VALUE,
m_hWnd, UM_STATENOTIF, TB_VOLUME_MASK,
NULL, &m_hVolume);
// Battery
hr = ::RegistryNotifyWindow(
SN_POWERBATTERYSTRENGTH_ROOT,
SN_POWERBATTERYSTRENGTH_PATH,
SN_POWERBATTERYSTRENGTH_VALUE,
m_hWnd, UM_STATENOTIF, TB_BATTERY_MASK,
NULL, &m_hBattery);
// phone status
hr = ::RegistryNotifyWindow(
SN_PHONERADIOOFF_ROOT,
SN_PHONERADIOOFF_PATH,
SN_PHONERADIOOFF_VALUE,
m_hWnd, UM_STATENOTIF, TB_PHONE_STATUS_MASK,
NULL, &m_hPhoneStatus);
// signal strengh
hr = ::RegistryNotifyWindow(
SN_PHONESIGNALSTRENGTH_ROOT,
SN_PHONESIGNALSTRENGTH_PATH,
SN_PHONESIGNALSTRENGTH_VALUE,
m_hWnd, UM_STATENOTIF, TB_SIGNAL_MASK,
NULL, &m_hSignal);
// operator name
hr = ::RegistryNotifyWindow(
SN_PHONEOPERATORNAME_ROOT,
SN_PHONEOPERATORNAME_PATH,
SN_PHONEOPERATORNAME_VALUE,
m_hWnd, UM_STATENOTIF, TB_OPERATOR_MASK,
NULL, &m_hOperator);
// cell system
hr = ::RegistryNotifyWindow(
SN_CELLSYSTEMCONNECTED_ROOT,
SN_CELLSYSTEMCONNECTED_PATH,
SN_CELLSYSTEMCONNECTED_VALUE,
m_hWnd, UM_STATENOTIF, TB_CELLSYSTEMCONNECTED_MASK,
NULL, &m_hCellSystem);
// active phone call
hr = ::RegistryNotifyWindow(
SN_PHONEACTIVECALLCOUNT_ROOT,
SN_PHONEACTIVECALLCOUNT_PATH,
SN_PHONEACTIVECALLCOUNT_VALUE,
m_hWnd, UM_STATENOTIF, TB_PHONEACTIVECALLCOUNT_MASK,
NULL, &m_hActivePhoneCall);
BOOL dummy;
OnStateNotif(0, 0, 0xFFFF, dummy);
return 0;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if (m_hVolume != NULL)
RegistryCloseNotification(m_hVolume);
if (m_hBattery != NULL)
RegistryCloseNotification(m_hBattery);
return 0;
}
LRESULT OnStateNotif(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& /*bHandled*/)
{
DWORD dwWhich = (UINT)lParam;
if (
(dwWhich & TB_SIGNAL_MASK)
|| (dwWhich & TB_OPERATOR_MASK)
|| (dwWhich & TB_PHONE_STATUS_MASK)
|| (dwWhich & TB_CELLSYSTEMCONNECTED_MASK)
|| (dwWhich & TB_PHONEACTIVECALLCOUNT_MASK)
)
dwWhich |= TB_SIGNAL_MASK | TB_OPERATOR_MASK | TB_PHONE_STATUS_MASK | TB_CELLSYSTEMCONNECTED_MASK | TB_PHONEACTIVECALLCOUNT_MASK;
RefreshStatus(dwWhich);
if (m_bSpeakerOn)
m_btnVolume.SetIcon( AtlLoadIcon(IDI_VOLUME_ON) );
else if (m_bVibrate)
m_btnVolume.SetIcon( AtlLoadIcon(IDI_VOLUME_VIBRATE) );
else
m_btnVolume.SetIcon( AtlLoadIcon(IDI_VOLUME_OFF) );
if (m_bCharging)
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_CHARGING) );
else if (m_bNoBattery)
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_ABSENT) );
else if (m_bBatteryCritical)
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_CRITICAL) );
else
{
if (m_nBatteryPercent != BATTERY_PERCENTAGE_UNKNOWN)
{
if ((m_nBatteryPercent >= 0) && (m_nBatteryPercent <= 20))
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_1) );
if ((m_nBatteryPercent >= 21) && (m_nBatteryPercent <= 40))
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_2) );
if ((m_nBatteryPercent >= 41) && (m_nBatteryPercent <= 60))
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_3) );
if ((m_nBatteryPercent >= 61) && (m_nBatteryPercent <= 80))
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_4) );
if ((m_nBatteryPercent >= 81) && (m_nBatteryPercent <= 100))
m_btnBattery.SetIcon( AtlLoadIcon(IDI_BATTERY_5) );
}
}
// phone
if (m_bPhoneOff)
{
wsprintf(m_szCarrier, L"No service");
m_btnCellular.SetIcon( AtlLoadIcon(IDI_PHONE) );
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_OFF) );
}
else
{
if (m_bActiveDataCall)
{
if (m_dwConnectionType & SN_CELLSYSTEMCONNECTED_GPRS_BITMASK)
m_btnCellular.SetIcon( AtlLoadIcon(IDI_CONN_G) );
if (m_dwConnectionType & SN_CELLSYSTEMCONNECTED_EDGE_BITMASK)
m_btnCellular.SetIcon( AtlLoadIcon(IDI_CONN_E) );
if (m_dwConnectionType & SN_CELLSYSTEMCONNECTED_UMTS_BITMASK)
m_btnCellular.SetIcon( AtlLoadIcon(IDI_CONN_3G) );
if (m_dwConnectionType & SN_CELLSYSTEMCONNECTED_HSDPA_BITMASK)
m_btnCellular.SetIcon( AtlLoadIcon(IDI_CONN_H) );
}
else if (m_bActiveCall)
m_btnCellular.SetIcon( AtlLoadIcon(IDI_INCALL) );
else
m_btnCellular.SetIcon( AtlLoadIcon(IDI_PHONE) );
}
if (m_bNoService)
{
if (!(m_bPhoneOff))
{
wsprintf(m_szCarrier, L"No service");
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_NO_SERVICE) );
}
}
else if (m_bSearchingForService)
{
wsprintf(m_szCarrier, L"Searching");
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_SEARCHING) );
}
else
{
m_nBars -= 1;
if (m_nBars == 0)
m_btnCellular.SetIcon2( NULL );
if (m_nBars == 1)
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_SIGNAL_1) );
if (m_nBars == 2)
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_SIGNAL_2) );
if (m_nBars == 3)
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_SIGNAL_3) );
if (m_nBars == 4)
m_btnCellular.SetIcon2( AtlLoadIcon(IDI_SIGNAL_4) );
}
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
RECT rc; GetClientRect(&rc);
// move buttons
RECT rcHHTaskTar; ::GetClientRect(::FindWindow(L"HHTaskBar", NULL), &rcHHTaskTar);
int hTaskBar = rcHHTaskTar.bottom - rcHHTaskTar.top;
int h = m_arrStaticImages[0].GetHeight();
int w = m_arrStaticImages[0].GetWidth();
RECT rcBtn;
SetRect(&rcBtn, rc.right - w, hTaskBar, rc.right, hTaskBar + h);
m_btnVolume.MoveWindow(&rcBtn);
SetRect(&rcBtn, rc.right - w, hTaskBar + h + 1, rc.right, hTaskBar + h + 1 + h);
m_btnBattery.MoveWindow(&rcBtn);
SetRect(&rcBtn, rc.right - w, hTaskBar + h + 1 + h + 1 + 1, rc.right, hTaskBar + h + 1 + h + 1 + h);
m_btnCellular.MoveWindow(&rcBtn);
int headOffset = hTaskBar + 3 * (h + 1);
RECT rcNotifyList = {0, headOffset, rc.right, rc.bottom};
m_notiflist.MoveWindow(&rcNotifyList);
}
bHandled = FALSE;
return 0;
}
LRESULT OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
if ((wParam == IDT_AUTOMINIMIZE) && (IsWindowVisible()))
{
StopMinimizeTimer();
GetParent().PostMessage(UM_MINIMIZE);
}
return 0;
}
LRESULT OnActivateMinimizeTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
ActivateMinimizeTimer();
return 0;
}
LRESULT OnStopMinimizeTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
StopMinimizeTimer();
return 0;
}
public:
CxImage m_imgIconBkg;
CFontHandle m_fHeaderText;
CFontHandle m_fTitleText;
COLORREF m_clText;
COLORREF m_clLine;
COLORREF m_clBkgHeader;
int m_scaleFactor;
DWORD m_tmrMinimize;
CxImage m_arrStaticImages[9];
void SetScaleFactor(int value)
{
m_scaleFactor = value;
m_notiflist.m_scaleFactor = value;
}
void ActivateMinimizeTimer()
{
KillTimer(IDT_AUTOMINIMIZE);
SetTimer(IDT_AUTOMINIMIZE, m_tmrMinimize);
}
void StopMinimizeTimer()
{
KillTimer(IDT_AUTOMINIMIZE);
}
private:
// notifications
HREGNOTIFY m_hVolume;
HREGNOTIFY m_hBattery;
HREGNOTIFY m_hPhoneStatus;
HREGNOTIFY m_hSignal;
HREGNOTIFY m_hOperator;
HREGNOTIFY m_hCellSystem;
HREGNOTIFY m_hActivePhoneCall;
BYTE m_nBatteryPercent;
BOOL m_bSpeakerOn;
BOOL m_bVibrate;
BOOL m_bCharging;
BOOL m_bNoBattery;
BOOL m_bBatteryCritical;
BOOL m_bPhoneOff;
BOOL m_bActiveDataCall;
BOOL m_bActiveCall;
BOOL m_bNoService;
BOOL m_bSearchingForService;
WCHAR m_szCarrier[50];
DWORD m_dwConnectionType;
int m_nBars; //0-5
CFingerButton m_btnVolume;
CFingerButton m_btnBattery;
CFingerButton m_btnCellular;
void RefreshStatus(DWORD dwWhich)
{
DWORD dw;
HRESULT hr;
// Speaker / volume
if (dwWhich & TB_VOLUME_MASK) {
hr = RegistryGetDWORD(
SN_RINGMODE_ROOT,
SN_RINGMODE_PATH,
SN_RINGMODE_VALUE,
&dw);
if (SUCCEEDED(hr)) {
m_bSpeakerOn = dw == SN_RINGMODE_SOUND;
m_bVibrate = dw == SN_RINGMODE_VIBRATE;
}
}
// Battery level & charging state
if (dwWhich & TB_BATTERY_MASK) {
SYSTEM_POWER_STATUS_EX2 sps = {0};
DWORD result = ::GetSystemPowerStatusEx2(&sps,
sizeof(SYSTEM_POWER_STATUS_EX2), false);
if (result > 0)
{
m_bCharging = (sps.BatteryFlag & BATTERY_FLAG_CHARGING) > 0;
m_bNoBattery = (sps.BatteryFlag & BATTERY_FLAG_NO_BATTERY) > 0;
m_bBatteryCritical = (sps.BatteryFlag & BATTERY_FLAG_CRITICAL) > 0;
m_nBatteryPercent = sps.BatteryLifePercent;
}
}
// Operator name
if (dwWhich & TB_OPERATOR_MASK) {
hr = RegistryGetString(
SN_PHONEOPERATORNAME_ROOT,
SN_PHONEOPERATORNAME_PATH,
SN_PHONEOPERATORNAME_VALUE,
m_szCarrier, sizeof(m_szCarrier));
}
// Signal Strength
if (dwWhich & TB_SIGNAL_MASK) {
hr = RegistryGetDWORD(
SN_PHONESIGNALSTRENGTH_ROOT,
SN_PHONESIGNALSTRENGTH_PATH,
SN_PHONESIGNALSTRENGTH_VALUE,
&dw);
if (SUCCEEDED(hr))
m_nBars = (int)((double)dw / 20.0);
}
// connection type
if (dwWhich & TB_CELLSYSTEMCONNECTED_MASK) {
hr = RegistryGetDWORD(
SN_CELLSYSTEMCONNECTED_ROOT,
SN_CELLSYSTEMCONNECTED_PATH,
SN_CELLSYSTEMCONNECTED_VALUE,
&dw);
if (SUCCEEDED(hr))
m_dwConnectionType = dw;
}
// phone status
if (dwWhich & TB_PHONE_STATUS_MASK) {
hr = RegistryGetDWORD(
SN_PHONERADIOOFF_ROOT,
SN_PHONERADIOOFF_PATH,
SN_PHONERADIOOFF_VALUE,
&dw);
if (SUCCEEDED(hr))
{
m_bPhoneOff = (dw & SN_PHONERADIOOFF_BITMASK) > 0;
m_bActiveDataCall = (dw & SN_PHONEACTIVEDATACALL_BITMASK) > 0;
m_bSearchingForService = (dw & SN_PHONESEARCHINGFORSERVICE_BITMASK) > 0;
m_bNoService = (dw & SN_PHONENOSERVICE_BITMASK) > 0;
}
}
// active call
if (dwWhich & TB_PHONEACTIVECALLCOUNT_MASK) {
hr = RegistryGetDWORD(
SN_PHONEACTIVECALLCOUNT_ROOT,
SN_PHONEACTIVECALLCOUNT_PATH,
SN_PHONEACTIVECALLCOUNT_VALUE,
&dw);
if (SUCCEEDED(hr))
m_bActiveCall = dw > 0;
else
m_bActiveCall = FALSE;
}
CONNMGR_CONNECTION_DETAILED_STATUS *pConnMgrDet = NULL;
HRESULT hResult;
DWORD dwBufferSize=0; //Code Snippet
hResult = ConnMgrQueryDetailedStatus(pConnMgrDet, &dwBufferSize);
if (hResult == (HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)))
{
pConnMgrDet = (CONNMGR_CONNECTION_DETAILED_STATUS*)malloc(dwBufferSize);
hResult = ConnMgrQueryDetailedStatus(pConnMgrDet, &dwBufferSize);
}
CONNMGR_CONNECTION_DETAILED_STATUS *pCurrent = pConnMgrDet;
if (hResult == S_OK)
{
while (pCurrent != NULL)
{
//Do what you want eg. if you want to check cellular network
if (pCurrent->dwType == CM_CONNTYPE_CELLULAR)
{
//Do some thing
}
pCurrent = pCurrent->pNext;
}
}
free(pConnMgrDet);
}
};<file_sep>/FingerSuite/Common/fngrbufdc.h
#ifndef __FNGRBUFDC_H__
#define __FNGRBUFDC_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error atlgdi.h requires atlapp.h to be included first
#endif
#ifndef __ATLGDI_H__
#error fngrbufdc.h requires atlgdi.h to be included first
#endif
///////////////////////////////////////////////////////////////////////////////
// Classes in this file:
//
// CBufferedPaintDC
class CBufferedPaintDC : public CDC
{
public:
HWND m_hWnd;
PAINTSTRUCT m_ps;
// Data members
HDC m_hPaintDC;
RECT m_rcClient;
CBitmap m_bmp;
HBITMAP m_hBmpOld;
int m_offset;
// Constructor/destructor
CBufferedPaintDC(HWND hWnd, int offset)
{
ATLASSERT(::IsWindow(hWnd));
m_hWnd = hWnd;
m_offset = offset;
m_hPaintDC = ::BeginPaint(hWnd, &m_ps);
// buffer
::GetClientRect(m_hWnd, &m_rcClient);
m_hDC = ::CreateCompatibleDC(m_hPaintDC);
ATLASSERT(m_hDC != NULL);
m_bmp.CreateCompatibleBitmap(m_hPaintDC, m_rcClient.right - m_rcClient.left, m_rcClient.bottom - m_rcClient.top);
ATLASSERT(m_bmp.m_hBitmap != NULL);
m_hBmpOld = SelectBitmap(m_bmp);
}
~CBufferedPaintDC()
{
ATLASSERT(m_hDC != NULL);
ATLASSERT(::IsWindow(m_hWnd));
::BitBlt(m_hPaintDC, m_rcClient.left, m_rcClient.top, m_rcClient.right - m_rcClient.left, m_rcClient.bottom - m_rcClient.top, m_hDC, m_rcClient.left, m_rcClient.top - m_offset, SRCCOPY);
SelectBitmap(m_hBmpOld);
::EndPaint(m_hWnd, &m_ps);
m_hPaintDC = NULL; // detach paint dc
Detach();
}
};
#endif<file_sep>/7-Zip/CPP/7zip/Archive/ElfHandler.cpp
// ElfHandler.cpp
#include "StdAfx.h"
#include "../../../C/CpuArch.h"
#include "Common/Buffer.h"
#include "Common/ComTry.h"
#include "Common/IntToString.h"
#include "Windows/PropVariantUtils.h"
#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"
#include "../Compress/CopyCoder.h"
static UInt16 Get16(const Byte *p, int be) { if (be) return GetBe16(p); return GetUi16(p); }
static UInt32 Get32(const Byte *p, int be) { if (be) return GetBe32(p); return GetUi32(p); }
static UInt64 Get64(const Byte *p, int be) { if (be) return GetBe64(p); return GetUi64(p); }
using namespace NWindows;
namespace NArchive {
namespace NElf {
#define ELF_CLASS_32 1
#define ELF_CLASS_64 2
#define ELF_DATA_2LSB 1
#define ELF_DATA_2MSB 2
#define NUM_SCAN_SECTIONS_MAX (1 << 6)
struct CHeader
{
bool Mode64;
bool Be;
Byte Os;
Byte AbiVer;
UInt16 Type;
UInt16 Machine;
// UInt32 Version;
// UInt64 EntryVa;
UInt64 ProgOffset;
UInt64 SectOffset;
UInt32 Flags;
UInt16 ElfHeaderSize;
UInt16 SegmentEntrySize;
UInt16 NumSegments;
UInt16 SectEntrySize;
UInt16 NumSections;
// UInt16 SectNameStringTableIndex;
bool Parse(const Byte *buf);
bool CheckSegmentEntrySize() const
{
return (Mode64 && SegmentEntrySize == 0x38) || (!Mode64 && SegmentEntrySize == 0x20);
};
UInt64 GetHeadersSize() const
{ return ElfHeaderSize +
(UInt64)SegmentEntrySize * NumSegments +
(UInt64)SectEntrySize * NumSections; }
};
bool CHeader::Parse(const Byte *p)
{
switch(p[4])
{
case ELF_CLASS_32: Mode64 = false; break;
case ELF_CLASS_64: Mode64 = true; break;
default: return false;
}
bool be;
switch(p[5])
{
case ELF_DATA_2LSB: be = false; break;
case ELF_DATA_2MSB: be = true; break;
default: return false;
}
Be = be;
if (p[6] != 1) // Version
return false;
Os = p[7];
AbiVer = p[8];
for (int i = 9; i < 16; i++)
if (p[i] != 0)
return false;
Type = Get16(p + 0x10, be);
Machine = Get16(p + 0x12, be);
if (Get32(p + 0x14, be) != 1) // Version
return false;
if (Mode64)
{
// EntryVa = Get64(p + 0x18, be);
ProgOffset = Get64(p + 0x20, be);
SectOffset = Get64(p + 0x28, be);
p += 0x30;
}
else
{
// EntryVa = Get32(p + 0x18, be);
ProgOffset = Get32(p + 0x1C, be);
SectOffset = Get32(p + 0x20, be);
p += 0x24;
}
Flags = Get32(p + 0, be);
ElfHeaderSize = Get16(p + 4, be);
SegmentEntrySize = Get16(p + 6, be);
NumSegments = Get16(p + 8, be);
SectEntrySize = Get16(p + 10, be);
NumSections = Get16(p + 12, be);
// SectNameStringTableIndex = Get16(p + 14, be);
return CheckSegmentEntrySize();
}
struct CSegment
{
UInt32 Type;
UInt32 Flags;
UInt64 Offset;
UInt64 Va;
// UInt64 Pa;
UInt64 PSize;
UInt64 VSize;
// UInt64 Align;
void UpdateTotalSize(UInt64 &totalSize)
{
UInt64 t = Offset + PSize;
if (t > totalSize)
totalSize = t;
}
void Parse(const Byte *p, bool mode64, bool be);
};
void CSegment::Parse(const Byte *p, bool mode64, bool be)
{
Type = Get32(p, be);
if (mode64)
{
Flags = Get32(p + 4, be);
Offset = Get64(p + 8, be);
Va = Get64(p + 0x10, be);
// Pa = Get64(p + 0x18, be);
PSize = Get64(p + 0x20, be);
VSize = Get64(p + 0x28, be);
// Align = Get64(p + 0x30, be);
}
else
{
Offset = Get32(p + 4, be);
Va = Get32(p + 8, be);
// Pa = Get32(p + 12, be);
PSize = Get32(p + 16, be);
VSize = Get32(p + 20, be);
Flags = Get32(p + 24, be);
// Align = Get32(p + 28, be);
}
}
static const CUInt32PCharPair g_MachinePairs[] =
{
{ 0, "None" },
{ 1, "AT&T WE 32100" },
{ 2, "SPARC" },
{ 3, "Intel 386" },
{ 4, "Motorola 68000" },
{ 5, "Motorola 88000" },
{ 6, "Intel 486" },
{ 7, "Intel i860" },
{ 8, "MIPS" },
{ 9, "IBM S/370" },
{ 10, "MIPS RS3000 LE" },
{ 11, "RS6000" },
{ 15, "PA-RISC" },
{ 16, "nCUBE" },
{ 17, "Fujitsu VPP500" },
{ 18, "SPARC 32+" },
{ 19, "Intel i960" },
{ 20, "PowerPC" },
{ 21, "PowerPC 64-bit" },
{ 22, "IBM S/390" },
{ 36, "NEX v800" },
{ 37, "Fujitsu FR20" },
{ 38, "TRW RH-32" },
{ 39, "Motorola RCE" },
{ 40, "ARM" },
{ 41, "Alpha" },
{ 42, "<NAME>" },
{ 43, "SPARC-V9" },
{ 44, "<NAME>" },
{ 45, "ARC" },
{ 46, "H8/300" },
{ 47, "H8/300H" },
{ 48, "H8S" },
{ 49, "H8/500" },
{ 50, "IA-64" },
{ 51, "Stanford MIPS-X" },
{ 52, "<NAME>" },
{ 53, "M68HC12" },
{ 54, "Fujitsu MMA" },
{ 55, "Siemens PCP" },
{ 56, "Sony nCPU" },
{ 57, "Denso NDR1" },
{ 58, "Motorola StarCore" },
{ 59, "Toyota ME16" },
{ 60, "ST100" },
{ 61, "Advanced Logic TinyJ" },
{ 62, "AMD64" },
{ 63, "Sony DSP" },
{ 66, "Siemens FX66" },
{ 67, "ST9+" },
{ 68, "ST7" },
{ 69, "MC68HC16" },
{ 70, "MC68HC11" },
{ 71, "MC68HC08" },
{ 72, "MC68HC05" },
{ 73, "Silicon Graphics SVx" },
{ 74, "ST19" },
{ 75, "Digital VAX" },
{ 76, "Axis CRIS" },
{ 77, "Infineon JAVELIN" },
{ 78, "Element 14 FirePath" },
{ 79, "LSI ZSP" },
{ 80, "MMIX" },
{ 81, "HUANY" },
{ 82, "SiTera Prism" },
{ 83, "Atmel AVR" },
{ 84, "Fujitsu FR30" },
{ 85, "Mitsubishi D10V" },
{ 86, "Mitsubishi D30V" },
{ 87, "NEC v850" },
{ 88, "Mitsubishi M32R" },
{ 89, "Matsushita MN10300" },
{ 90, "Matsushita MN10200" },
{ 91, "picoJava" },
{ 92, "OpenRISC" },
{ 93, "ARC Tangent-A5" },
{ 94, "Tensilica Xtensa" },
{ 0x9026, "Alpha" }
};
static const CUInt32PCharPair g_AbiOS[] =
{
{ 0, "None" },
{ 1, "HP-UX" },
{ 2, "NetBSD" },
{ 3, "Linux" },
{ 6, "Solaris" },
{ 7, "AIX" },
{ 8, "IRIX" },
{ 9, "FreeBSD" },
{ 10, "TRU64" },
{ 11, "Novell Modesto" },
{ 12, "OpenBSD" },
{ 13, "OpenVMS" },
{ 14, "HP NSK" },
{ 15, "AROS" },
{ 97, "ARM" },
{ 255, "Standalone" }
};
static const CUInt32PCharPair g_SegmentFlags[] =
{
{ 1 << 0, "Execute" },
{ 1 << 1, "Write" },
{ 1 << 2, "Read" }
};
static const char *g_Types[] =
{
"None",
"Relocatable file",
"Executable file",
"Shared object file",
"Core file"
};
static const char *g_SegnmentTypes[] =
{
"Unused",
"Loadable segment",
"Dynamic linking tables",
"Program interpreter path name",
"Note section",
"SHLIB",
"Program header table",
"TLS"
};
class CHandler:
public IInArchive,
public CMyUnknownImp
{
CMyComPtr<IInStream> _inStream;
CObjectVector<CSegment> _sections;
UInt32 _peOffset;
CHeader _header;
UInt64 _totalSize;
HRESULT Open2(IInStream *stream);
bool Parse(const Byte *buf, UInt32 size);
public:
MY_UNKNOWN_IMP1(IInArchive)
INTERFACE_IInArchive(;)
};
#define ELF_PT_PHDR 6
bool CHandler::Parse(const Byte *buf, UInt32 size)
{
if (size < 64)
return false;
if (!_header.Parse(buf))
return false;
if (_header.ProgOffset > size ||
_header.ProgOffset + (UInt64)_header.SegmentEntrySize * _header.NumSegments > size ||
_header.NumSegments > NUM_SCAN_SECTIONS_MAX)
return false;
const Byte *p = buf + _header.ProgOffset;
_totalSize = _header.ProgOffset;
for (int i = 0; i < _header.NumSegments; i++, p += _header.SegmentEntrySize)
{
CSegment sect;
sect.Parse(p, _header.Mode64, _header.Be);
sect.UpdateTotalSize(_totalSize);
if (sect.Type != ELF_PT_PHDR)
_sections.Add(sect);
}
UInt64 total2 = _header.SectOffset + (UInt64)_header.SectEntrySize * _header.NumSections;
if (total2 > _totalSize)
_totalSize = total2;
return true;
}
STATPROPSTG kArcProps[] =
{
{ NULL, kpidCpu, VT_BSTR},
{ NULL, kpidBit64, VT_BOOL},
{ NULL, kpidBigEndian, VT_BOOL},
{ NULL, kpidHostOS, VT_BSTR},
{ NULL, kpidCharacts, VT_BSTR},
{ NULL, kpidPhySize, VT_UI8},
{ NULL, kpidHeadersSize, VT_UI8}
};
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidType, VT_BSTR},
{ NULL, kpidCharacts, VT_BSTR},
{ NULL, kpidOffset, VT_UI8},
{ NULL, kpidVa, VT_UI8}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
switch(propID)
{
case kpidPhySize: prop = _totalSize; break;
case kpidHeadersSize: prop = _header.GetHeadersSize(); break;
case kpidBit64: if (_header.Mode64) prop = _header.Mode64; break;
case kpidBigEndian: if (_header.Be) prop = _header.Be; break;
case kpidCpu: PAIR_TO_PROP(g_MachinePairs, _header.Machine, prop); break;
case kpidHostOS: PAIR_TO_PROP(g_AbiOS, _header.Os, prop); break;
case kpidCharacts: TYPE_TO_PROP(g_Types, _header.Type, prop); break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
const CSegment &item = _sections[index];
switch(propID)
{
case kpidPath:
{
wchar_t sz[32];
ConvertUInt64ToString(index, sz);
prop = sz;
break;
}
case kpidSize: prop = (UInt64)item.VSize; break;
case kpidPackSize: prop = (UInt64)item.PSize; break;
case kpidOffset: prop = item.Offset; break;
case kpidVa: prop = item.Va; break;
case kpidType: TYPE_TO_PROP(g_SegnmentTypes, item.Type, prop); break;
case kpidCharacts: FLAGS_TO_PROP(g_SegmentFlags, item.Flags, prop); break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
HRESULT CHandler::Open2(IInStream *stream)
{
const UInt32 kBufSize = 1 << 18;
const UInt32 kSigSize = 4;
CByteBuffer buffer;
buffer.SetCapacity(kBufSize);
Byte *buf = buffer;
size_t processed = kSigSize;
RINOK(ReadStream_FALSE(stream, buf, processed));
if (buf[0] != 0x7F || buf[1] != 'E' || buf[2] != 'L' || buf[3] != 'F')
return S_FALSE;
processed = kBufSize - kSigSize;
RINOK(ReadStream(stream, buf + kSigSize, &processed));
processed += kSigSize;
if (!Parse(buf, (UInt32)processed))
return S_FALSE;
UInt64 fileSize;
RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize));
return (fileSize == _totalSize) ? S_OK : S_FALSE;
}
STDMETHODIMP CHandler::Open(IInStream *inStream,
const UInt64 * /* maxCheckStartPosition */,
IArchiveOpenCallback * /* openArchiveCallback */)
{
COM_TRY_BEGIN
Close();
RINOK(Open2(inStream));
_inStream = inStream;
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_inStream.Release();
_sections.Clear();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _sections.Size();
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _sections.Size();
if (numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
totalSize += _sections[allFilesMode ? i : indices[i]].PSize;
extractCallback->SetTotal(totalSize);
UInt64 currentTotalSize = 0;
UInt64 currentItemSize;
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
streamSpec->SetStream(_inStream);
for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
{
lps->InSize = lps->OutSize = currentTotalSize;
RINOK(lps->SetCur());
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
UInt32 index = allFilesMode ? i : indices[i];
const CSegment &item = _sections[index];
currentItemSize = item.PSize;
CMyComPtr<ISequentialOutStream> outStream;
RINOK(extractCallback->GetStream(index, &outStream, askMode));
if (!testMode && !outStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(_inStream->Seek(item.Offset, STREAM_SEEK_SET, NULL));
streamSpec->Init(currentItemSize);
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
outStream.Release();
RINOK(extractCallback->SetOperationResult(copyCoderSpec->TotalSize == currentItemSize ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kDataError));
}
return S_OK;
COM_TRY_END
}
static IInArchive *CreateArc() { return new CHandler; }
static CArcInfo g_ArcInfo =
{ L"ELF", L"", 0, 0xDE, { 0 }, 0, false, CreateArc, 0 };
REGISTER_ARC(Elf)
}}
<file_sep>/FingerSuite/Common/atlcedlgs.h
#ifndef __ATLCEDLGS_H__
#define __ATLCEDLGS_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLDLGS_H__
#error atlcedlgs.h requires atldlgs.h to be included first
#endif
#ifndef _WIN32_WCE
#error atlcedlgs.h compiles under Windows CE only
#endif
/////////////////////////////////////////////////////////////////////////////
// Classes in this file
//
// CCePropertyPageImpl
// CCePropertySheet
//
template< class T, class TBase = CPropertySheetWindow >
class ATL_NO_VTABLE CCePropertySheetImpl : public CPropertySheetImpl< T, TBase >
{
public:
// Construction/Destruction
CCePropertySheetImpl(ATL::_U_STRINGorID caption = (LPCTSTR) NULL, UINT uStartPage = 0, HWND hWndParent = NULL)
{
::ZeroMemory(&m_psh, sizeof(PROPSHEETHEADER));
m_psh.dwSize = sizeof(PROPSHEETHEADER);
m_psh.dwFlags = PSH_USECALLBACK | PSH_MAXIMIZE;
#if (_ATL_VER >= 0x0700)
m_psh.hInstance = ATL::_AtlBaseModule.GetResourceInstance();
#else //!(_ATL_VER >= 0x0700)
m_psh.hInstance = _Module.GetResourceInstance();
#endif //!(_ATL_VER >= 0x0700)
m_psh.phpage = NULL; // will be set later
m_psh.nPages = 0; // will be set later
m_psh.pszCaption = caption.m_lpstr;
m_psh.nStartPage = uStartPage;
m_psh.hwndParent = hWndParent; // if NULL, will be set in DoModal/Create
m_psh.pfnCallback = T::PropSheetCallback;
}
static int CALLBACK PropSheetCallback(HWND hWnd, UINT uMsg, LPARAM lParam)
{
if( uMsg == PSCB_INITIALIZED )
{
ATLASSERT(hWnd != NULL);
#if (_ATL_VER >= 0x0700)
T* pT = (T*) ATL::_AtlWinModule.ExtractCreateWndData();
#else //!(_ATL_VER >= 0x0700)
T* pT = (T*) _Module.ExtractCreateWndData();
#endif //!(_ATL_VER >= 0x0700)
// Subclass the sheet window
pT->SubclassWindow(hWnd);
// Remove page handles array
pT->_CleanUpPages();
// Display empty menubar
SHMENUBARINFO cbi = { 0 };
cbi.cbSize = sizeof(SHMENUBARINFO);
cbi.hwndParent = hWnd;
cbi.dwFlags = SHCMBF_EMPTYBAR;
::SHCreateMenuBar( &cbi );
}
else if( uMsg == PSCB_GETVERSION )
{
return COMCTL32_VERSION;
}
else if( uMsg == PSCB_GETTITLE )
{
T::OnGetTitle((LPTSTR)lParam);
}
else if( uMsg = PSCB_GETLINKTEXT )
{
T::OnGetLinkText((LPTSTR)lParam);
}
return 0;
}
static void OnGetTitle(LPTSTR pstrTitle)
{
}
static void OnGetLinkText(LPTSTR pstrText)
{
}
};
// for non-customized sheets
class CCePropertySheet : public CCePropertySheetImpl<CCePropertySheet>
{
public:
CCePropertySheet(ATL::_U_STRINGorID caption = (LPCTSTR) NULL, UINT uStartPage = 0, HWND hWndParent = NULL)
: CCePropertySheetImpl<CCePropertySheet>(caption, uStartPage, hWndParent)
{
}
BEGIN_MSG_MAP(CCePropertySheet)
MESSAGE_HANDLER(WM_COMMAND, CCePropertySheetImpl<CCePropertySheet>::OnCommand)
END_MSG_MAP()
};
#endif // __ATLCEDLGS_H__
<file_sep>/7-Zip/CPP/7zip/Archive/Nsis/NsisHandler.h
// NSisHandler.h
#ifndef __NSIS_HANDLER_H
#define __NSIS_HANDLER_H
#include "Common/MyCom.h"
#include "../IArchive.h"
#include "NsisIn.h"
#include "../../Common/CreateCoder.h"
namespace NArchive {
namespace NNsis {
class CHandler:
public IInArchive,
PUBLIC_ISetCompressCodecsInfo
public CMyUnknownImp
{
CMyComPtr<IInStream> _inStream;
CInArchive _archive;
DECL_EXTERNAL_CODECS_VARS
bool GetUncompressedSize(int index, UInt32 &size);
bool GetCompressedSize(int index, UInt32 &size);
UString GetMethod(bool useItemFilter, UInt32 dictionary) const;
public:
MY_QUERYINTERFACE_BEGIN2(IInArchive)
QUERY_ENTRY_ISetCompressCodecsInfo
MY_QUERYINTERFACE_END
MY_ADDREF_RELEASE
INTERFACE_IInArchive(;)
DECL_ISetCompressCodecsInfo
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdSubAlloc.h
// PpmdSubAlloc.h
// 2009-05-30 : <NAME> : Public domain
// This code is based on <NAME>'s PPMdH code (public domain)
#ifndef __COMPRESS_PPMD_SUB_ALLOC_H
#define __COMPRESS_PPMD_SUB_ALLOC_H
#include "../../../C/Alloc.h"
#include "PpmdType.h"
const UINT N1=4, N2=4, N3=4, N4=(128+3-1*N1-2*N2-3*N3)/4;
const UINT UNIT_SIZE=12, N_INDEXES=N1+N2+N3+N4;
// Extra 1 * UNIT_SIZE for NULL support
// Extra 2 * UNIT_SIZE for s0 in GlueFreeBlocks()
const UInt32 kExtraSize = (UNIT_SIZE * 3);
const UInt32 kMaxMemBlockSize = 0xFFFFFFFF - kExtraSize;
struct MEM_BLK
{
UInt16 Stamp, NU;
UInt32 Next, Prev;
void InsertAt(Byte *Base, UInt32 p)
{
Prev = p;
MEM_BLK *pp = (MEM_BLK *)(Base + p);
Next = pp->Next;
pp->Next = ((MEM_BLK *)(Base + Next))->Prev = (UInt32)((Byte *)this - Base);
}
void Remove(Byte *Base)
{
((MEM_BLK *)(Base + Prev))->Next = Next;
((MEM_BLK *)(Base + Next))->Prev = Prev;
}
};
class CSubAllocator
{
UInt32 SubAllocatorSize;
Byte Indx2Units[N_INDEXES], Units2Indx[128], GlueCount;
UInt32 FreeList[N_INDEXES];
Byte *Base;
Byte *HeapStart, *LoUnit, *HiUnit;
public:
Byte *pText, *UnitsStart;
CSubAllocator():
SubAllocatorSize(0),
GlueCount(0),
LoUnit(0),
HiUnit(0),
pText(0),
UnitsStart(0)
{
memset(Indx2Units, 0, sizeof(Indx2Units));
memset(FreeList, 0, sizeof(FreeList));
}
~CSubAllocator()
{
StopSubAllocator();
};
void *GetPtr(UInt32 offset) const { return (offset == 0) ? 0 : (void *)(Base + offset); }
void *GetPtrNoCheck(UInt32 offset) const { return (void *)(Base + offset); }
UInt32 GetOffset(void *ptr) const { return (ptr == 0) ? 0 : (UInt32)((Byte *)ptr - Base); }
UInt32 GetOffsetNoCheck(void *ptr) const { return (UInt32)((Byte *)ptr - Base); }
MEM_BLK *GetBlk(UInt32 offset) const { return (MEM_BLK *)(Base + offset); }
UInt32 *GetNode(UInt32 offset) const { return (UInt32 *)(Base + offset); }
void InsertNode(void* p, int indx)
{
*(UInt32 *)p = FreeList[indx];
FreeList[indx] = GetOffsetNoCheck(p);
}
void* RemoveNode(int indx)
{
UInt32 offset = FreeList[indx];
UInt32 *p = GetNode(offset);
FreeList[indx] = *p;
return (void *)p;
}
UINT U2B(int NU) const { return (UINT)(NU) * UNIT_SIZE; }
void SplitBlock(void* pv, int oldIndx, int newIndx)
{
int i, UDiff = Indx2Units[oldIndx] - Indx2Units[newIndx];
Byte* p = ((Byte*)pv) + U2B(Indx2Units[newIndx]);
if (Indx2Units[i = Units2Indx[UDiff-1]] != UDiff)
{
InsertNode(p, --i);
p += U2B(i = Indx2Units[i]);
UDiff -= i;
}
InsertNode(p, Units2Indx[UDiff - 1]);
}
UInt32 GetUsedMemory() const
{
UInt32 RetVal = SubAllocatorSize - (UInt32)(HiUnit - LoUnit) - (UInt32)(UnitsStart - pText);
for (UInt32 i = 0; i < N_INDEXES; i++)
for (UInt32 pn = FreeList[i]; pn != 0; RetVal -= (UInt32)Indx2Units[i] * UNIT_SIZE)
pn = *GetNode(pn);
return (RetVal >> 2);
}
UInt32 GetSubAllocatorSize() const { return SubAllocatorSize; }
void StopSubAllocator()
{
if (SubAllocatorSize != 0)
{
BigFree(Base);
SubAllocatorSize = 0;
Base = 0;
}
}
bool StartSubAllocator(UInt32 size)
{
if (SubAllocatorSize == size)
return true;
StopSubAllocator();
if (size == 0)
Base = 0;
else
{
if ((Base = (Byte *)::BigAlloc(size + kExtraSize)) == 0)
return false;
HeapStart = Base + UNIT_SIZE; // we need such code to support NULL;
}
SubAllocatorSize = size;
return true;
}
void InitSubAllocator()
{
int i, k;
memset(FreeList, 0, sizeof(FreeList));
HiUnit = (pText = HeapStart) + SubAllocatorSize;
UINT Diff = UNIT_SIZE * (SubAllocatorSize / 8 / UNIT_SIZE * 7);
LoUnit = UnitsStart = HiUnit - Diff;
for (i = 0, k=1; i < N1 ; i++, k += 1) Indx2Units[i] = (Byte)k;
for (k++; i < N1 + N2 ;i++, k += 2) Indx2Units[i] = (Byte)k;
for (k++; i < N1 + N2 + N3 ;i++,k += 3) Indx2Units[i] = (Byte)k;
for (k++; i < N1 + N2 + N3 + N4; i++, k += 4) Indx2Units[i] = (Byte)k;
GlueCount = 0;
for (k = i = 0; k < 128; k++)
{
i += (Indx2Units[i] < k+1);
Units2Indx[k] = (Byte)i;
}
}
void GlueFreeBlocks()
{
UInt32 s0 = (UInt32)(HeapStart + SubAllocatorSize - Base);
// We need add exta MEM_BLK with Stamp=0
GetBlk(s0)->Stamp = 0;
s0 += UNIT_SIZE;
MEM_BLK *ps0 = GetBlk(s0);
UInt32 p;
int i;
if (LoUnit != HiUnit)
*LoUnit=0;
ps0->Next = ps0->Prev = s0;
for (i = 0; i < N_INDEXES; i++)
while (FreeList[i] != 0)
{
MEM_BLK *pp = (MEM_BLK *)RemoveNode(i);
pp->InsertAt(Base, s0);
pp->Stamp = 0xFFFF;
pp->NU = Indx2Units[i];
}
for (p = ps0->Next; p != s0; p = GetBlk(p)->Next)
{
for (;;)
{
MEM_BLK *pp = GetBlk(p);
MEM_BLK *pp1 = GetBlk(p + pp->NU * UNIT_SIZE);
if (pp1->Stamp != 0xFFFF || int(pp->NU) + pp1->NU >= 0x10000)
break;
pp1->Remove(Base);
pp->NU = (UInt16)(pp->NU + pp1->NU);
}
}
while ((p = ps0->Next) != s0)
{
MEM_BLK *pp = GetBlk(p);
pp->Remove(Base);
int sz;
for (sz = pp->NU; sz > 128; sz -= 128, p += 128 * UNIT_SIZE)
InsertNode(Base + p, N_INDEXES - 1);
if (Indx2Units[i = Units2Indx[sz-1]] != sz)
{
int k = sz - Indx2Units[--i];
InsertNode(Base + p + (sz - k) * UNIT_SIZE, k - 1);
}
InsertNode(Base + p, i);
}
}
void* AllocUnitsRare(int indx)
{
if ( !GlueCount )
{
GlueCount = 255;
GlueFreeBlocks();
if (FreeList[indx] != 0)
return RemoveNode(indx);
}
int i = indx;
do
{
if (++i == N_INDEXES)
{
GlueCount--;
i = U2B(Indx2Units[indx]);
return (UnitsStart - pText > i) ? (UnitsStart -= i) : (NULL);
}
} while (FreeList[i] == 0);
void* RetVal = RemoveNode(i);
SplitBlock(RetVal, i, indx);
return RetVal;
}
void* AllocUnits(int NU)
{
int indx = Units2Indx[NU - 1];
if (FreeList[indx] != 0)
return RemoveNode(indx);
void* RetVal = LoUnit;
LoUnit += U2B(Indx2Units[indx]);
if (LoUnit <= HiUnit)
return RetVal;
LoUnit -= U2B(Indx2Units[indx]);
return AllocUnitsRare(indx);
}
void* AllocContext()
{
if (HiUnit != LoUnit)
return (HiUnit -= UNIT_SIZE);
if (FreeList[0] != 0)
return RemoveNode(0);
return AllocUnitsRare(0);
}
void* ExpandUnits(void* oldPtr, int oldNU)
{
int i0=Units2Indx[oldNU - 1], i1=Units2Indx[oldNU - 1 + 1];
if (i0 == i1)
return oldPtr;
void* ptr = AllocUnits(oldNU + 1);
if (ptr)
{
memcpy(ptr, oldPtr, U2B(oldNU));
InsertNode(oldPtr, i0);
}
return ptr;
}
void* ShrinkUnits(void* oldPtr, int oldNU, int newNU)
{
int i0 = Units2Indx[oldNU - 1], i1 = Units2Indx[newNU - 1];
if (i0 == i1)
return oldPtr;
if (FreeList[i1] != 0)
{
void* ptr = RemoveNode(i1);
memcpy(ptr, oldPtr, U2B(newNU));
InsertNode(oldPtr,i0);
return ptr;
}
else
{
SplitBlock(oldPtr, i0, i1);
return oldPtr;
}
}
void FreeUnits(void* ptr, int oldNU)
{
InsertNode(ptr, Units2Indx[oldNU - 1]);
}
};
#endif
<file_sep>/FBReaderJ/src/org/geometerplus/zlibrary/core/txt/ZLTxtReader.java
/*
* Copyright (C) 2007-2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.zlibrary.core.txt;
import java.lang.String;
public interface ZLTxtReader {
public void startDocumentHandler();
public void endDocumentHandler();
public void characterDataHandler(String tag);
public void startElementHandler();
public void endElementHandler();
public void setByteDecoder(String charset);
}
<file_sep>/FBReaderJ/src/org/geometerplus/fbreader/network/NetworkLink.java
/*
* Copyright (C) 2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
package org.geometerplus.fbreader.network;
import java.util.*;
import org.geometerplus.zlibrary.core.options.ZLBooleanOption;
import org.geometerplus.zlibrary.core.network.ZLNetworkRequest;
import org.geometerplus.fbreader.network.authentication.NetworkAuthenticationManager;
abstract public class NetworkLink {
public static final String URL_MAIN = "main";
public static final String URL_SEARCH = "search";
public static final String URL_SIGN_IN = "signIn";
public static final String URL_SIGN_OUT = "signOut";
public static final String URL_SIGN_UP = "signUp";
public static final String URL_REFILL_ACCOUNT = "refillAccount";
public static final String URL_RECOVER_PASSWORD = "<PASSWORD>";
public final String SiteName;
public final String Title;
public final String Summary;
public final String Icon;
public final ZLBooleanOption OnOption;
public final TreeMap<String, String> Links;
/**
* Creates new NetworkLink instance.
*
* @param siteName name of the corresponding website. Must be not <code>null</code>.
* @param title title of the corresponding library item. Must be not <code>null</code>.
* @param summary description of the corresponding library item. Can be <code>null</code>.
* @param icon string contains link's icon data/url. Can be <code>null</code>.
* @param links map contains URLs with their identifiers; must always contain one URL with <code>URL_MAIN</code> identifier
*/
public NetworkLink(String siteName, String title, String summary, String icon, Map<String, String> links) {
SiteName = siteName;
Title = title;
Summary = summary;
Icon = icon;
OnOption = new ZLBooleanOption(SiteName, "on", true);
Links = new TreeMap(links);
}
public abstract ZLNetworkRequest simpleSearchRequest(String pattern, NetworkOperationData data);
public abstract ZLNetworkRequest resume(NetworkOperationData data);
public abstract NetworkLibraryItem libraryItem();
public abstract NetworkAuthenticationManager authenticationManager();
public abstract String rewriteUrl(String url, boolean isUrlExternal);
}
<file_sep>/FingerSuite/FingerNotification/resource.h
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by FingerNotification.rc
//
#define IDS_LVK_EXIT 98
#define IDS_RVK_MENU 99
#define IDS_NO_NEW_NOTIFICATIONS 102
#define IDS_VOLUME 103
#define IDS_BATTERY 104
#define IDR_MAINFRAME 128
#define IDR_SOFTKEYMENU 201
#define IDM_SOFTKEYMENU 201
#define IDI_VOLUME_VIBRATE 202
#define IDI_VOLUME_OFF 203
#define IDI_VOLUME_ON 204
#define IDI_BATTERY_ABSENT 205
#define IDI_BATTERY_CHARGING 206
#define IDI_BATTERY_CRITICAL 208
#define IDI_BATTERY_1 209
#define IDI_BATTERY_2 210
#define IDI_BATTERY_3 211
#define IDI_BATTERY_4 212
#define IDI_BATTERY_5 213
#define IDI_ICON6 219
#define IDI_ICON10 223
#define IDI_SIGNAL_4 226
#define IDI_CONN_E 227
#define IDI_CONN_G 228
#define IDI_CONN_H 229
#define IDI_INCALL 230
#define IDI_NO_SERVICE 231
#define IDI_OFF 232
#define IDI_PHONE 233
#define IDI_SEARCHING 234
#define IDI_SIGNAL_1 235
#define IDI_SIGNAL_2 236
#define IDI_SIGNAL_3 237
#define IDI_ICON1 238
#define IDI_CONN_3G 238
#define IDM_BTN1 32772
#define IDM_BTN2 32773
#define ID_MENU_SHOWORIGINAL 40003
#define ID_MENU_ABOUT 40004
#define ID_MENU_EXIT 40006
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 239
#define _APS_NEXT_COMMAND_VALUE 32774
#define _APS_NEXT_CONTROL_VALUE 1000
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
<file_sep>/SQLCEHelper/Source/ForeignKey.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
//-------------------------------------------------------------------------
//
// CForeignKey - table foreign key schema
//
//-------------------------------------------------------------------------
CForeignKey::CForeignKey(DBCONSTRAINTDESC* pConstraintDesc)
{
ULONG i;
ATLASSERT(pConstraintDesc != NULL);
ATLASSERT(pConstraintDesc->ConstraintType == DBCONSTRAINTTYPE_FOREIGNKEY);
ATLASSERT(pConstraintDesc->cColumns == pConstraintDesc->cForeignKeyColumns);
m_strName = pConstraintDesc->pConstraintID->uName.pwszName;
m_strRefTable = pConstraintDesc->pReferencedTableID->uName.pwszName;
m_match = pConstraintDesc->MatchType;
m_deleteRule = pConstraintDesc->DeleteRule;
m_updateRule = pConstraintDesc->UpdateRule;
m_deferrability = pConstraintDesc->Deferrability;
for(i = 0; i < pConstraintDesc->cColumns; ++i)
{
LPCTSTR pszRefColumn = pConstraintDesc->rgColumnList[i].uName.pwszName,
pszKeyColumn = pConstraintDesc->rgForeignKeyColumnList[i].uName.pwszName;
CForeignKeyPair* pPair = new CForeignKeyPair(pszRefColumn, pszKeyColumn);
if(pPair != NULL)
m_pairs.Add(pPair);
}
}
CForeignKey::~CForeignKey()
{
Clear();
}
void CForeignKey::Clear()
{
size_t i, n = m_pairs.GetCount();
for(i = 0; i < n; ++i)
delete m_pairs[i];
m_pairs.RemoveAll();
}
<file_sep>/SQLCEHelper/Source/Rowset.cpp
#include "stdafx.h"
#include "Currency.h"
using namespace OLEDBCLI;
CRowset::CRowset()
: m_pRowset (NULL),
m_pRowsetChange (NULL),
m_pRowsetUpdate (NULL),
m_pRowsetIndex (NULL),
m_pColAccessor (NULL),
m_pKeyAccessor (NULL),
m_hRow (NULL),
m_nColumns (0),
m_nKeyColumns (0),
m_nAccessors (0),
m_nRowSize (0),
m_nKeySize (0),
m_pBoundColumn (NULL),
m_pBoundKey (NULL),
m_pColumnNames (NULL),
m_phAccessor (NULL),
m_hKeyAccessor (NULL),
m_pBuffer (NULL),
m_pKeyBuffer (NULL),
m_pBindStatus (NULL),
m_bCustomBound (false),
m_pValueRef (NULL),
m_pKeyRef (NULL)
{
}
CRowset::~CRowset()
{
Close();
}
// CRowset::GetBlobCount
//
// Counts the number of BLOB columns in the rowset.
// This is required in order to know the number of accessor to allocate.
//
ULONG CRowset::GetBlobCount(DBCOLUMNINFO* pColumnInfo, ULONG nColumns)
{
ULONG nBlobs = 0,
iCol;
for(iCol = 0; iCol < nColumns; ++iCol)
{
bool bIsBlob = (pColumnInfo[iCol].dwFlags & DBCOLUMNFLAGS_ISLONG) != 0;
if(bIsBlob)
++nBlobs;
}
return nBlobs;
}
DBCOLUMNINFO* CRowset::GetTableColumnInfo(LPCTSTR pszColumnName, DBCOLUMNINFO* pColumnInfo)
{
DBCOLUMNINFO* pColInfo = pColumnInfo;
if(!pColumnInfo)
return NULL;
for(ULONG iCol = 0; iCol< m_nColumns; ++iCol, ++pColInfo)
{
if(NULL != pColInfo->pwszName)
{
if(0 == _wcsicmp(pColInfo->pwszName, pszColumnName))
return pColInfo;
}
}
return NULL;
}
// CRowset::BindKeyColumns
//
// Binds the key columns, if any
//
HRESULT CRowset::BindKeyColumns(DBCOLUMNINFO* pColumnInfo)
{
HRESULT hr;
ULONG nPropSet = 0;
DBPROPSET* pPropSet = NULL;
ULONG i;
DBINDEXCOLUMNDESC* pKeyColumnDesc;
hr = m_pRowsetIndex->GetIndexInfo(&m_nKeyColumns, // Number of index columns
&pKeyColumnDesc, // Names of columns
&nPropSet, // Don't care
&pPropSet); // Don't care
if(SUCCEEDED(hr))
{
CBindingArray binding;
DBBINDING* pBinding = NULL;
m_pBoundKey = new BOUNDCOLUMN[m_nKeyColumns];
if(binding.Allocate(m_nKeyColumns) && m_pBoundKey != NULL)
{
DWORD dwOffset = 0;
BOUNDCOLUMN* pBoundKey = m_pBoundKey;
memset(m_pBoundKey, 0, m_nKeyColumns * sizeof(BOUNDCOLUMN));
m_nKeySize = 0;
pBinding = binding[0];
for(i = 0; i < m_nKeyColumns; ++i, ++pBinding, ++pBoundKey)
{
DBCOLUMNINFO* pColInfo;
pColInfo = GetTableColumnInfo(pKeyColumnDesc[i].pColumnID->uName.pwszName, pColumnInfo);
pBinding->iOrdinal = pColInfo->iOrdinal;
pBinding->dwPart = DBPART_VALUE | DBPART_STATUS | DBPART_LENGTH;
pBinding->obLength = dwOffset;
pBinding->obStatus = AddOffset(pBinding->obLength, sizeof(ULONG));
pBinding->obValue = AddOffset(pBinding->obStatus, sizeof(DBSTATUS));
pBinding->pObject = NULL;
pBinding->pBindExt = NULL;
pBinding->pTypeInfo = NULL;
pBinding->dwMemOwner = DBMEMOWNER_CLIENTOWNED;
pBinding->dwFlags = 0;
pBinding->wType = pColInfo->wType;
pBinding->bPrecision = pColInfo->bPrecision;
pBinding->bScale = pColInfo->bScale;
switch(pBinding->wType)
{
case DBTYPE_WSTR:
pBinding->cbMaxLen = sizeof(WCHAR)*(pColInfo->ulColumnSize + 1); // Extra buffer for null terminator
break;
default:
pBinding->cbMaxLen = pColInfo->ulColumnSize;
break;
}
dwOffset = AddOffset(pBinding->obValue, pBinding->cbMaxLen);
pBoundKey->bPrecision = pBinding->bPrecision;
pBoundKey->bScale = pBinding->bScale;
pBoundKey->dwFlags = pColumnInfo->dwFlags;
pBoundKey->iAccessor = 0;
pBoundKey->iOrdinal = i + 1;//pBinding->iOrdinal;
pBoundKey->obLength = pBinding->obLength;
pBoundKey->obStatus = pBinding->obStatus;
pBoundKey->obValue = pBinding->obValue;
pBoundKey->pwszName = pColumnInfo->pwszName;
pBoundKey->ulColumnSize = pBinding->cbMaxLen;
pBoundKey->wType = pColInfo->wType;
}
// Allocate the key buffer
m_pKeyBuffer = new BYTE[dwOffset * 2];
if(m_pKeyBuffer != NULL)
{
m_nKeySize = dwOffset;
// Allocate the CDbValueRef array
m_pKeyRef = new CDbValueRef[m_nKeyColumns];
if(m_pKeyRef != NULL)
{
ULONG iCol;
// Assign all value refs
for(iCol = 0; iCol < m_nKeyColumns; ++iCol)
{
pBoundKey = m_pBoundKey + iCol;
m_pKeyRef[iCol] = CDbValueRef(pBoundKey, m_pKeyBuffer);
}
hr = m_pRowsetIndex->QueryInterface(IID_IAccessor, (void**)&m_pKeyAccessor);
if(SUCCEEDED(hr))
{
hr = m_pKeyAccessor->CreateAccessor(DBACCESSOR_ROWDATA, m_nKeyColumns, binding[0], dwOffset * 2, &m_hKeyAccessor, NULL);
}
}
else
hr = E_OUTOFMEMORY;
}
else
hr = E_OUTOFMEMORY;
}
else
hr = E_OUTOFMEMORY;
}
//
// Free the provider-allocated memory
//
if(pPropSet != NULL)
{
for(i = 0; i < nPropSet; ++i)
{
ULONG iProp;
for(iProp = 0; iProp < pPropSet[i].cProperties; ++iProp)
VariantClear(&pPropSet[i].rgProperties[iProp].vValue);
CoTaskMemFree(pPropSet[i].rgProperties);
}
CoTaskMemFree(pPropSet);
}
if(pKeyColumnDesc != NULL)
CDbMemory::Free(pKeyColumnDesc, m_nKeyColumns);
return hr;
}
// CRowset::Open
//
// Opens the rowset using an existing IRowset pointer
//
HRESULT CRowset::Open(IRowset* pRowset)
{
HRESULT hr;
CComPtr<IColumnsInfo> spColumnsInfo; // Automatically deleted at the end of the method
ULONG iCol,
iAcc = 0,
nBlobs = 0;
BOUNDCOLUMN* pBoundColumn = NULL;
DBCOLUMNINFO* pColumnInfo = NULL;
DBBINDING* pBinding = NULL;
DBBINDSTATUS* pBindStatus = NULL;
ULONG iBinding = 0;
CBindingArray binding;
CAtlArray<DBCOLUMNINFO> columnInfo;
Close();
m_pRowset = pRowset;
// Query for additional interfaces
hr = m_pRowset->QueryInterface(IID_IRowsetChange, (void**)&m_pRowsetChange);
if(FAILED(hr))
m_pRowsetChange = NULL;
hr = m_pRowset->QueryInterface(IID_IRowsetUpdate, (void**)&m_pRowsetUpdate);
if(FAILED(hr))
m_pRowsetUpdate = NULL;
hr = m_pRowset->QueryInterface(IID_IRowsetIndex, (void**)&m_pRowsetIndex);
if(FAILED(hr))
m_pRowsetIndex = NULL;
// Get the associated IColumnsInfo interface
hr = m_pRowset->QueryInterface(IID_IColumnsInfo, (void**)&spColumnsInfo);
if(FAILED(hr))
return hr;
// Get the the table's column names.
// Note that the first column (iOrdinal = 0) is the bookmark - it has no name!
hr = spColumnsInfo->GetColumnInfo(&m_nColumns, &pColumnInfo, &m_pColumnNames);
if(FAILED(hr))
return hr;
// Copy the DBCOLUMNINFO array to our safe array
if(!columnInfo.SetCount(m_nColumns))
{
CoTaskMemFree(pColumnInfo);
return E_OUTOFMEMORY;
}
memcpy(columnInfo.GetData(), pColumnInfo, m_nColumns * sizeof(DBCOLUMNINFO));
// Get the number of blob columns in the rowset.
nBlobs = GetBlobCount(pColumnInfo, m_nColumns);
CoTaskMemFree(pColumnInfo);
// Allocate the bound columns array
m_pBoundColumn = new BOUNDCOLUMN[m_nColumns];
if(m_pBoundColumn == NULL)
return E_OUTOFMEMORY;
memset(m_pBoundColumn, 0, m_nColumns * sizeof(BOUNDCOLUMN));
// Start the binding process by allocating the binding array
if(!binding.Allocate(m_nColumns))
return E_OUTOFMEMORY;
m_nAccessors = nBlobs + 1;
m_nRowSize = 0;
pBinding = binding[0];
pColumnInfo = columnInfo.GetData();
// Fill the binding array for the non-BLOB columns
// All of these columns will be bound by the accessor handle at index zero
for(iCol = 0; iCol < m_nColumns; ++iCol, ++pColumnInfo)
{
ULONG nColumnSize = pColumnInfo->ulColumnSize;
DBTYPE wType = pColumnInfo->wType;
bool bIsBlob = (pColumnInfo->dwFlags & DBCOLUMNFLAGS_ISLONG) != 0;
// Skip this column if it is a BLOB
if(bIsBlob)
continue;
if(wType == DBTYPE_STR)
++nColumnSize; // Add the NULL terminator
// If this is a UNICODE string, correct the size and allow for the NULL terminator
if(wType == DBTYPE_WSTR)
nColumnSize = (nColumnSize + 1) * sizeof(wchar_t);
pBinding->iOrdinal = pColumnInfo->iOrdinal;
pBinding->wType = wType;
pBinding->bPrecision = pColumnInfo->bPrecision;
pBinding->bScale = pColumnInfo->bScale;
pBinding->dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
pBinding->dwMemOwner = DBMEMOWNER_CLIENTOWNED;
pBinding->cbMaxLen = nColumnSize;
pBinding->obLength = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG));
pBinding->obStatus = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG));
pBinding->obValue = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, nColumnSize);
// Set the bound column info
pBoundColumn = m_pBoundColumn + iCol;
pBoundColumn->bPrecision = pBinding->bPrecision;
pBoundColumn->bScale = pBinding->bScale;
pBoundColumn->dwFlags = pColumnInfo->dwFlags;
pBoundColumn->iAccessor = 0;
pBoundColumn->iOrdinal = pBinding->iOrdinal;
pBoundColumn->obLength = pBinding->obLength;
pBoundColumn->obStatus = pBinding->obStatus;
pBoundColumn->obValue = pBinding->obValue;
pBoundColumn->pwszName = pColumnInfo->pwszName;
pBoundColumn->ulColumnSize = nColumnSize;
pBoundColumn->wType = wType;
++pBinding;
}
// Fill the binding array for the BLOB columns
// Each column will be bound using its own accessor handle wich is stored in the accessor handle array.
int iAccessor = 1;
pColumnInfo = columnInfo.GetData();
for(iCol = 0; (m_nAccessors > 1) && (iCol < m_nColumns); ++iCol, ++pColumnInfo)
{
ULONG nColumnSize = pColumnInfo->ulColumnSize;
DBTYPE wType = pColumnInfo->wType;
bool bIsBlob = (pColumnInfo->dwFlags & DBCOLUMNFLAGS_ISLONG) != 0;
DBOBJECT* pDbObject;
// Skip this column if it is NOT a BLOB
if(!bIsBlob)
continue;
// Allocate the DBOBJECT - this will be released by the Close method
pDbObject = new DBOBJECT;
if(pDbObject == NULL)
{
Close();
return E_OUTOFMEMORY;
}
pDbObject->dwFlags = STGM_READ; // Check if this is enough
pDbObject->iid = IID_ISequentialStream;
nColumnSize = sizeof(IUnknown*);
pBinding->iOrdinal = pColumnInfo->iOrdinal;
pBinding->wType = DBTYPE_IUNKNOWN;
pBinding->bPrecision = 0;
pBinding->bScale = 0;
pBinding->dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
pBinding->dwMemOwner = DBMEMOWNER_CLIENTOWNED;
pBinding->cbMaxLen = nColumnSize;
pBinding->pObject = pDbObject;
pBinding->obLength = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG));
pBinding->obStatus = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG));
pBinding->obValue = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, nColumnSize);
// Set the bound column info
pBoundColumn = m_pBoundColumn + iCol;
pBoundColumn->bPrecision = pBinding->bPrecision;
pBoundColumn->bScale = pBinding->bScale;
pBoundColumn->dwFlags = pColumnInfo->dwFlags;
pBoundColumn->iAccessor = iAccessor++;
pBoundColumn->iOrdinal = pBinding->iOrdinal;
pBoundColumn->obLength = pBinding->obLength;
pBoundColumn->obStatus = pBinding->obStatus;
pBoundColumn->obValue = pBinding->obValue;
pBoundColumn->pwszName = pColumnInfo->pwszName;
pBoundColumn->ulColumnSize = nColumnSize;
pBoundColumn->wType = wType;
++pBinding;
}
// Allocate the data buffer
m_pBuffer = new BYTE[m_nRowSize];
if(m_pBuffer == NULL)
return E_OUTOFMEMORY;
memset(m_pBuffer, 0, m_nRowSize);
// Allocate the DBBINDSTATUS array. We own this memory.
m_pBindStatus = new DBBINDSTATUS[m_nColumns];
if(m_pBindStatus == NULL)
return E_OUTOFMEMORY;
// Allocate the CDbValueRef array
m_pValueRef = new CDbValueRef[m_nColumns];
if(m_pValueRef == NULL)
return E_OUTOFMEMORY;
// Assign all value refs
for(iCol = 0; iCol < m_nColumns; ++iCol)
{
pBoundColumn = m_pBoundColumn + iCol;
m_pValueRef[iCol] = CDbValueRef(pBoundColumn, m_pBuffer);
}
// Get the IAccessor interface
hr = m_pRowset->QueryInterface(IID_IAccessor, (void**)&m_pColAccessor);
if(FAILED(hr))
return hr;
// Allocate the accessor handle array
m_phAccessor = new HACCESSOR[m_nAccessors];
if(m_phAccessor == NULL)
return E_OUTOFMEMORY;
// Bind the non-BLOB data first
hr = m_pColAccessor->CreateAccessor(DBACCESSOR_ROWDATA,
m_nColumns - nBlobs,
binding[0],
m_nRowSize,
&m_phAccessor[0],
m_pBindStatus);
if(FAILED(hr))
return hr;
ULONG nBlobBindSize = AddOffset(sizeof(IUnknown*), AddOffset(sizeof(ULONG), sizeof(ULONG)));
iAccessor = 1;
pBinding = binding[0] + m_nColumns - nBlobs;
pBindStatus = m_pBindStatus + m_nColumns - nBlobs;
for(iCol = 0; SUCCEEDED(hr) && (iCol < nBlobs); ++iCol)
{
hr = m_pColAccessor->CreateAccessor(DBACCESSOR_ROWDATA,
1,
pBinding,
nBlobBindSize,
&m_phAccessor[iAccessor],
pBindStatus);
++pBinding;
++iAccessor;
++pBindStatus;
}
// Finally, bind the key columns
if(m_pRowsetIndex != NULL)
hr = BindKeyColumns(columnInfo.GetData());
return hr;
}
// CRowset::Close
//
// Closes a rowset
//
void CRowset::Close()
{
ULONG i;
ReleaseRow();
if(m_pColAccessor != NULL)
{
if(m_phAccessor != NULL)
{
for(i = 0; i < m_nAccessors; ++i)
{
m_pColAccessor->ReleaseAccessor(m_phAccessor[i], NULL);
m_phAccessor[i] = NULL;
}
}
delete [] m_phAccessor;
m_phAccessor = NULL;
m_pColAccessor->Release();
m_pColAccessor = NULL;
}
if(m_pKeyAccessor != NULL)
{
m_pKeyAccessor->ReleaseAccessor(m_hKeyAccessor, NULL);
m_pKeyAccessor->Release();
m_pKeyAccessor = NULL;
}
// Release the BOUNDCOLUMN arrays
if(m_pBoundColumn != NULL)
{
delete [] m_pBoundColumn;
m_pBoundColumn = NULL;
}
if(m_pBoundKey != NULL)
{
delete [] m_pBoundKey;
m_pBoundKey = NULL;
}
if(m_pRowset != NULL)
{
m_pRowset->Release();
m_pRowset = NULL;
}
if(m_pRowsetChange != NULL)
{
m_pRowsetChange->Release();
m_pRowsetChange = NULL;
}
if(m_pRowsetUpdate != NULL)
{
m_pRowsetUpdate->Release();
m_pRowsetUpdate = NULL;
}
if(m_pRowsetIndex != NULL)
{
m_pRowsetIndex->Release();
m_pRowsetIndex = NULL;
}
if(m_pColumnNames != NULL)
{
CoTaskMemFree(m_pColumnNames);
m_pColumnNames = NULL;
}
m_nColumns = 0;
// Free the data buffer
delete [] m_pBuffer;
delete [] m_pKeyBuffer;
delete [] m_pBindStatus;
delete [] m_pValueRef;
delete [] m_pKeyRef;
m_pBuffer = NULL;
m_pKeyBuffer = NULL;
m_pBindStatus = NULL;
m_pValueRef = NULL;
m_pKeyRef = NULL;
m_nRowSize = 0;
}
// CRowset::ReleaseRow
//
// Releases the acquired row, if any
//
HRESULT CRowset::ReleaseRow()
{
HRESULT hr = S_OK;
if(m_hRow != NULL && m_pRowset != NULL)
{
hr = m_pRowset->ReleaseRows(1, &m_hRow, NULL, NULL, NULL);
if(SUCCEEDED(hr))
m_hRow = NULL;
}
return hr;
}
// CRowset::MoveFirst
//
// Moves to the first row in the rowset
//
HRESULT CRowset::MoveFirst()
{
HRESULT hr;
ReleaseRow();
hr = m_pRowset->RestartPosition(DB_NULL_HCHAPTER);
if(FAILED(hr))
return hr;
return MoveNext();
}
// CRowset::MoveRelative
//
// Moves the rowset position relative to the current position
// Reads the next row
//
HRESULT CRowset::MoveRelative(LONG nOffset)
{
HRESULT hr;
ULONG nRows;
HROW* pRow = &m_hRow;
ReleaseRow();
hr = m_pRowset->GetNextRows(DB_NULL_HCHAPTER, nOffset - 1, 1, &nRows, &pRow);
if(FAILED(hr))
return hr;
// Fetch the row
hr = m_pRowset->GetData(m_hRow, m_phAccessor[0], m_pBuffer);
return hr;
}
// CRowset::MoveToBookmark
//
// Moves the rowset pointer to the given bookmark
//
HRESULT CRowset::MoveToBookmark(ULONG cbBookmark, const BYTE *pBookmark)
{
HRESULT hr;
CComPtr<IRowsetBookmark> spRowsetBookmark;
hr = m_pRowset->QueryInterface(IID_IRowsetBookmark,(void**)&spRowsetBookmark);
if(FAILED(hr))
return hr;
ReleaseRow();
hr = spRowsetBookmark->PositionOnBookmark(DB_NULL_HCHAPTER, cbBookmark, pBookmark);
if(FAILED(hr))
return hr;
// Move and read the row
hr = MoveNext();
return hr;
}
// CRowset::GetRowCount
//
// Counts all the rows in the rowset by scrolling through all of them.
//
HRESULT CRowset::GetRowCount(ULONG *pcRows)
{
HRESULT hr;
ULONG nRows,
nRowCount = 0;
HROW* pRow = &m_hRow;
ReleaseRow();
hr = m_pRowset->RestartPosition(DB_NULL_HCHAPTER);
while(hr == S_OK)
{
hr = m_pRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &nRows, &pRow);
if(hr == S_OK)
{
++nRowCount;
ReleaseRow();
}
}
if(SUCCEEDED(hr))
*pcRows = nRowCount;
return hr;
}
HRESULT CRowset::Update()
{
DBROWSTATUS* pRowStatus;
HRESULT hr;
if(m_pRowsetUpdate == NULL)
return E_NOINTERFACE;
hr = m_pRowsetUpdate->Update(DB_NULL_HCHAPTER, 1, &m_hRow, NULL, NULL, &pRowStatus);
if(SUCCEEDED(hr))
CoTaskMemFree(pRowStatus);
return hr;
}
HRESULT CRowset::Undo()
{
DBROWSTATUS* pRowStatus;
HRESULT hr;
if(m_pRowsetUpdate == NULL)
return E_NOINTERFACE;
hr = m_pRowsetUpdate->Undo(DB_NULL_HCHAPTER, 1, &m_hRow, NULL, NULL, &pRowStatus);
if(SUCCEEDED(hr))
CoTaskMemFree(pRowStatus);
return hr;
}
// CRowset::Insert
//
// Inserts the current row
//
HRESULT CRowset::Insert()
{
HRESULT hr;
if(m_pRowsetChange == NULL)
return E_NOINTERFACE;
ReleaseRow();
hr = m_pRowsetChange->InsertRow(DB_NULL_HCHAPTER, m_phAccessor[0], m_pBuffer, &m_hRow);
// Check for delayed update mode
if(m_pRowsetUpdate != NULL && SUCCEEDED(hr))
{
ULONG i;
// Set the data for all accessors (BLOBs)
for(i = 1; SUCCEEDED(hr) && (i < m_nAccessors); ++i)
hr = m_pRowsetChange->SetData(m_hRow, m_phAccessor[i], m_pBuffer);
if(SUCCEEDED(hr))
hr = Update();
else
Undo();
}
return hr;
}
// CRowset::Delete
//
// Deletes the current row
//
HRESULT CRowset::Delete()
{
HRESULT hr;
DBROWSTATUS rowStatus = 0;
if(m_pRowsetChange == NULL)
return E_NOINTERFACE;
// Delete the rows
hr = m_pRowsetChange->DeleteRows(DB_NULL_HCHAPTER, 1, &m_hRow, &rowStatus);
// Check for delayed update mode
if(m_pRowsetUpdate != NULL)
{
if(SUCCEEDED(hr))
hr = Update();
else
Undo();
}
return hr;
}
// CRowset::SetData
//
// Sets the current row data
//
HRESULT CRowset::SetData()
{
HRESULT hr = S_OK;
ULONG i;
if(m_pRowsetChange == NULL)
return E_NOINTERFACE;
for(i = 0; SUCCEEDED(hr) && (i < m_nAccessors); ++i)
hr = m_pRowsetChange->SetData(m_hRow, m_phAccessor[i], m_pBuffer);
// Check for delayed update mode
if(m_pRowsetUpdate != NULL)
{
if(SUCCEEDED(hr))
hr = Update();
else
Undo();
}
return hr;
}
/*
ULONG CRowset::GetColumnIndex(LPCTSTR pszColumnName)
{
return 0;
}
*/
// CRowset::GetColumnIndex
//
// Returns a column index given the column ordinal
//
ULONG CRowset::GetColumnIndex(ULONG iOrdinal)
{
if(m_bCustomBound)
{
BOUNDCOLUMN* pBoundColumn = m_pBoundColumn;
ULONG iCol;
for(iCol = 0; iCol < m_nColumns; ++iCol, ++pBoundColumn)
{
if(pBoundColumn->iOrdinal == iOrdinal)
return iCol;
}
}
else
{
if(HasBookmark())
return iOrdinal;
return iOrdinal - 1;
}
return (ULONG)-1;
}
// CRowset::SeekRow
//
// Seeks the previously set key values - does NOT retrieve data from the row.
//
HRESULT CRowset::SeekRow(int cKeyValues, DBSEEK dwSeekOptions)
{
HRESULT hr = E_NOINTERFACE;
if(m_pRowsetIndex != NULL)
{
ReleaseRow();
hr = m_pRowsetIndex->Seek(m_hKeyAccessor,
m_nKeyColumns,
m_pKeyBuffer,
dwSeekOptions);
if(hr == S_OK)
{
ULONG ulRowsFetched = 0;
// Release a row if one is already around
//ReleaseRows();
// Get the row handle
HROW* phRow = &m_hRow;
hr = m_pRowset->GetNextRows(NULL, 0, 1, &ulRowsFetched, &phRow);
}
}
return hr;
}
// CRowset::Seek
//
// Seeks the previously set key values and retrieve data from the row, if found.
//
HRESULT CRowset::Seek(int cKeyValues, DBSEEK dwSeekOptions)
{
HRESULT hr = SeekRow(cKeyValues, dwSeekOptions);
if(hr == S_OK)
hr = m_pRowset->GetData(m_hRow, m_phAccessor[0], m_pBuffer);
return hr;
}<file_sep>/7-Zip/CPP/7zip/Compress/PpmdEncoder.h
// PpmdEncoder.h
// 2009-05-30 : <NAME> : Public domain
#ifndef __COMPRESS_PPMD_ENCODER_H
#define __COMPRESS_PPMD_ENCODER_H
#include "../../Common/MyCom.h"
#include "../ICoder.h"
#include "../Common/InBuffer.h"
#include "PpmdEncode.h"
#include "RangeCoder.h"
namespace NCompress {
namespace NPpmd {
class CEncoder :
public ICompressCoder,
public ICompressSetCoderProperties,
public ICompressWriteCoderProperties,
public CMyUnknownImp
{
public:
CInBuffer _inStream;
NRangeCoder::CEncoder _rangeEncoder;
CEncodeInfo _info;
UInt32 _usedMemorySize;
Byte _order;
HRESULT Flush()
{
_rangeEncoder.FlushData();
return _rangeEncoder.FlushStream();
}
void ReleaseStreams()
{
_inStream.ReleaseStream();
_rangeEncoder.ReleaseStream();
}
HRESULT CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
class CEncoderFlusher
{
CEncoder *_encoder;
public:
CEncoderFlusher(CEncoder *encoder): _encoder(encoder) {}
~CEncoderFlusher()
{
_encoder->Flush();
_encoder->ReleaseStreams();
}
};
public:
MY_UNKNOWN_IMP2(
ICompressSetCoderProperties,
ICompressWriteCoderProperties)
STDMETHOD(Code)(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress);
STDMETHOD(SetCoderProperties)(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps);
STDMETHOD(WriteCoderProperties)(ISequentialOutStream *outStream);
CEncoder();
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/Wim/WimRegister.cpp
// WimRegister.cpp
#include "StdAfx.h"
#include "../../Common/RegisterArc.h"
#include "WimHandler.h"
static IInArchive *CreateArc() { return new NArchive::NWim::CHandler; }
static CArcInfo g_ArcInfo =
{ L"Wim", L"wim swm", 0, 0xE6, { 'M', 'S', 'W', 'I', 'M', 0, 0, 0 }, 8, false, CreateArc, 0 };
REGISTER_ARC(Wim)
<file_sep>/SQLCEHelper/Source/Command.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
// CCommand::CCommand
//
// Constructor - builds the CCommand from the CSession object
//
CCommand::CCommand(OLEDBCLI::CSession &session)
: m_pCommand (NULL),
m_nParams (0),
m_pszParamNames (NULL),
m_pBoundParam (NULL),
m_pBuffer (NULL),
m_nRowSize (0),
m_pBindStatus (NULL),
m_hParamAccessor(NULL),
m_pParam (NULL),
m_pParamInfo (NULL)
{
IUnknown* pUnknown = session;
CComPtr<IDBCreateCommand> spCreateCommand;
HRESULT hr;
hr = pUnknown->QueryInterface(IID_IDBCreateCommand, (void**)&spCreateCommand);
if(SUCCEEDED(hr))
{
hr = spCreateCommand->CreateCommand(NULL, IID_ICommandText, (IUnknown**)&m_pCommand);
if(FAILED(hr))
m_pCommand = NULL;
}
}
// CCommand::~CCommand
//
// Destructor
//
CCommand::~CCommand()
{
ClearParameters();
if(m_pCommand != NULL)
{
m_pCommand->Release();
m_pCommand = NULL;
}
}
void CCommand::ClearBinding()
{
if(m_pBuffer != NULL)
{
delete [] m_pBuffer;
m_pBuffer = NULL;
m_nRowSize = 0;
}
if(m_pBoundParam != NULL)
{
delete [] m_pBoundParam;
m_pBoundParam = NULL;
}
if(m_pBindStatus != NULL)
{
delete [] m_pBindStatus;
m_pBindStatus = NULL;
}
if(m_hParamAccessor != NULL)
{
CComPtr<IAccessor> spAccessor;
HRESULT hr = m_pCommand->QueryInterface(IID_IAccessor, (void**)&spAccessor);
if(SUCCEEDED(hr))
{
spAccessor->ReleaseAccessor(m_hParamAccessor, NULL);
m_hParamAccessor = NULL;
}
}
}
// CCommand::ClearParameters
//
// Frees all parameter info.
//
void CCommand::ClearParameters()
{
ClearBinding();
if(m_pszParamNames != NULL)
{
CoTaskMemFree(m_pszParamNames);
m_pszParamNames = NULL;
}
if(m_pParamInfo != NULL)
{
CoTaskMemFree(m_pParamInfo);
m_pParamInfo = NULL;
}
if(m_pParam != NULL)
delete [] m_pParam;
m_pParam = NULL;
m_nParams = 0;
}
// CCommand::SetText
//
// Sets the command text
//
HRESULT CCommand::SetText(LPCTSTR pszText)
{
HRESULT hr;
ATLASSERT(m_pCommand != NULL);
ATLASSERT(pszText != NULL);
hr = m_pCommand->SetCommandText(DBGUID_DEFAULT, pszText);
return hr;
}
// CCommand::RebindParameters
//
// Checks if the parameter buffer increased since last Bind.
// Must return true for first execution.
//
bool CCommand::RebindParameters()
{
ULONG iParam;
ULONG nSize = 0;
for(iParam = 0; iParam < m_nParams; ++iParam)
{
nSize += sizeof(DBSTATUS) + sizeof(ULONG);
if(m_pParam[iParam].GetType() == DBTYPE_WSTR)
nSize += m_pParam[iParam].GetLength() * sizeof(wchar_t);
else
nSize += m_pParam[iParam].GetLength();
}
return nSize > m_nRowSize;
}
// CCommand::BindParameters
//
// Binds command parameters
//
HRESULT CCommand::BindParameters()
{
HRESULT hr;
CComPtr<IAccessor> spAccessor;
DBBINDING* pBinding = NULL;
BOUNDCOLUMN* pBoundParam = NULL;
ULONG iParam;
CBindingArray binding;
DBPARAMINFO* pParamInfo = m_pParamInfo;
// Check if we need to bind the parameters
if(!RebindParameters())
return S_OK;
// Start the binding process by allocating the binding array
if(!binding.Allocate(m_nParams))
return E_OUTOFMEMORY;
// Allocate the BOUNDCOLUMN array for parameters
m_pBoundParam = new BOUNDCOLUMN[m_nParams];
if(m_pBoundParam == NULL)
return E_OUTOFMEMORY;
pBinding = binding[0];
pBoundParam = m_pBoundParam;
for(iParam = 0; iParam < m_nParams; ++iParam, ++pParamInfo, ++pBinding, ++pBoundParam)
{
ULONG nParamSize = m_pParam[iParam].GetLength();
DBTYPE wType = pParamInfo->wType;
DWORD dwFlags = pParamInfo->dwFlags;
if(wType == DBTYPE_STR)
++nParamSize; // Add the NULL terminator
// If this is a UNICODE string, correct the size and allow for the NULL terminator
if(wType == DBTYPE_WSTR)
nParamSize = (nParamSize + 1) * sizeof(wchar_t);
pBinding->iOrdinal = pParamInfo->iOrdinal;
pBinding->wType = wType;
pBinding->bPrecision = pParamInfo->bPrecision;
pBinding->bScale = pParamInfo->bScale;
pBinding->dwPart = DBPART_VALUE | DBPART_LENGTH | DBPART_STATUS;
pBinding->dwMemOwner = DBMEMOWNER_CLIENTOWNED;
pBinding->cbMaxLen = nParamSize;
pBinding->pObject = NULL;
if(dwFlags & DBPARAMFLAGS_ISINPUT)
pBinding->eParamIO |= DBPARAMIO_INPUT;
if(dwFlags & DBPARAMFLAGS_ISOUTPUT)
pBinding->eParamIO |= DBPARAMIO_OUTPUT;
pBinding->obLength = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG));
pBinding->obStatus = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, sizeof(ULONG));
pBinding->obValue = m_nRowSize;
m_nRowSize = AddOffset(m_nRowSize, nParamSize);
pBoundParam->bPrecision = pBinding->bPrecision;
pBoundParam->bScale = pBinding->bScale;
pBoundParam->dwFlags = dwFlags;
pBoundParam->iAccessor = 0;
pBoundParam->iOrdinal = pBinding->iOrdinal;
pBoundParam->obLength = pBinding->obLength;
pBoundParam->obStatus = pBinding->obStatus;
pBoundParam->obValue = pBinding->obValue;
pBoundParam->pwszName = pParamInfo->pwszName;
pBoundParam->ulColumnSize = nParamSize;
pBoundParam->wType = wType;
}
// Allocate the data buffer
m_pBuffer = new BYTE[m_nRowSize];
if(m_pBuffer == NULL)
return E_OUTOFMEMORY;
// Allocate the DBBINDSTATUS array. We own this memory.
m_pBindStatus = new DBBINDSTATUS[m_nParams];
if(m_pBindStatus == NULL)
return E_OUTOFMEMORY;
hr = m_pCommand->QueryInterface(IID_IAccessor, (void**)&spAccessor);
if(FAILED(hr))
return hr;
hr = spAccessor->CreateAccessor(DBACCESSOR_PARAMETERDATA, m_nParams, binding[0], m_nRowSize, &m_hParamAccessor, m_pBindStatus);
return hr;
}
// CCommand::SetAllParameters
//
// Copies all parameter values from the staging array to the parameter buffer
//
void CCommand::SetAllParameters()
{
ULONG iParam;
BOUNDCOLUMN* pBoundParam = m_pBoundParam;
for(iParam = 0; iParam < m_nParams; ++iParam, ++pBoundParam)
{
CDbValue& value = m_pParam[iParam];
DBSTATUS* pStatus = (DBSTATUS*) (m_pBuffer + pBoundParam->obStatus);
ULONG* pLength = (ULONG*) (m_pBuffer + pBoundParam->obLength);
BYTE* pValue = (BYTE*) (m_pBuffer + pBoundParam->obValue);
*pStatus = value.GetStatus();
*pLength = value.GetType() == DBTYPE_WSTR ? value.GetLength() * sizeof(wchar_t) : value.GetLength();
if(*pStatus == DBSTATUS_S_OK && *pLength > 0)
memcpy(pValue, value.GetDataPtr(), *pLength);
}
}
// CCommand::CreateParameters
//
// Creates te parameter value array to buffer data
//
HRESULT CCommand::CreateParameters(DBPARAMINFO* pParamInfo)
{
ULONG iParam;
m_pParam = new CDbValue[m_nParams];
if(m_pParam == NULL)
return E_OUTOFMEMORY;
for(iParam = 0; iParam < m_nParams; ++iParam, ++pParamInfo)
{
bool bIsLong = pParamInfo->ulParamSize > 8192;
ULONG nParamSize = bIsLong ? 1024 : pParamInfo->ulParamSize;
m_pParam[iParam].Initialize(pParamInfo->wType, nParamSize, nParamSize, bIsLong);
}
return S_OK;
}
// CCommand::Prepare
//
// Prepares the command for execution (compiles an execution plan)
//
HRESULT CCommand::Prepare(ULONG cExpectedRuns)
{
CComPtr<ICommandPrepare> spCommandPrepare;
CComPtr<ICommandWithParameters> spCommandParams;
HRESULT hr;
ATLASSERT(m_pCommand != NULL);
hr = m_pCommand->QueryInterface(IID_ICommandPrepare, (void**)&spCommandPrepare);
if(FAILED(hr))
return hr;
hr = spCommandPrepare->Prepare(cExpectedRuns);
if(FAILED(hr))
return hr;
// Retrieve the command parameters, if any
hr = m_pCommand->QueryInterface(IID_ICommandWithParameters, (void**)&spCommandParams);
if(SUCCEEDED(hr))
{
ClearParameters();
hr = spCommandParams->GetParameterInfo(&m_nParams, &m_pParamInfo, &m_pszParamNames);
if(SUCCEEDED(hr) && m_nParams)
{
hr = CreateParameters(m_pParamInfo);
if(SUCCEEDED(hr))
hr = BindParameters();
}
}
return hr;
}
// CCommand::Unprepare
//
// Unprepares the command (releases the compiled execution plan)
//
HRESULT CCommand::Unprepare()
{
CComPtr<ICommandPrepare> spCommandPrepare;
HRESULT hr;
ATLASSERT(m_pCommand != NULL);
hr = m_pCommand->QueryInterface(IID_ICommandPrepare, (void**)&spCommandPrepare);
if(FAILED(hr))
return hr;
hr = spCommandPrepare->Unprepare();
if(SUCCEEDED(hr))
ClearParameters();
return hr;
}
// CCommand::Execute
//
// Executes the command without returning a rowset.
// Use for DDL commands.
//
HRESULT CCommand::Execute(LONG *pcRowsAffected)
{
HRESULT hr;
DBPARAMS dbParams;
DBPARAMS* pParams = NULL;
ATLASSERT(m_pCommand != NULL);
hr = BindParameters();
if(FAILED(hr))
return hr;
SetAllParameters();
if(m_nParams)
{
dbParams.cParamSets = 1;
dbParams.hAccessor = m_hParamAccessor;
dbParams.pData = m_pBuffer;
pParams = &dbParams;
}
hr = m_pCommand->Execute(NULL, IID_NULL, &dbParams, pcRowsAffected, NULL);
return hr;
}
// CCommand::Execute
//
// Executes the command and returns a rowset.
//
HRESULT CCommand::Execute(CRowset &rowset, LONG *pcRowsAffected)
{
HRESULT hr;
IRowset* pRowset = NULL;
DBPARAMS dbParams;
DBPARAMS* pParams = NULL;
ATLASSERT(m_pCommand != NULL);
hr = BindParameters();
if(FAILED(hr))
return hr;
SetAllParameters();
if(m_nParams)
{
dbParams.cParamSets = 1;
dbParams.hAccessor = m_hParamAccessor;
dbParams.pData = m_pBuffer;
pParams = &dbParams;
}
hr = m_pCommand->Execute(NULL, IID_IRowset, pParams, pcRowsAffected, (IUnknown**)&pRowset);
if(FAILED(hr))
return hr;
hr = rowset.Open(pRowset);
return hr;
}
// CCommand::FindParameter
//
// Returns a parameter entry index from the given ordinal or NULL if not found
//
ULONG CCommand::FindParameter(ULONG iOrdinal)
{
ULONG i;
BOUNDCOLUMN* p;
for(i = 0, p = m_pBoundParam; i < m_nParams; ++i, ++p)
{
if(p->iOrdinal == iOrdinal)
return i;
}
return (ULONG)-1;
}
<file_sep>/7-Zip/CPP/7zip/Archive/Nsis/NsisIn.h
// NsisIn.h
#ifndef __ARCHIVE_NSIS_IN_H
#define __ARCHIVE_NSIS_IN_H
#include "Common/Buffer.h"
#include "Common/MyCom.h"
#include "Common/StringConvert.h"
#include "NsisDecode.h"
// #define NSIS_SCRIPT
namespace NArchive {
namespace NNsis {
const int kSignatureSize = 16;
#define NSIS_SIGNATURE { 0xEF, 0xBE, 0xAD, 0xDE, 0x4E, 0x75, 0x6C, 0x6C, 0x73, 0x6F, 0x66, 0x74, 0x49, 0x6E, 0x73, 0x74}
extern Byte kSignature[kSignatureSize];
const UInt32 kFlagsMask = 0xF;
namespace NFlags
{
const UInt32 kUninstall = 1;
const UInt32 kSilent = 2;
const UInt32 kNoCrc = 4;
const UInt32 kForceCrc = 8;
}
struct CFirstHeader
{
UInt32 Flags;
UInt32 HeaderLength;
UInt32 ArchiveSize;
bool ThereIsCrc() const
{
if ((Flags & NFlags::kForceCrc ) != 0)
return true;
return ((Flags & NFlags::kNoCrc) == 0);
}
UInt32 GetDataSize() const { return ArchiveSize - (ThereIsCrc() ? 4 : 0); }
};
struct CBlockHeader
{
UInt32 Offset;
UInt32 Num;
};
struct CItem
{
AString PrefixA;
UString PrefixU;
AString NameA;
UString NameU;
FILETIME MTime;
bool IsUnicode;
bool UseFilter;
bool IsCompressed;
bool SizeIsDefined;
bool CompressedSizeIsDefined;
bool EstimatedSizeIsDefined;
UInt32 Pos;
UInt32 Size;
UInt32 CompressedSize;
UInt32 EstimatedSize;
UInt32 DictionarySize;
CItem(): IsUnicode(false), UseFilter(false), IsCompressed(true), SizeIsDefined(false),
CompressedSizeIsDefined(false), EstimatedSizeIsDefined(false), Size(0) {}
bool IsINSTDIR() const
{
return (PrefixA.Length() >= 3 || PrefixU.Length() >= 3);
}
UString GetReducedName(bool unicode) const
{
UString s;
if (unicode)
s = PrefixU;
else
s = MultiByteToUnicodeString(PrefixA);
if (s.Length() > 0)
if (s[s.Length() - 1] != L'\\')
s += L'\\';
if (unicode)
s += NameU;
else
s += MultiByteToUnicodeString(NameA);
const int len = 9;
if (s.Left(len).CompareNoCase(L"$INSTDIR\\") == 0)
s = s.Mid(len);
return s;
}
};
class CInArchive
{
UInt64 _archiveSize;
CMyComPtr<IInStream> _stream;
Byte ReadByte();
UInt32 ReadUInt32();
HRESULT Open2(
DECL_EXTERNAL_CODECS_LOC_VARS2
);
void ReadBlockHeader(CBlockHeader &bh);
AString ReadStringA(UInt32 pos) const;
UString ReadStringU(UInt32 pos) const;
AString ReadString2A(UInt32 pos) const;
UString ReadString2U(UInt32 pos) const;
AString ReadString2(UInt32 pos) const;
AString ReadString2Qw(UInt32 pos) const;
HRESULT ReadEntries(const CBlockHeader &bh);
HRESULT Parse();
CByteBuffer _data;
UInt64 _size;
size_t _posInData;
UInt32 _stringsPos;
bool _headerIsCompressed;
UInt32 _nonSolidStartOffset;
public:
HRESULT Open(
DECL_EXTERNAL_CODECS_LOC_VARS
IInStream *inStream, const UInt64 *maxCheckStartPosition);
void Clear();
UInt64 StreamOffset;
CDecoder Decoder;
CObjectVector<CItem> Items;
CFirstHeader FirstHeader;
NMethodType::EEnum Method;
UInt32 DictionarySize;
bool IsSolid;
bool UseFilter;
bool FilterFlag;
bool IsUnicode;
#ifdef NSIS_SCRIPT
AString Script;
#endif
UInt32 GetOffset() const { return IsSolid ? 4 : 0; }
UInt64 GetDataPos(int index)
{
const CItem &item = Items[index];
return GetOffset() + FirstHeader.HeaderLength + item.Pos;
}
UInt64 GetPosOfSolidItem(int index) const
{
const CItem &item = Items[index];
return 4 + FirstHeader.HeaderLength + item.Pos;
}
UInt64 GetPosOfNonSolidItem(int index) const
{
const CItem &item = Items[index];
return StreamOffset + _nonSolidStartOffset + 4 + item.Pos;
}
void Release()
{
Decoder.Release();
}
};
}}
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/RpmHandler.cpp
// RpmHandler.cpp
#include "StdAfx.h"
#include "../../../C/CpuArch.h"
#include "Common/ComTry.h"
#include "Common/MyString.h"
#include "Windows/PropVariant.h"
#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"
#include "../Compress/CopyCoder.h"
using namespace NWindows;
#define Get16(p) GetBe16(p)
#define Get32(p) GetBe32(p)
namespace NArchive {
namespace NRpm {
/* Reference: lib/signature.h of rpm package */
#define RPMSIG_NONE 0 /* Do not change! */
/* The following types are no longer generated */
#define RPMSIG_PGP262_1024 1 /* No longer generated */ /* 256 byte */
/* These are the new-style signatures. They are Header structures. */
/* Inside them we can put any number of any type of signature we like. */
#define RPMSIG_HEADERSIG 5 /* New Header style signature */
const UInt32 kLeadSize = 96;
struct CLead
{
unsigned char Magic[4];
unsigned char Major; // not supported ver1, only support 2,3 and lator
unsigned char Minor;
UInt16 Type;
UInt16 ArchNum;
char Name[66];
UInt16 OSNum;
UInt16 SignatureType;
char Reserved[16]; // pad to 96 bytes -- 8 byte aligned
bool MagicCheck() const
{ return Magic[0] == 0xed && Magic[1] == 0xab && Magic[2] == 0xee && Magic[3] == 0xdb; };
};
const UInt32 kEntryInfoSize = 16;
/*
struct CEntryInfo
{
int Tag;
int Type;
int Offset; // Offset from beginning of data segment, only defined on disk
int Count;
};
*/
// case: SignatureType == RPMSIG_HEADERSIG
const UInt32 kCSigHeaderSigSize = 16;
struct CSigHeaderSig
{
unsigned char Magic[4];
UInt32 Reserved;
UInt32 IndexLen; // count of index entries
UInt32 DataLen; // number of bytes
bool MagicCheck()
{ return Magic[0] == 0x8e && Magic[1] == 0xad && Magic[2] == 0xe8 && Magic[3] == 0x01; };
UInt32 GetLostHeaderLen()
{ return IndexLen * kEntryInfoSize + DataLen; };
};
static HRESULT RedSigHeaderSig(IInStream *inStream, CSigHeaderSig &h)
{
char dat[kCSigHeaderSigSize];
char *cur = dat;
RINOK(ReadStream_FALSE(inStream, dat, kCSigHeaderSigSize));
memmove(h.Magic, cur, 4);
cur += 4;
cur += 4;
h.IndexLen = Get32(cur);
cur += 4;
h.DataLen = Get32(cur);
return S_OK;
}
HRESULT OpenArchive(IInStream *inStream)
{
UInt64 pos;
char leadData[kLeadSize];
char *cur = leadData;
CLead lead;
RINOK(ReadStream_FALSE(inStream, leadData, kLeadSize));
memmove(lead.Magic, cur, 4);
cur += 4;
lead.Major = *cur++;
lead.Minor = *cur++;
lead.Type = Get16(cur);
cur += 2;
lead.ArchNum = Get16(cur);
cur += 2;
memmove(lead.Name, cur, sizeof(lead.Name));
cur += sizeof(lead.Name);
lead.OSNum = Get16(cur);
cur += 2;
lead.SignatureType = Get16(cur);
cur += 2;
if (!lead.MagicCheck() || lead.Major < 3)
return S_FALSE;
CSigHeaderSig sigHeader, header;
if (lead.SignatureType == RPMSIG_NONE)
{
;
}
else if (lead.SignatureType == RPMSIG_PGP262_1024)
{
UInt64 pos;
RINOK(inStream->Seek(256, STREAM_SEEK_CUR, &pos));
}
else if (lead.SignatureType == RPMSIG_HEADERSIG)
{
RINOK(RedSigHeaderSig(inStream, sigHeader));
if (!sigHeader.MagicCheck())
return S_FALSE;
UInt32 len = sigHeader.GetLostHeaderLen();
RINOK(inStream->Seek(len, STREAM_SEEK_CUR, &pos));
if ((pos % 8) != 0)
{
RINOK(inStream->Seek((pos / 8 + 1) * 8 - pos,
STREAM_SEEK_CUR, &pos));
}
}
else
return S_FALSE;
RINOK(RedSigHeaderSig(inStream, header));
if (!header.MagicCheck())
return S_FALSE;
int headerLen = header.GetLostHeaderLen();
if (headerLen == -1)
return S_FALSE;
RINOK(inStream->Seek(headerLen, STREAM_SEEK_CUR, &pos));
return S_OK;
}
class CHandler:
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp
{
CMyComPtr<IInStream> _stream;
UInt64 _pos;
UInt64 _size;
Byte _sig[4];
public:
MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};
STATPROPSTG kProps[] =
{
{ NULL, kpidSize, VT_UI8}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps_NO_Table
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
NCOM::CPropVariant prop;
switch(propID) { case kpidMainSubfile: prop = (UInt32)0; break; }
prop.Detach(value);
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *inStream,
const UInt64 * /* maxCheckStartPosition */,
IArchiveOpenCallback * /* openArchiveCallback */)
{
COM_TRY_BEGIN
try
{
Close();
if (OpenArchive(inStream) != S_OK)
return S_FALSE;
RINOK(inStream->Seek(0, STREAM_SEEK_CUR, &_pos));
RINOK(ReadStream_FALSE(inStream, _sig, sizeof(_sig) / sizeof(_sig[0])));
UInt64 endPosition;
RINOK(inStream->Seek(0, STREAM_SEEK_END, &endPosition));
_size = endPosition - _pos;
_stream = inStream;
return S_OK;
}
catch(...) { return S_FALSE; }
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
_stream.Release();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = 1;
return S_OK;
}
STDMETHODIMP CHandler::GetProperty(UInt32 /* index */, PROPID propID, PROPVARIANT *value)
{
NWindows::NCOM::CPropVariant prop;
switch(propID)
{
case kpidSize:
case kpidPackSize:
prop = _size;
break;
case kpidExtension:
{
char s[32];
MyStringCopy(s, "cpio.");
const char *ext;
if (_sig[0] == 0x1F && _sig[1] == 0x8B)
ext = "gz";
else if (_sig[0] == 'B' && _sig[1] == 'Z' && _sig[2] == 'h')
ext = "bz2";
else
ext = "lzma";
MyStringCopy(s + MyStringLen(s), ext);
prop = s;
break;
}
}
prop.Detach(value);
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
if (numItems == 0)
return S_OK;
if (numItems != (UInt32)-1 && (numItems != 1 || indices[0] != 0))
return E_INVALIDARG;
RINOK(extractCallback->SetTotal(_size));
CMyComPtr<ISequentialOutStream> outStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
RINOK(extractCallback->GetStream(0, &outStream, askMode));
if (!testMode && !outStream)
return S_OK;
RINOK(extractCallback->PrepareOperation(askMode));
CMyComPtr<ICompressCoder> copyCoder = new NCompress::CCopyCoder;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
RINOK(_stream->Seek(_pos, STREAM_SEEK_SET, NULL));
RINOK(copyCoder->Code(_stream, outStream, NULL, NULL, progress));
outStream.Release();
return extractCallback->SetOperationResult(NExtract::NOperationResult::kOK);
COM_TRY_END
}
STDMETHODIMP CHandler::GetStream(UInt32 /* index */, ISequentialInStream **stream)
{
COM_TRY_BEGIN
return CreateLimitedInStream(_stream, _pos, _size, stream);
COM_TRY_END
}
static IInArchive *CreateArc() { return new NArchive::NRpm::CHandler; }
static CArcInfo g_ArcInfo =
{ L"Rpm", L"rpm", 0, 0xEB, { 0xED, 0xAB, 0xEE, 0xDB}, 4, false, CreateArc, 0 };
REGISTER_ARC(Rpm)
}}
<file_sep>/FingerSuite/FingerMsgBox/MainFrm.h
// MainFrm.h : interface of the CMainFrame class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "sharedmem.h"
#include "InterceptEngine.h"
#include "..\Common\Utils.h"
#include "..\Common\log\logger.h"
#include "..\Common\AboutView.h"
#include "..\Common\fngrbtn.h"
#include "..\FingerSuiteCPL\Commons.h"
#include "MsgBoxWindow.h"
#include "..\Common\fngrsplash.h"
#define IDT_TMR_DISABLED 10012
#define MASK_EVENTMUTE 0x0004
typedef enum {QVGA = 320, WQVGA = 400, VGA = 640, WVGA = 800} RESOLUTION;
static UINT UWM_INTERCEPT_MSGBOX = ::RegisterWindowMessage(UWM_INTERCEPT_MSGBOX_MSG);
static UINT UWM_UPDATECONFIGURATION = ::RegisterWindowMessage(UWM_UPDATECONFIGURATION_MSG);
class CMainFrame : public CFrameWindowImpl<CMainFrame>, public CUpdateUI<CMainFrame>,
public CMessageFilter, public CIdleHandler
{
public:
DECLARE_FRAME_WND_CLASS(L"FINGER_MSGBOX", IDR_MAINFRAME)
CMsgBoxWindow m_msgBoxView;
CAboutView m_aboutView;
virtual BOOL PreTranslateMessage(MSG* pMsg)
{
if(CFrameWindowImpl<CMainFrame>::PreTranslateMessage(pMsg))
return TRUE;
return m_msgBoxView.PreTranslateMessage(pMsg);
}
virtual BOOL OnIdle()
{
return FALSE;
}
void DoPaint(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
if (m_bDisabledTransp)
{
dc.FillSolidRect(&rc, m_clNoTranspBackground);
}
else
{
if (!(m_imgBkg.IsValid()))
CaptureScreen(dc);
m_imgBkg.Draw(dc, rc);
}
}
BEGIN_UPDATE_UI_MAP(CMainFrame)
END_UPDATE_UI_MAP()
BEGIN_MSG_MAP(CMainFrame)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
MESSAGE_HANDLER(WM_DESTROY, OnDestroy)
MESSAGE_HANDLER(WM_SIZE, OnSize)
MESSAGE_HANDLER(WM_CLOSE, OnClose)
MESSAGE_HANDLER(WM_ERASEBKGND, OnEraseBkgnd)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_ACTIVATE, OnActivate)
MESSAGE_HANDLER(WM_WININICHANGE, OnWininichange)
MESSAGE_HANDLER(UM_MINIMIZE, OnMinimize)
MESSAGE_HANDLER(UWM_INTERCEPT_MSGBOX, OnInterceptMsgBox)
MESSAGE_HANDLER(UWM_UPDATECONFIGURATION, OnUpdateConfiguration)
COMMAND_ID_HANDLER(ID_MENU_CANCEL, OnCancel)
COMMAND_ID_HANDLER(ID_MENU_EXIT, OnMenuExit)
COMMAND_ID_HANDLER(ID_MENU_ABOUT, OnMenuAbout)
COMMAND_ID_HANDLER(ID_MENU_SHOWORIGINAL, OnMenuShowOriginal)
COMMAND_ID_HANDLER(ID_MENU_ADDTOEXCLUSIONLIST, OnMenuAddToExclusionList)
COMMAND_ID_HANDLER(ID_MENU_ADDTOWNDEXCLUSIONLIST, OnMenuAddToWndExclusionList)
CHAIN_MSG_MAP(CUpdateUI<CMainFrame>)
CHAIN_MSG_MAP(CFrameWindowImpl<CMainFrame>)
END_MSG_MAP()
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
CreateSimpleCEMenuBar(FM_IDW_MENU_BAR, SHCMBF_HIDESIPBUTTON);
CSplashWindow* pSplash = new CSplashWindow(m_hWnd, IDR_MAINFRAME, L"FingerMsgbox");
LoadConfiguration();
// msgbox
m_hWndClient = m_msgBoxView.Create(m_hWnd);
// about
CString strCredits = "\n\n"
"\tFingerMsgBox v1.01\n\n"
"\rProgrammed by:\n"
"<NAME>\n"
"<<EMAIL>>\n"
"\n\n"
"http://forum.xda-developers.com/\n"
" showthread.php?t=459125\n";
m_aboutView.SetCredits(strCredits);
m_aboutView.Create(m_hWnd, rcDefault, NULL, WS_CHILD | WS_VISIBLE |WS_CLIPSIBLINGS | WS_CLIPCHILDREN); //
// register object for message filtering and idle updates
CMessageLoop* pLoop = _Module.GetMessageLoop();
ATLASSERT(pLoop != NULL);
pLoop->AddMessageFilter(this);
pLoop->AddIdleHandler(this);
SetHWndServerMsgBox(m_hWnd);
InstallHook();
SignalWaitEvent(EVT_FNGRMSGBOX);
ModifyStyle(0, WS_NONAVDONEBUTTON, SWP_NOSIZE);
m_bDisabled = FALSE;
pSplash->Dismiss();
return 0;
}
LRESULT OnDestroy(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 0;
}
LRESULT OnSize(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& bHandled)
{
if(wParam != SIZE_MINIMIZED)
{
}
return 0;
}
LRESULT OnClose(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& bHandled)
{
RemoveHook();
if (!(m_fText.IsNull()))
{
m_fText.DeleteObject();
m_fText = NULL;
}
if (!(m_fCaption.IsNull()))
{
m_fCaption.DeleteObject();
m_fCaption = NULL;
}
if (!(m_fBtn.IsNull()))
{
m_fBtn.DeleteObject();
m_fBtn = NULL;
}
bHandled = FALSE;
return 0;
}
LRESULT OnEraseBkgnd(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
return 1;
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if(wParam != NULL)
{
DoPaint((HDC)wParam);
}
else
{
CPaintDC dc(m_hWnd);
DoPaint(dc.m_hDC);
}
return 0;
}
LRESULT OnActivate(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
int fActive = LOWORD(wParam);
if ((fActive == WA_ACTIVE) || (fActive == WA_CLICKACTIVE))
{
}
else if (fActive == WA_INACTIVE)
{
if (IsWindowVisible())
{
SetMsgBoxResult(IDCANCEL);
Minimize();
}
}
return 0;
}
LRESULT OnWininichange(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
if (wParam == SETTINGCHANGE_RESET)
{
//SetMsgBoxResult(IDCANCEL);
//Minimize();
m_msgBoxView.ModifyShape();
m_msgBoxView.ModifyButtons();
}
return 0;
}
LRESULT OnMinimize(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
Minimize();
return 0;
}
LRESULT OnCancel(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
SetMsgBoxResult(IDCANCEL);
Minimize();
return 0;
}
LRESULT OnInterceptMsgBox(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM lParam, BOOL& bHandled)
{
LPMSGBOXINFO lpInfo = (LPMSGBOXINFO)lParam;
HWND hDestWnd = lpInfo->hWnd;
UINT uType = lpInfo->uType;
LOG(L"Intercepting MessageBoxW...uType=%08x hWnd=%08X\n", uType, hDestWnd);
if (m_bDisabled)
return 1;
if (IsDeviceLocked())
return 1;
m_hForeWnd = ::GetForegroundWindow();
if (IsExcludedApp(hDestWnd))
return 1;
if (IsExcludedWnd(hDestWnd))
return 1;
if (!(m_msgBoxView.SetMsgBox(hDestWnd, uType, lpInfo->szCaption, lpInfo->szText)))
return 1;
Sleep(100);
SwitchToMsgBoxView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
PlayMessageBoxSound(uType);
bHandled = TRUE;
return 0;
}
LRESULT OnMenuExit(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
SetMsgBoxResult(IDCANCEL);
Minimize();
PostMessage(WM_CLOSE);
return 0;
}
LRESULT OnMenuAbout(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
SwitchToAboutView();
SetForegroundWindow((HWND)((ULONG) m_hWnd | 0x00000001));
ShowWindow(SW_SHOW);
return 0;
}
LRESULT OnMenuShowOriginal(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
SetMsgBoxResult(-1);
Minimize();
return 0;
}
LRESULT OnMenuAddToExclusionList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
HWND hDestWnd = m_msgBoxView.GetOwnerWnd();
DWORD dwProcessId; GetWindowThreadProcessId(hDestWnd, &dwProcessId);
HMODULE hProcess = (HMODULE)dwProcessId;
WCHAR szName[MAX_PATH];
if (GetModuleFileName(hProcess, szName, MAX_PATH))
{
CString szApp = (LPTSTR)szName;
szApp = szApp.Right(szApp.GetLength() - szApp.ReverseFind('\\') - 1);
if (m_excludedApps.Find(szApp) == -1)
m_excludedApps.Add(szApp);
SaveExclusionList(m_excludedApps, L"Software\\FingerMsgbox");
}
SetMsgBoxResult(-1);
Minimize();
return 0;
}
LRESULT OnMenuAddToWndExclusionList(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
HWND hDestWnd = m_msgBoxView.GetOwnerWnd();
WCHAR szTitle[MAX_PATH];
::GetWindowText(hDestWnd, szTitle, MAX_PATH);
WCHAR szClassName[MAX_PATH];
::GetClassName(hDestWnd, szClassName, MAX_PATH);
WCHAR szName[MAX_PATH];
wsprintf(szName, L"%s - %s", szTitle, szClassName);
CString szWnd = (LPTSTR)szName;
if (m_excludedWnds.Find(szWnd) == -1)
m_excludedWnds.Add(szWnd);
SaveWndExclusionList(m_excludedWnds, L"Software\\FingerMsgbox");
SetMsgBoxResult(-1);
Minimize();
return 0;
}
LRESULT OnUpdateConfiguration(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
LoadConfiguration();
SetMsgBoxResult(FALSE);
Minimize();
return 0;
}
private:
void Minimize()
{
ShowWindow(SW_HIDE);
SignalWaitEvent(EVT_FNGRMSGBOX);
}
HWND ManageDOTNETApp(HWND& hDestWnd)
{
HWND hDestCtrl = NULL;
WCHAR szClass[50];
::GetClassName(hDestWnd, szClass, 50);
if (lstrcmpi(szClass, L"MS_SOFTKEY_CE_1.0") == 0)
{
DWORD dwProcessId; GetWindowThreadProcessId(hDestWnd, &dwProcessId);
HWND hDotNETWnd = ::FindWindow(L"#NETCF_AGL_BASE_", NULL);
if (hDotNETWnd != NULL)
{
DWORD dwProcess2Id; GetWindowThreadProcessId(hDotNETWnd, &dwProcess2Id);
if (dwProcess2Id == dwProcessId)
{
hDestCtrl = hDestWnd;
hDestWnd = hDotNETWnd;
}
}
}
return hDestCtrl;
}
BOOL IsExcludedApp(HWND hWnd)
{
DWORD dwProcessId; GetWindowThreadProcessId(hWnd, &dwProcessId);
HMODULE hProcess = (HMODULE)dwProcessId;
WCHAR szName[MAX_PATH];
if (GetModuleFileName(hProcess, szName, MAX_PATH))
{
CString szApp = (LPTSTR)szName;
szApp = szApp.Right(szApp.GetLength() - szApp.ReverseFind('\\') - 1);
for (int i = 0; i < m_excludedApps.GetSize(); i ++)
{
if (m_excludedApps[i].CompareNoCase( szApp ) == 0)
return TRUE;
}
}
return FALSE;
}
BOOL IsExcludedWnd(HWND hWnd)
{
WCHAR szTitle[MAX_PATH];
::GetWindowText(hWnd, szTitle, MAX_PATH);
WCHAR szClassName[MAX_PATH];
::GetClassName(hWnd, szClassName, MAX_PATH);
WCHAR szName[MAX_PATH];
wsprintf(szName, L"%s - %s", szTitle, szClassName);
CString szWnd = (LPTSTR)szName;
for (int i = 0; i < m_excludedWnds.GetSize(); i ++)
{
if (m_excludedWnds[i].CompareNoCase( szWnd ) == 0)
return TRUE;
}
return FALSE;
}
void CaptureScreen(CDCHandle dc)
{
RECT rc; GetClientRect(&rc);
CDC dcTemp; dcTemp.CreateCompatibleDC(dc);
CBitmap bmpBkg; bmpBkg.CreateCompatibleBitmap(dc, rc.right, rc.bottom);
CBitmap bmpOld = dcTemp.SelectBitmap(bmpBkg);
dcTemp.FillSolidRect(&rc, RGB(0,0,0));
dcTemp.SelectBitmap(bmpOld);
m_imgBkg.CreateFromHBITMAP(bmpBkg);
m_imgBkg.AlphaCreate();
m_imgBkg.AlphaSet((BYTE)m_iTransp);
}
void LoadConfiguration()
{
WCHAR keyName[] = L"Software\\FingerMsgBox";
// load transparency level
m_iTransp = 128;
if (!(RegReadDWORD(HKEY_LOCAL_MACHINE, keyName, L"TransparencyLevel", m_iTransp)))
wprintf(L"Unable to read TransparencyLevel from registry: %s\n", ErrorString(GetLastError()));
m_msgBoxView.m_iTransp = m_iTransp;
m_bDisabledTransp = FALSE;
if (!(RegReadBOOL(HKEY_LOCAL_MACHINE, keyName, L"DisableTransparency", m_bDisabledTransp)))
wprintf(L"Unable to read DisableTransparency from registry: %s\n", ErrorString(GetLastError()));
m_msgBoxView.m_bDisabledTransp = m_bDisabledTransp;
m_clNoTranspBackground = RGB(0,0,0);
RegReadColor(HKEY_LOCAL_MACHINE, keyName, L"NoTranspBkgColor", m_clNoTranspBackground);
m_msgBoxView.m_clNoTranspBackground = m_clNoTranspBackground;
WCHAR szSkin[60] = L"default";
RegReadString(HKEY_LOCAL_MACHINE, keyName, L"Skin", szSkin);
WCHAR szAppPath[MAX_PATH] = L"";
CString strAppDirectory;
GetModuleFileName(NULL, szAppPath, MAX_PATH);
strAppDirectory = szAppPath;
strAppDirectory = strAppDirectory.Left(strAppDirectory.ReverseFind('\\'));
CString skinBasePath; skinBasePath.Format(L"%s\\skins\\%s", strAppDirectory, szSkin);
// detect resolution
RESOLUTION resolution = QVGA;
DEVMODE dm;
::ZeroMemory(&dm, sizeof(DEVMODE));
dm.dmSize = sizeof(DEVMODE);
if (EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dm))
{
resolution = (RESOLUTION)dm.dmPelsHeight;
}
// load icon images
switch (resolution)
{
case QVGA:
case WQVGA:
m_msgBoxView.SetScaleFactor(1);
break;
case VGA:
case WVGA:
m_msgBoxView.SetScaleFactor(2);
break;
}
if ( (resolution == VGA) || (resolution == WVGA))
{
m_msgBoxView.m_imgHeader.Load(skinBasePath + L"\\msgbox_header_vga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnInfo.Load(skinBasePath + L"\\msgbox_iconinfo_vga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnQuestion.Load(skinBasePath + L"\\msgbox_iconquestion_vga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnStop.Load(skinBasePath + L"\\msgbox_iconstop_vga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnWarning.Load(skinBasePath + L"\\msgbox_iconwarning_vga.png", CXIMAGE_FORMAT_PNG);
// normal
AddDynamicSet(m_msgBoxView.m_arrDynamicImages, NORMAL, skinBasePath + L"\\msgbox_button_normal_left_vga.png",
skinBasePath + L"\\msgbox_button_normal_center_vga.png",
skinBasePath + L"\\msgbox_button_normal_right_vga.png");
// pressed
AddDynamicSet(m_msgBoxView.m_arrDynamicImages, PUSHED, skinBasePath + L"\\msgbox_button_pressed_left_vga.png",
skinBasePath + L"\\msgbox_button_pressed_center_vga.png",
skinBasePath + L"\\msgbox_button_pressed_right_vga.png");
}
else
{
m_msgBoxView.m_imgHeader.Load(skinBasePath + L"\\msgbox_header_qvga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnInfo.Load(skinBasePath + L"\\msgbox_iconinfo_qvga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnQuestion.Load(skinBasePath + L"\\msgbox_iconquestion_qvga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnStop.Load(skinBasePath + L"\\msgbox_iconstop_qvga.png", CXIMAGE_FORMAT_PNG);
m_msgBoxView.m_icnWarning.Load(skinBasePath + L"\\msgbox_iconwarning_qvga.png", CXIMAGE_FORMAT_PNG);
// normal
AddDynamicSet(m_msgBoxView.m_arrDynamicImages, NORMAL, skinBasePath + L"\\msgbox_button_normal_left_qvga.png",
skinBasePath + L"\\msgbox_button_normal_center_qvga.png",
skinBasePath + L"\\msgbox_button_normal_right_qvga.png");
// pressed
AddDynamicSet(m_msgBoxView.m_arrDynamicImages, PUSHED, skinBasePath + L"\\msgbox_button_pressed_left_qvga.png",
skinBasePath + L"\\msgbox_button_pressed_center_qvga.png",
skinBasePath + L"\\msgbox_button_pressed_right_qvga.png");
}
// load skin settings
CSimpleIniW ini(TRUE, TRUE, TRUE);
SI_Error rc = ini.LoadFile(skinBasePath + L"\\settings_fingermsgbox.ini");
// load background and selected color
COLORREF clValue = 0;
m_msgBoxView.m_clBkg = (StringRGBToColor(ini.GetValue(L"colors", L"BkgColor"), clValue)) ? clValue : RGB(255,255,255);
m_msgBoxView.m_clCaptionText = (StringRGBToColor(ini.GetValue(L"colors", L"CaptionTextColor"), clValue)) ? clValue : RGB(255,255,255);
m_msgBoxView.m_clText = (StringRGBToColor(ini.GetValue(L"colors", L"TextColor"), clValue)) ? clValue : RGB(0,0,0);
m_msgBoxView.m_clBtnText = (StringRGBToColor(ini.GetValue(L"colors", L"ButtonTextColor"), clValue)) ? clValue : RGB(0,0,0);
m_msgBoxView.m_clBtnSelText = (StringRGBToColor(ini.GetValue(L"colors", L"SelButtonTextColor"), clValue)) ? clValue : RGB(255,255,255);
m_msgBoxView.m_clLine = (StringRGBToColor(ini.GetValue(L"colors", L"LineColor"), clValue)) ? clValue : RGB(160,160,160);
if (!(m_fText.IsNull())) m_fText.DeleteObject();
if (!(m_fCaption.IsNull())) m_fCaption.DeleteObject();
if (!(m_fBtn.IsNull())) m_fBtn.DeleteObject();
LOGFONT lf;
if (StringToLogFont(ini.GetValue(L"fonts", L"TextFont"), lf))
{
m_fText.CreateFontIndirect(&lf);
}
if (StringToLogFont(ini.GetValue(L"fonts", L"CaptionFont"), lf))
{
m_fCaption.CreateFontIndirect(&lf);
}
if (StringToLogFont(ini.GetValue(L"fonts", L"ButtonFont"), lf))
{
m_fBtn.CreateFontIndirect(&lf);
}
m_msgBoxView.m_fText = m_fText;
m_msgBoxView.m_fCaption = m_fCaption;
m_msgBoxView.m_fBtn = m_fBtn;
//sounds
m_szDefaultSound = ini.GetValue(L"sounds", L"DefaultSound" );
m_szErrorSound = ini.GetValue(L"sounds", L"ErrorSound" );
m_szWarningSound = ini.GetValue(L"sounds", L"WarningSound" );
m_szInfoSound = ini.GetValue(L"sounds", L"InfoSound" );
m_szQuestionSound = ini.GetValue(L"sounds", L"QuestionSound" );
//general options
LPCWSTR lpwszCenterCaption = ini.GetValue(L"general", L"CenterCaption");
if (lstrcmpi(lpwszCenterCaption, L"true") == 0)
m_msgBoxView.m_bCenterCaption = TRUE;
else
m_msgBoxView.m_bCenterCaption = FALSE;
// list of excluded apps
LoadExclusionList(m_excludedApps, L"Software\\FingerMsgbox");
LoadWndExclusionList(m_excludedWnds, L"Software\\FingerMsgbox");
}
public:
static HRESULT ActivatePreviousInstance(HINSTANCE hInstance)
{
const TCHAR* pszMutex = L"FINGERMSGBOXMUTEX";
const TCHAR* pszClass = L"FINGER_MSGBOX";
const DWORD dRetryInterval = 100;
const int iMaxRetries = 25;
for(int i = 0; i < iMaxRetries; ++i)
{
HANDLE hMutex = CreateMutex(NULL, FALSE, pszMutex);
DWORD dw = GetLastError();
if(hMutex == NULL)
{
HRESULT hr = (dw == ERROR_INVALID_HANDLE) ? E_INVALIDARG : E_FAIL;
return hr;
}
if(dw == ERROR_ALREADY_EXISTS)
{
CloseHandle(hMutex);
HWND hwnd = FindWindow(pszClass, NULL);
if(hwnd == NULL)
{
Sleep(dRetryInterval);
continue;
}
else
{
if(SetForegroundWindow(reinterpret_cast<HWND>(reinterpret_cast<ULONG>(hwnd) | 0x1)) != 0)
{
return S_FALSE;
}
}
}
else
{
return S_OK;
}
}
return S_OK;
}
void SwitchToMsgBoxView()
{
m_hWndClient = m_msgBoxView;
m_aboutView.ShowWindow(SW_HIDE);
m_aboutView.SetWindowLongPtr(GWL_ID, 0);
m_msgBoxView.ShowWindow(SW_SHOW);
m_msgBoxView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_msgBoxView.SetFocus();
}
void SwitchToAboutView()
{
m_hWndClient = m_aboutView;
m_msgBoxView.ShowWindow(SW_HIDE);
m_msgBoxView.SetWindowLongPtr(GWL_ID, 0);
m_aboutView.ShowWindow(SW_SHOW);
m_aboutView.SetWindowLongPtr(GWL_ID, ATL_IDW_PANE_FIRST);
m_aboutView.SetFocus();
UpdateLayout();
}
void PlayMessageBoxSound(int uType)
{
if (!(IsEvtSoundActive()))
return;
CString fileName;
if ((uType & MB_ICONEXCLAMATION) || (uType & MB_ICONWARNING))
{
fileName = m_szWarningSound;
goto soundend;
}
if ((uType & MB_ICONINFORMATION) || (uType & MB_ICONASTERISK))
{
fileName = m_szInfoSound;
goto soundend;
}
if (uType & MB_ICONQUESTION)
{
fileName = m_szQuestionSound;
goto soundend;
}
if ((uType & MB_ICONSTOP) || (uType & MB_ICONERROR) || (uType & MB_ICONHAND))
{
fileName = m_szErrorSound;
goto soundend;
}
soundend:
if (fileName.IsEmpty())
fileName = m_szDefaultSound;
PlaySound(fileName, NULL, SND_ASYNC | SND_FILENAME | SND_NODEFAULT);
}
protected:
HWND m_hForeWnd;
CxImage m_imgBkg;
BOOL m_bDisabledTransp;
COLORREF m_clNoTranspBackground;
DWORD m_iTransp;
CSimpleArray<CString, CStringEqualHelper<CString>> m_excludedApps;
CSimpleArray<CString, CStringEqualHelper<CString>> m_excludedWnds;
BOOL m_bDisabled;
CMenu m_menuConfig;
CFontHandle m_fText;
CFontHandle m_fCaption;
CFontHandle m_fBtn;
CString m_szDefaultSound;
CString m_szErrorSound;
CString m_szWarningSound;
CString m_szInfoSound;
CString m_szQuestionSound;
private:
BOOL IsEvtSoundActive()
{
BOOL bRes = TRUE;
DWORD dwMute = 0;
HRESULT hr = RegistryGetDWORD(HKEY_CURRENT_USER, L"ControlPanel\\Volume", L"Mute", &dwMute);
if (SUCCEEDED(hr))
{
if ( ! (dwMute & MASK_EVENTMUTE) )
bRes = FALSE;
}
return bRes;
}
};
<file_sep>/7-Zip/CPP/7zip/Compress/PpmdEncoder.cpp
// PpmdEncoder.cpp
// 2009-05-30 : <NAME> : Public domain
#include "StdAfx.h"
// #include <fstream.h>
// #include <iomanip.h>
#include "../Common/StreamUtils.h"
#include "PpmdEncoder.h"
namespace NCompress {
namespace NPpmd {
const UInt32 kMinMemSize = (1 << 11);
const UInt32 kMinOrder = 2;
/*
UInt32 g_NumInner = 0;
UInt32 g_InnerCycles = 0;
UInt32 g_Encode2 = 0;
UInt32 g_Encode2Cycles = 0;
UInt32 g_Encode2Cycles2 = 0;
class CCounter
{
public:
CCounter() {}
~CCounter()
{
ofstream ofs("Res.dat");
ofs << "innerEncode1 = " << setw(10) << g_NumInner << endl;
ofs << "g_InnerCycles = " << setw(10) << g_InnerCycles << endl;
ofs << "g_Encode2 = " << setw(10) << g_Encode2 << endl;
ofs << "g_Encode2Cycles = " << setw(10) << g_Encode2Cycles << endl;
ofs << "g_Encode2Cycles2= " << setw(10) << g_Encode2Cycles2 << endl;
}
};
CCounter g_Counter;
*/
STDMETHODIMP CEncoder::SetCoderProperties(const PROPID *propIDs, const PROPVARIANT *props, UInt32 numProps)
{
for (UInt32 i = 0; i < numProps; i++)
{
const PROPVARIANT &prop = props[i];
switch(propIDs[i])
{
case NCoderPropID::kUsedMemorySize:
if (prop.vt != VT_UI4)
return E_INVALIDARG;
if (prop.ulVal < kMinMemSize || prop.ulVal > kMaxMemBlockSize)
return E_INVALIDARG;
_usedMemorySize = (UInt32)prop.ulVal;
break;
case NCoderPropID::kOrder:
if (prop.vt != VT_UI4)
return E_INVALIDARG;
if (prop.ulVal < kMinOrder || prop.ulVal > kMaxOrderCompress)
return E_INVALIDARG;
_order = (Byte)prop.ulVal;
break;
default:
return E_INVALIDARG;
}
}
return S_OK;
}
STDMETHODIMP CEncoder::WriteCoderProperties(ISequentialOutStream *outStream)
{
const UInt32 kPropSize = 5;
Byte props[kPropSize];
props[0] = _order;
for (int i = 0; i < 4; i++)
props[1 + i] = Byte(_usedMemorySize >> (8 * i));
return WriteStream(outStream, props, kPropSize);
}
const UInt32 kUsedMemorySizeDefault = (1 << 24);
const int kOrderDefault = 6;
CEncoder::CEncoder():
_usedMemorySize(kUsedMemorySizeDefault),
_order(kOrderDefault)
{
}
HRESULT CEncoder::CodeReal(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 * /* inSize */, const UInt64 * /* outSize */, ICompressProgressInfo *progress)
{
if (!_inStream.Create(1 << 20))
return E_OUTOFMEMORY;
if (!_rangeEncoder.Create(1 << 20))
return E_OUTOFMEMORY;
if (!_info.SubAllocator.StartSubAllocator(_usedMemorySize))
return E_OUTOFMEMORY;
_inStream.SetStream(inStream);
_inStream.Init();
_rangeEncoder.SetStream(outStream);
_rangeEncoder.Init();
CEncoderFlusher flusher(this);
_info.MaxOrder = 0;
_info.StartModelRare(_order);
for (;;)
{
UInt32 size = (1 << 18);
do
{
Byte symbol;
if (!_inStream.ReadByte(symbol))
{
// here we can write End Mark for stream version.
// In current version this feature is not used.
// _info.EncodeSymbol(-1, &_rangeEncoder);
return S_OK;
}
_info.EncodeSymbol(symbol, &_rangeEncoder);
}
while (--size != 0);
if (progress != NULL)
{
UInt64 inSize = _inStream.GetProcessedSize();
UInt64 outSize = _rangeEncoder.GetProcessedSize();
RINOK(progress->SetRatioInfo(&inSize, &outSize));
}
}
}
STDMETHODIMP CEncoder::Code(ISequentialInStream *inStream, ISequentialOutStream *outStream,
const UInt64 *inSize, const UInt64 *outSize, ICompressProgressInfo *progress)
{
try { return CodeReal(inStream, outStream, inSize, outSize, progress); }
catch(const COutBufferException &e) { return e.ErrorCode; }
catch(const CInBufferException &e) { return e.ErrorCode; }
catch(...) { return E_FAIL; }
}
}}
<file_sep>/FingerSuite/Common/utils.h
#ifndef UTILS_H
#define UTILS_H
#pragma once
//#include "resource.h"
#include <snapi.h>
#include <regext.h>
#include "log\logger.h"
#ifndef __ATLMISC_H__
#error utils.h requires atlmisc.h to be included first
#endif
template <class T>
class CStringEqualHelper
{
public:
static bool IsEqual(const T& t1, const T& t2)
{
if (t1.Compare(t2) == 0)
return true;
else
return false;
}
};
//#ifdef __cplusplus
//extern "C" {
//#endif
inline CString ErrorString(DWORD err)
{
CString Error;
LPTSTR s;
if(::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
err,
0,
(LPTSTR)&s,
0,
NULL) == 0)
{ /* failed */
// Unknown error code %08x (%d)
CString fmt = L"Unknown error 0x%08x (%d)\n";
CString t;
t.Format(fmt, err, LOWORD(err));
Error = t;
} /* failed */
else
{ /* success */
LPTSTR p = _tcschr(s, _T('\r'));
if(p != NULL)
{ /* lose CRLF */
*p = _T('\0');
} /* lose CRLF */
Error = s;
::LocalFree(s);
} /* success */
return Error;
} // ErrorString
inline HBITMAP LoadImageFile( LPCTSTR szFileName )
{
CString szImage = szFileName;
CBitmapHandle hBmp = szImage.Find( L".bmp") != -1 ?
::SHLoadDIBitmap( szFileName) : ::SHLoadImageFile( szFileName);
if( hBmp.IsNull())
{
wprintf(L"Cannot load image from: %s\n", szFileName);
}
return hBmp;
}
inline int ParseTokens( CSimpleArray<CString>& result, CString szString, CString szTokens = ",;" )
{
int iNum = 0;
int iCurrPos= 0;
CString subString;
while( -1 != ( iCurrPos = szString.FindOneOf( szTokens ) ) )
{
iNum++;
result.Add( szString.Left( iCurrPos ) );
szString = szString.Right( szString.GetLength() - iCurrPos - 1 );
}
if ( szString.GetLength() > 0 )
{
// the last one...
iNum++;
result.Add( szString );
}
return iNum;
}
inline void DrawTransparent(HDC hdc, int x, int y, HBITMAP
hBitmap, COLORREF crColour)
{
COLORREF crOldBack = SetBkColor(hdc, RGB(255, 255, 255));
COLORREF crOldText = SetTextColor(hdc, RGB(0, 0, 0));
HDC dcImage, dcTrans;
// Create two memory dcs for the image and the mask
dcImage=CreateCompatibleDC(hdc);
dcTrans=CreateCompatibleDC(hdc);
// Select the image into the appropriate dc
HBITMAP pOldBitmapImage = (HBITMAP)SelectObject(dcImage, hBitmap);
// Create the mask bitmap
BITMAP bitmap;
GetObject(hBitmap, sizeof(BITMAP), &bitmap);
HBITMAP bitmapTrans=CreateBitmap(bitmap.bmWidth, bitmap.bmHeight, 1, 1, NULL);
// Select the mask bitmap into the appropriate dc
HBITMAP pOldBitmapTrans = (HBITMAP)SelectObject(dcTrans, bitmapTrans);
// Build mask based on transparent colour
SetBkColor(dcImage, crColour);
BitBlt(dcTrans, 0, 0, bitmap.bmWidth, bitmap.bmHeight, dcImage, 0, 0, SRCCOPY);
// Do the work - True Mask method - cool if not actual display
BitBlt(hdc, x, y, bitmap.bmWidth, bitmap.bmHeight, dcImage, 0, 0, SRCINVERT);
BitBlt(hdc, x, y, bitmap.bmWidth, bitmap.bmHeight, dcTrans, 0, 0, SRCAND);
BitBlt(hdc, x, y, bitmap.bmWidth, bitmap.bmHeight, dcImage, 0, 0, SRCINVERT);
// Restore settings
SelectObject(dcImage, pOldBitmapImage);
SelectObject(dcTrans, pOldBitmapTrans);
SetBkColor(hdc, crOldBack);
SetTextColor(hdc, crOldText);
}
/*
void FlipBitmap(CBitmap src)
{
CDC dc; dc.CreateCompatibleDC(NULL);
SIZE sz; src.GetSize(sz);
CBitmap oldBmp = dc.SelectBitmap(src);
dc.StretchBlt(0, 0, sz.cx, sz.cy, dc, 0, sz.cy-1, sz.cx, -sz.cy, SRCCOPY );
dc.SelectBitmap(oldBmp);
}
*/
inline BOOL RegReadDWORD(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, DWORD& dwValue)
{
BOOL bRet = TRUE;
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(hKey,
lpszSubkey,
0,
0,
&hConf))
{
DWORD dwSize = sizeof(DWORD);
DWORD dwType = REG_DWORD;
DWORD dwNewValue;
if (ERROR_SUCCESS == RegQueryValueEx(hConf,
lpszName,
NULL,
&dwType,
(LPBYTE)&dwNewValue,
&dwSize))
{
// read dword
dwValue = dwNewValue;
}
else
bRet = FALSE;
RegCloseKey(hConf);
}
else
bRet = FALSE;
return bRet;
}
inline BOOL RegReadBOOL(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, BOOL& bValue)
{
BOOL bRet = TRUE;
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(hKey,
lpszSubkey,
0,
0,
&hConf))
{
DWORD dwSize = sizeof(DWORD);
DWORD dwType = REG_DWORD;
DWORD dwNewValue;
if (ERROR_SUCCESS == RegQueryValueEx(hConf,
lpszName,
NULL,
&dwType,
(LPBYTE)&dwNewValue,
&dwSize))
{
// read dword
bValue = (BOOL)dwNewValue;
}
else
bRet = FALSE;
RegCloseKey(hConf);
}
else
bRet = FALSE;
return bRet;
}
inline BOOL RegReadColor(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, COLORREF& clValue)
{
BOOL bRet = TRUE;
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(hKey,
lpszSubkey,
0,
0,
&hConf))
{
DWORD dwSize = 50;
DWORD dwType = REG_SZ;
BYTE data[50];
ZeroMemory(data, 50);
if (ERROR_SUCCESS == RegQueryValueEx(hConf,
lpszName,
NULL,
&dwType,
data,
&dwSize))
{
// read sz
CString value = (WCHAR *)data;
CSimpleArray<CString> colors;
int n = ParseTokens(colors, value, " ");
if (n == 3)
{
int r = _wtoi( colors[0] );
int g = _wtoi( colors[1] );
int b = _wtoi( colors[2] );
clValue = RGB(r,g,b);
}
}
else
bRet = FALSE;
RegCloseKey(hConf);
}
else
bRet = FALSE;
return bRet;
}
inline BOOL RegReadString(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, LPWSTR szValue)
{
BOOL bRet = TRUE;
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(hKey,
lpszSubkey,
0,
0,
&hConf))
{
DWORD dwSize = MAX_PATH * 2;
DWORD dwType = REG_SZ;
BYTE data[MAX_PATH * 2];
ZeroMemory(data, MAX_PATH * 2);
if (ERROR_SUCCESS == RegQueryValueEx(hConf,
lpszName,
NULL,
&dwType,
data,
&dwSize))
{
// read sz
lstrcpy(szValue, (WCHAR *)data);
}
else
bRet = FALSE;
RegCloseKey(hConf);
}
else
bRet = FALSE;
return bRet;
}
inline void RegWriteColor(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, COLORREF clValue)
{
HKEY hConf;
DWORD dwOptions = REG_OPTION_NON_VOLATILE;
DWORD dwDisposition;
if (ERROR_SUCCESS == RegCreateKeyEx(hKey, lpszSubkey, 0, NULL, dwOptions, 0, NULL, &hConf, &dwDisposition))
{
WCHAR buf[30];
DWORD dwWrittenChar = wsprintf(buf, L"%d %d %d", GetRValue(clValue), GetGValue(clValue), GetBValue(clValue)) + 1;
DWORD dwType = REG_SZ;
RegSetValueEx(hConf, lpszName, 0, dwType, (BYTE*)buf, dwWrittenChar * sizeof(WCHAR));
RegCloseKey(hConf);
}
}
inline void RegWriteBOOL(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, BOOL bValue)
{
HKEY hConf;
DWORD dwOptions = REG_OPTION_NON_VOLATILE;
DWORD dwDisposition;
if (ERROR_SUCCESS == RegCreateKeyEx(hKey, lpszSubkey, 0, NULL, dwOptions, 0, NULL, &hConf, &dwDisposition))
{
DWORD dwType = REG_DWORD;
DWORD dwVal = (DWORD)bValue;
RegSetValueEx(hConf, lpszName, 0, dwType, (CONST BYTE*)&dwVal, sizeof(DWORD));
RegCloseKey(hConf);
}
}
inline void RegWriteDWORD(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, DWORD dwVal)
{
HKEY hConf;
DWORD dwOptions = REG_OPTION_NON_VOLATILE;
DWORD dwDisposition;
if (ERROR_SUCCESS == RegCreateKeyEx(hKey, lpszSubkey, 0, NULL, dwOptions, 0, NULL, &hConf, &dwDisposition))
{
DWORD dwType = REG_DWORD;
RegSetValueEx(hConf, lpszName, 0, dwType, (CONST BYTE*)&dwVal, sizeof(DWORD));
RegCloseKey(hConf);
}
}
inline void RegWriteString(HKEY hKey, LPCTSTR lpszSubkey, LPCTSTR lpszName, LPCTSTR lpszValue, DWORD dwLength)
{
HKEY hConf;
DWORD dwOptions = REG_OPTION_NON_VOLATILE;
DWORD dwDisposition;
if (ERROR_SUCCESS == RegCreateKeyEx(hKey, lpszSubkey, 0, NULL, dwOptions, 0, NULL, &hConf, &dwDisposition))
{
DWORD dwType = REG_SZ;
RegSetValueEx(hConf, lpszName, 0, dwType, (BYTE*)lpszValue, (dwLength + 1) * sizeof(WCHAR));
RegCloseKey(hConf);
}
}
inline void LoadExclusionList(CSimpleArray<CString, CStringEqualHelper<CString>> &list, LPTSTR pszKey)
{
list.RemoveAll();
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
pszKey, // L"Software\\FingerMenu",
0,
0,
&hConf))
{
long lRes;
DWORD dwIndex = -1;
CString szProcessName;
CString szValueName;
do
{
WCHAR valueName[1024];
DWORD cchValueName = 1024;
BYTE data[1024];
DWORD dwSize = 1024;
DWORD dwType = REG_SZ;
ZeroMemory(data, sizeof(data));
ZeroMemory(valueName, sizeof(valueName));
dwIndex ++;
if (ERROR_SUCCESS == (lRes = RegEnumValue(hConf,
dwIndex,
valueName,
&cchValueName,
NULL,
&dwType,
data,
&dwSize) ))
{
szValueName = valueName;
szProcessName = (PWCHAR)data;
if ((dwType == REG_SZ) && (szValueName.Find(L"ExcludedApp", 0) == 0))
{
list.Add(szProcessName);
}
}
} while (lRes == ERROR_SUCCESS);
}
}
inline void SaveExclusionList(CSimpleArray<CString, CStringEqualHelper<CString>> &list, LPTSTR pszKey)
{
//WCHAR szKeyName[] = L"Software\\FingerMenu";
// delete all registry key
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
pszKey,
0,
0,
&hConf))
{
for (int i = 0; i < 200; i++)
{
CString name; name.Format(L"ExcludedApp%02d", i);
RegDeleteValue(hConf, name);
}
RegCloseKey(hConf);
}
for (int i = 0; i < list.GetSize(); i++)
{
CString name; name.Format(L"ExcludedApp%02d", i);
RegWriteString(HKEY_LOCAL_MACHINE, pszKey, name, list[i], list[i].GetLength());
}
}
inline void LoadWndExclusionList(CSimpleArray<CString, CStringEqualHelper<CString>> &list, LPTSTR pszKey)
{
list.RemoveAll();
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
pszKey, // L"Software\\FingerMenu",
0,
0,
&hConf))
{
long lRes;
DWORD dwIndex = -1;
CString szProcessName;
CString szValueName;
do
{
WCHAR valueName[1024];
DWORD cchValueName = 1024;
BYTE data[1024];
DWORD dwSize = 1024;
DWORD dwType = REG_SZ;
ZeroMemory(data, sizeof(data));
ZeroMemory(valueName, sizeof(valueName));
dwIndex ++;
if (ERROR_SUCCESS == (lRes = RegEnumValue(hConf,
dwIndex,
valueName,
&cchValueName,
NULL,
&dwType,
data,
&dwSize) ))
{
szValueName = valueName;
szProcessName = (PWCHAR)data;
if ((dwType == REG_SZ) && (szValueName.Find(L"ExcludedWnd", 0) == 0))
{
list.Add(szProcessName);
}
}
} while (lRes == ERROR_SUCCESS);
}
}
inline void SaveWndExclusionList(CSimpleArray<CString, CStringEqualHelper<CString>> &list, LPTSTR pszKey)
{
//WCHAR szKeyName[] = L"Software\\FingerMenu";
// delete all registry key
HKEY hConf;
if (ERROR_SUCCESS == RegOpenKeyEx(HKEY_LOCAL_MACHINE,
pszKey,
0,
0,
&hConf))
{
for (int i = 0; i < 200; i++)
{
CString name; name.Format(L"ExcludedWnd%02d", i);
RegDeleteValue(hConf, name);
}
RegCloseKey(hConf);
}
for (int i = 0; i < list.GetSize(); i++)
{
CString name; name.Format(L"ExcludedWnd%02d", i);
RegWriteString(HKEY_LOCAL_MACHINE, pszKey, name, list[i], list[i].GetLength());
}
}
inline void SplitString(CString Source, CString Deliminator, CSimpleArray<CString>& AddIt, BOOL bAddEmpty)
{
// initialize the variables
CString newCString = Source;
CString tmpCString = "";
CString AddCString = "";
int pos1 = 0;
int pos = 0;
if (Deliminator.IsEmpty()) {
// Add default [comma] if empty!
// acknowledgement: <NAME> [<EMAIL>]
Deliminator = ",";
}
// do this loop as long as you have a deliminator
do {
// set to zero
pos1 = 0;
// position of deliminator starting at pos1 (0)
pos = newCString.Find(Deliminator, pos1);
// if the deliminator is found...
if ( pos != -1 ) {
// load a new var with the info left
// of the position
CString AddCString = newCString.Left(pos);
if (!AddCString.IsEmpty()) {
// if there is a string to add, then
// add it to the Array
AddIt.Add(AddCString);
}
else if (bAddEmpty) {
// if empty strings are ok, then add them
AddIt.Add(AddCString);
}
// make a copy of the of this var. with the info
// right of the deliminator
tmpCString = newCString.Mid(pos + Deliminator.GetLength());
// reset this var with new info
newCString = tmpCString;
}
} while ( pos != -1 );
if (!newCString.IsEmpty()) {
// as long as the variable is not emty, add it
AddIt.Add(newCString);
}
}
inline BOOL StringRGBToColor(LPCTSTR lpszColor, COLORREF &clValue)
{
BOOL bRet = FALSE;
if (lpszColor == NULL)
return FALSE;
CString value = lpszColor;
CSimpleArray<CString> colors;
int n = ParseTokens(colors, value, " ");
if (n == 3)
{
int r = _wtoi( colors[0] );
int g = _wtoi( colors[1] );
int b = _wtoi( colors[2] );
bRet = TRUE;
clValue = RGB(r,g,b);
}
return bRet;
}
inline BOOL StringToLogFont(LPCTSTR lpszFont, LOGFONT &lf)
{
//HDC hDC = ::GetDC(0);
BOOL bRet = TRUE;
CDCHandle dc(::GetDC(0));
CFont font = dc.GetCurrentFont();
font.GetLogFont(lf);
if (lpszFont == NULL)
{
return bRet;
}
CString value = lpszFont;
CSimpleArray<CString> values;
int n = ParseTokens(values, value, ",");
//ZeroMemory(&lf, sizeof(LOGFONT));
if (n >= 1)
{
// weight
if (lstrcmpi(values[0], L"regular") == 0)
lf.lfWeight = FW_NORMAL;
if (lstrcmpi(values[0], L"italic") == 0)
{
lf.lfWeight = FW_NORMAL;
lf.lfItalic = TRUE;
}
if (lstrcmpi(values[0], L"bold") == 0)
lf.lfWeight = FW_BOLD;
if (lstrcmpi(values[0], L"bold italic") == 0)
{
lf.lfWeight = FW_BOLD;
lf.lfItalic = TRUE;
}
}
if (n >= 2)
{
// height
values[1].Replace(L"p", L" ");
int l = _wtoi(values[1]);
if (l > 0)
{
lf.lfHeight = -::MulDiv(l, dc.GetDeviceCaps(LOGPIXELSY), 72);
}
}
// face
if (n >= 3)
{
ZeroMemory(lf.lfFaceName, LF_FACESIZE);
lstrcpy(lf.lfFaceName, values[2]);
}
// charset
/*
if (lstrcmpi(values[3], L"ansi" ) == 0) lf.lfCharSet = ANSI_CHARSET;
if (lstrcmpi(values[3], L"baltic" ) == 0) lf.lfCharSet = BALTIC_CHARSET;
if (lstrcmpi(values[3], L"chinesebig5" ) == 0) lf.lfCharSet = CHINESEBIG5_CHARSET;
if (lstrcmpi(values[3], L"default" ) == 0) lf.lfCharSet = DEFAULT_CHARSET;
if (lstrcmpi(values[3], L"easteurope" ) == 0) lf.lfCharSet = EASTEUROPE_CHARSET;
if (lstrcmpi(values[3], L"gb2312" ) == 0) lf.lfCharSet = GB2312_CHARSET;
if (lstrcmpi(values[3], L"greek" ) == 0) lf.lfCharSet = GREEK_CHARSET;
if (lstrcmpi(values[3], L"hangul" ) == 0) lf.lfCharSet = HANGUL_CHARSET;
if (lstrcmpi(values[3], L"mac" ) == 0) lf.lfCharSet = MAC_CHARSET;
if (lstrcmpi(values[3], L"oem" ) == 0) lf.lfCharSet = OEM_CHARSET;
if (lstrcmpi(values[3], L"russian" ) == 0) lf.lfCharSet = RUSSIAN_CHARSET;
if (lstrcmpi(values[3], L"shiftjis" ) == 0) lf.lfCharSet = SHIFTJIS_CHARSET;
if (lstrcmpi(values[3], L"symbol" ) == 0) lf.lfCharSet = SYMBOL_CHARSET;
if (lstrcmpi(values[3], L"turkish" ) == 0) lf.lfCharSet = TURKISH_CHARSET;
if (lstrcmpi(values[3], L"johab" ) == 0) lf.lfCharSet = JOHAB_CHARSET;
if (lstrcmpi(values[3], L"hebrew" ) == 0) lf.lfCharSet = HEBREW_CHARSET;
if (lstrcmpi(values[3], L"arabic" ) == 0) lf.lfCharSet = ARABIC_CHARSET;
if (lstrcmpi(values[3], L"thai" ) == 0) lf.lfCharSet = THAI_CHARSET;
*/
return bRet;
}
inline LPWSTR LoadResourceString(UINT uID)
{
LPWSTR lpOutput = new WCHAR[50];
ZeroMemory(lpOutput, 50);
int nCharCopied = ::LoadString(ModuleHelper::GetResourceInstance(), uID, lpOutput, 50);
if (nCharCopied == 0)
return NULL;
return lpOutput;
}
inline BOOL IsDeviceLocked()
{
BOOL bRes = FALSE;
DWORD dwLockState = 0;
RegistryGetDWORD(SN_LOCK_ROOT, SN_LOCK_PATH, SN_LOCK_VALUE, &dwLockState);
if (dwLockState & SN_LOCK_BITMASK_KEYLOCKED)
bRes = TRUE;
return bRes;
}
// remote message
inline LPVOID PrepareRemoteMessage(LPHANDLE lphFile, DWORD dwBufferSize)
{
LPVOID pViewMMFFile = NULL;
*lphFile = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwBufferSize + 1, L"SENDMESSAGEFILEMAP");
if ( *lphFile )
{
pViewMMFFile = MapViewOfFile(*lphFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
return pViewMMFFile;
}
inline void CloseRemoteMessage(HANDLE hFile, LPVOID pView)
{
UnmapViewOfFile(pView);
CloseHandle(hFile);
}
inline LRESULT SendMessageRemote(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, DWORD dwLParamSize = 0, UINT uTimeout = 0)
{
LRESULT lResult = 0;
DWORD dwResult;
if (dwLParamSize == 0)
{
if (uTimeout == 0)
lResult = ::SendMessage(hWnd, msg, wParam, lParam);
else
// TODO
lResult = ::SendMessageTimeout(hWnd, msg, wParam, lParam, SMTO_NORMAL, uTimeout, &dwResult);
}
else
{
HANDLE hFileMMF = NULL;
HANDLE pViewMMFFile = NULL;
hFileMMF = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwLParamSize + 1, L"SENDMESSAGEFILEMAP");
if ( hFileMMF )
{
pViewMMFFile = MapViewOfFile(hFileMMF, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
memcpy(pViewMMFFile, (LPVOID)lParam, dwLParamSize);
if (uTimeout == 0)
lResult = ::SendMessage(hWnd, msg, wParam, (LPARAM)pViewMMFFile);
else
// TODO
lResult = ::SendMessageTimeout(hWnd, msg, wParam, (LPARAM)pViewMMFFile, SMTO_NORMAL, uTimeout, &dwResult);
UnmapViewOfFile(pViewMMFFile);
CloseHandle(hFileMMF);
hFileMMF = NULL;
pViewMMFFile = NULL;
}
return lResult;
}
inline LRESULT CallRemoteWindowProc2(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam, DWORD dwLParamSize = 0)
{
LONG wndProc = ::GetWindowLong(hWnd, GWL_WNDPROC);
LRESULT lResult = 0;
if (dwLParamSize == 0)
{
lResult = ::CallWindowProc((WNDPROC)wndProc, hWnd, msg, wParam, lParam);
}
else
{
HANDLE hFileMMF = NULL;
HANDLE pViewMMFFile = NULL;
hFileMMF = ::CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, dwLParamSize + 1, L"SENDMESSAGEFILEMAP");
if ( hFileMMF )
{
pViewMMFFile = MapViewOfFile(hFileMMF, FILE_MAP_ALL_ACCESS, 0, 0, 0);
}
memcpy(pViewMMFFile, (LPVOID)lParam, dwLParamSize);
lResult = ::CallWindowProc((WNDPROC)wndProc, hWnd, msg, wParam, (LPARAM)pViewMMFFile);
UnmapViewOfFile(pViewMMFFile);
CloseHandle(hFileMMF);
}
return lResult;
}
//#ifdef __cplusplus
//}
//#endif
#endif //UTILS_H
<file_sep>/7-Zip/CPP/7zip/MyVersion.h
#define MY_VER_MAJOR 9
#define MY_VER_MINOR 10
#define MY_VER_BUILD 0
#define MY_VERSION "9.10 beta"
#define MY_7ZIP_VERSION "7-Zip 9.10 beta"
#define MY_DATE "2009-12-22"
#define MY_COPYRIGHT "Copyright (c) 1999-2009 <NAME>"
#define MY_VERSION_COPYRIGHT_DATE MY_VERSION " " MY_COPYRIGHT " " MY_DATE
<file_sep>/7-Zip/C/7zVersion.h
#define MY_VER_MAJOR 9
#define MY_VER_MINOR 10
#define MY_VER_BUILD 0
#define MY_VERSION "9.10 beta"
#define MY_DATE "2009-12-22"
#define MY_COPYRIGHT ": <NAME> : Public domain"
#define MY_VERSION_COPYRIGHT_DATE MY_VERSION " " MY_COPYRIGHT " : " MY_DATE
<file_sep>/SQLCEHelper/Source/Column.cpp
#include "stdafx.h"
using namespace OLEDBCLI;
//-------------------------------------------------------------------------
//
// CColumn class
//
//-------------------------------------------------------------------------
CColumn::CColumn()
: m_wType (DBTYPE_EMPTY),
m_ulOrdinal (0),
m_ulSize (0),
m_dwFlags (0),
m_bPrecision(0),
m_bScale (0),
m_bRowGuid (false),
m_bIdentity (false)
{
}
CColumn::CColumn(DBCOLUMNDESC* pColumnDesc, ULONG iOrdinal)
: m_wType (DBTYPE_EMPTY),
m_ulOrdinal (0),
m_ulSize (0),
m_dwFlags (0),
m_bPrecision(0),
m_bScale (0),
m_bRowGuid (false),
m_bIdentity (false)
{
ATLASSERT(pColumnDesc != NULL);
m_strName = pColumnDesc->dbcid.uName.pwszName;
m_wType = pColumnDesc->wType;
m_ulSize = pColumnDesc->ulColumnSize;
m_bPrecision = pColumnDesc->bPrecision;
m_bScale = pColumnDesc->bScale;
m_dwFlags = 0;
m_ulOrdinal = iOrdinal;
m_bRowGuid = false;
m_bIdentity = false;
m_nSeed = 0;
m_nIncrement = 0;
ParseProperties(pColumnDesc);
}
CColumn::~CColumn()
{
}
// CColumn::ParseProperties
//
// Parses the column description properties
//
void CColumn::ParseProperties(DBCOLUMNDESC* pColumnDesc)
{
ULONG cs,
cp;
DBPROPSET* pPropSet = pColumnDesc->rgPropertySets;
for(cs = 0; cs < pColumnDesc->cPropertySets; ++cs, ++pPropSet)
{
if(pPropSet->guidPropertySet == DBPROPSET_SSCE_COLUMN)
{
DBPROP* pProp = pPropSet->rgProperties;
for(cp = 0; cp < pPropSet->cProperties; ++cp, ++pProp)
{
if(pProp->dwPropertyID == DBPROP_SSCE2_COL_ROWGUID ||
pProp->dwPropertyID == DBPROP_SSCE3_COL_ROWGUID)
m_bRowGuid = (pProp->vValue.boolVal == VARIANT_TRUE);
}
}
if(pPropSet->guidPropertySet == DBPROPSET_COLUMN)
{
DBPROP* pProp = pPropSet->rgProperties;
for(cp = 0; cp < pPropSet->cProperties; ++cp, ++pProp)
{
switch(pProp->dwPropertyID)
{
case DBPROP_COL_DEFAULT:
{
VARIANT varStr;
HRESULT hr;
VariantInit(&varStr);
hr = VariantChangeType(&varStr, &pProp->vValue, 0, VT_BSTR);
if(SUCCEEDED(hr))
m_strDefault = (LPCTSTR)varStr.bstrVal;
else
m_strDefault = _T("VariantChangeType failed.");
VariantClear(&varStr);
}
break;
case DBPROP_COL_AUTOINCREMENT:
m_bIdentity = (pProp->vValue.boolVal == VARIANT_TRUE);
break;
case DBPROP_COL_SEED:
m_nSeed = pProp->vValue.intVal;
break;
case DBPROP_COL_INCREMENT:
m_nIncrement = pProp->vValue.intVal;
break;
case DBPROP_COL_NULLABLE:
if(pProp->vValue.boolVal == VARIANT_TRUE)
m_dwFlags |= DBCOLUMNFLAGS_ISNULLABLE;
break;
case DBPROP_COL_ISLONG:
if(pProp->vValue.boolVal == VARIANT_TRUE)
m_dwFlags |= DBCOLUMNFLAGS_ISLONG;
break;
case DBPROP_COL_FIXEDLENGTH:
if(pProp->vValue.boolVal == VARIANT_TRUE)
m_dwFlags |= DBCOLUMNFLAGS_ISFIXEDLENGTH;
break;
default:
break;
}
}
}
}
}
<file_sep>/7-Zip/CPP/7zip/Archive/PeHandler.cpp
// PeHandler.cpp
#include "StdAfx.h"
#include "../../../C/CpuArch.h"
#include "Common/DynamicBuffer.h"
#include "Common/ComTry.h"
#include "Common/IntToString.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariantUtils.h"
#include "Windows/Time.h"
#include "../Common/LimitedStreams.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamObjects.h"
#include "../Common/StreamUtils.h"
#include "../Compress/CopyCoder.h"
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
#define Get64(p) GetUi64(p)
using namespace NWindows;
namespace NArchive {
namespace NPe {
#define NUM_SCAN_SECTIONS_MAX (1 << 6)
#define PE_SIG 0x00004550
#define PE_OptHeader_Magic_32 0x10B
#define PE_OptHeader_Magic_64 0x20B
static AString GetDecString(UInt32 v)
{
char sz[32];
ConvertUInt64ToString(v, sz);
return sz;
}
struct CVersion
{
UInt16 Major;
UInt16 Minor;
void Parse(const Byte *buf);
AString GetString() const { return GetDecString(Major) + '.' + GetDecString(Minor); }
};
void CVersion::Parse(const Byte *p)
{
Major = Get16(p);
Minor = Get16(p + 2);
}
static const UInt32 kHeaderSize = 4 + 20;
struct CHeader
{
UInt16 NumSections;
UInt32 Time;
UInt32 PointerToSymbolTable;
UInt32 NumSymbols;
UInt16 OptHeaderSize;
UInt16 Flags;
UInt16 Machine;
bool Parse(const Byte *buf);
};
bool CHeader::Parse(const Byte *p)
{
if (Get32(p) != PE_SIG)
return false;
p += 4;
Machine = Get16(p + 0);
NumSections = Get16(p + 2);
Time = Get32(p + 4);
PointerToSymbolTable = Get32(p + 8);
NumSymbols = Get32(p + 12);
OptHeaderSize = Get16(p + 16);
Flags = Get16(p + 18);
return true;
}
struct CDirLink
{
UInt32 Va;
UInt32 Size;
void Parse(const Byte *p);
};
void CDirLink::Parse(const Byte *p)
{
Va = Get32(p);
Size = Get32(p + 4);
};
enum
{
kDirLink_Certificate = 4,
kDirLink_Debug = 6
};
struct CDebugEntry
{
UInt32 Flags;
UInt32 Time;
CVersion Ver;
UInt32 Type;
UInt32 Size;
UInt32 Va;
UInt32 Pa;
void Parse(const Byte *p);
};
void CDebugEntry::Parse(const Byte *p)
{
Flags = Get32(p);
Time = Get32(p + 4);
Ver.Parse(p + 8);
Type = Get32(p + 12);
Size = Get32(p + 16);
Va = Get32(p + 20);
Pa = Get32(p + 24);
}
static const UInt32 kNumDirItemsMax = 16;
struct COptHeader
{
UInt16 Magic;
Byte LinkerVerMajor;
Byte LinkerVerMinor;
UInt32 CodeSize;
UInt32 InitDataSize;
UInt32 UninitDataSize;
// UInt32 AddressOfEntryPoint;
// UInt32 BaseOfCode;
// UInt32 BaseOfData32;
// UInt64 ImageBase;
UInt32 SectAlign;
UInt32 FileAlign;
CVersion OsVer;
CVersion ImageVer;
CVersion SubsysVer;
UInt32 ImageSize;
UInt32 HeadersSize;
UInt32 CheckSum;
UInt16 SubSystem;
UInt16 DllCharacts;
UInt64 StackReserve;
UInt64 StackCommit;
UInt64 HeapReserve;
UInt64 HeapCommit;
UInt32 NumDirItems;
CDirLink DirItems[kNumDirItemsMax];
bool Is64Bit() const { return Magic == PE_OptHeader_Magic_64; }
bool Parse(const Byte *p, UInt32 size);
int GetNumFileAlignBits() const
{
for (int i = 9; i <= 16; i++)
if (((UInt32)1 << i) == FileAlign)
return i;
return -1;
}
};
bool COptHeader::Parse(const Byte *p, UInt32 size)
{
Magic = Get16(p);
switch (Magic)
{
case PE_OptHeader_Magic_32:
case PE_OptHeader_Magic_64:
break;
default:
return false;
}
LinkerVerMajor = p[2];
LinkerVerMinor = p[3];
bool hdr64 = Is64Bit();
CodeSize = Get32(p + 4);
InitDataSize = Get32(p + 8);
UninitDataSize = Get32(p + 12);
// AddressOfEntryPoint = Get32(p + 16);
// BaseOfCode = Get32(p + 20);
// BaseOfData32 = Get32(p + 24);
// ImageBase = hdr64 ? GetUi64(p + 24) :Get32(p + 28);
SectAlign = Get32(p + 32);
FileAlign = Get32(p + 36);
OsVer.Parse(p + 40);
ImageVer.Parse(p + 44);
SubsysVer.Parse(p + 48);
// reserved = Get32(p + 52);
ImageSize = Get32(p + 56);
HeadersSize = Get32(p + 60);
CheckSum = Get32(p + 64);
SubSystem = Get16(p + 68);
DllCharacts = Get16(p + 70);
if (hdr64)
{
StackReserve = Get64(p + 72);
StackCommit = Get64(p + 80);
HeapReserve = Get64(p + 88);
HeapCommit = Get64(p + 96);
}
else
{
StackReserve = Get32(p + 72);
StackCommit = Get32(p + 76);
HeapReserve = Get32(p + 80);
HeapCommit = Get32(p + 84);
}
UInt32 pos = (hdr64 ? 108 : 92);
NumDirItems = Get32(p + pos);
pos += 4;
if (pos + 8 * NumDirItems != size)
return false;
for (UInt32 i = 0; i < NumDirItems && i < kNumDirItemsMax; i++)
DirItems[i].Parse(p + pos + i * 8);
return true;
}
static const UInt32 kSectionSize = 40;
struct CSection
{
AString Name;
UInt32 VSize;
UInt32 Va;
UInt32 PSize;
UInt32 Pa;
UInt32 Flags;
UInt32 Time;
// UInt16 NumRelocs;
bool IsDebug;
bool IsRealSect;
CSection(): IsRealSect(false), IsDebug(false) {}
UInt64 GetPackSize() const { return PSize; }
void UpdateTotalSize(UInt32 &totalSize)
{
UInt32 t = Pa + PSize;
if (t > totalSize)
totalSize = t;
}
void Parse(const Byte *p);
};
static bool operator <(const CSection &a1, const CSection &a2) { return (a1.Pa < a2.Pa) || ((a1.Pa == a2.Pa) && (a1.PSize < a2.PSize)) ; }
static bool operator ==(const CSection &a1, const CSection &a2) { return (a1.Pa == a2.Pa) && (a1.PSize == a2.PSize); }
static AString GetName(const Byte *name)
{
const int kNameSize = 8;
AString res;
char *p = res.GetBuffer(kNameSize);
memcpy(p, name, kNameSize);
p[kNameSize] = 0;
res.ReleaseBuffer();
return res;
}
void CSection::Parse(const Byte *p)
{
Name = GetName(p);
VSize = Get32(p + 8);
Va = Get32(p + 12);
PSize = Get32(p + 16);
Pa = Get32(p + 20);
// NumRelocs = Get16(p + 32);
Flags = Get32(p + 36);
}
static const CUInt32PCharPair g_HeaderCharacts[] =
{
{ 1 << 1, "Executable" },
{ 1 << 13, "DLL" },
{ 1 << 8, "32-bit" },
{ 1 << 5, "LargeAddress" },
{ 1 << 0, "NoRelocs" },
{ 1 << 2, "NoLineNums" },
{ 1 << 3, "NoLocalSyms" },
{ 1 << 4, "AggressiveWsTrim" },
{ 1 << 9, "NoDebugInfo" },
{ 1 << 10, "RemovableRun" },
{ 1 << 11, "NetRun" },
{ 1 << 12, "System" },
{ 1 << 14, "UniCPU" },
{ 1 << 7, "Little-Endian" },
{ 1 << 15, "Big-Endian" }
};
static const CUInt32PCharPair g_DllCharacts[] =
{
{ 1 << 6, "Relocated" },
{ 1 << 7, "Integrity" },
{ 1 << 8, "NX-Compatible" },
{ 1 << 9, "NoIsolation" },
{ 1 << 10, "NoSEH" },
{ 1 << 11, "NoBind" },
{ 1 << 13, "WDM" },
{ 1 << 15, "TerminalServerAware" }
};
static const CUInt32PCharPair g_SectFlags[] =
{
{ 1 << 3, "NoPad" },
{ 1 << 5, "Code" },
{ 1 << 6, "InitializedData" },
{ 1 << 7, "UninitializedData" },
{ 1 << 9, "Comments" },
{ 1 << 11, "Remove" },
{ 1 << 12, "COMDAT" },
{ 1 << 15, "GP" },
{ 1 << 24, "ExtendedRelocations" },
{ 1 << 25, "Discardable" },
{ 1 << 26, "NotCached" },
{ 1 << 27, "NotPaged" },
{ 1 << 28, "Shared" },
{ 1 << 29, "Execute" },
{ 1 << 30, "Read" },
{ (UInt32)1 << 31, "Write" }
};
static const CUInt32PCharPair g_MachinePairs[] =
{
{ 0x014C, "x86" },
{ 0x0162, "MIPS-R3000" },
{ 0x0166, "MIPS-R4000" },
{ 0x0168, "MIPS-R10000" },
{ 0x0169, "MIPS-V2" },
{ 0x0184, "Alpha" },
{ 0x01A2, "SH3" },
{ 0x01A3, "SH3-DSP" },
{ 0x01A4, "SH3E" },
{ 0x01A6, "SH4" },
{ 0x01A8, "SH5" },
{ 0x01C0, "ARM" },
{ 0x01C2, "ARM-Thumb" },
{ 0x01F0, "PPC" },
{ 0x01F1, "PPC-FP" },
{ 0x0200, "IA-64" },
{ 0x0284, "Alpha-64" },
{ 0x0200, "IA-64" },
{ 0x0366, "MIPSFPU" },
{ 0x8664, "x64" },
{ 0x0EBC, "EFI" }
};
static const CUInt32PCharPair g_SubSystems[] =
{
{ 0, "Unknown" },
{ 1, "Native" },
{ 2, "Windows GUI" },
{ 3, "Windows CUI" },
{ 7, "Posix" },
{ 9, "Windows CE" },
{ 10, "EFI" },
{ 11, "EFI Boot" },
{ 12, "EFI Runtime" },
{ 13, "EFI ROM" },
{ 14, "XBOX" }
};
static const wchar_t *g_ResTypes[] =
{
NULL,
L"CURSOR",
L"BITMAP",
L"ICON",
L"MENU",
L"DIALOG",
L"STRING",
L"FONTDIR",
L"FONT",
L"ACCELERATOR",
L"RCDATA",
L"MESSAGETABLE",
L"GROUP_CURSOR",
NULL,
L"GROUP_ICON",
NULL,
L"VERSION",
L"DLGINCLUDE",
NULL,
L"PLUGPLAY",
L"VXD",
L"ANICURSOR",
L"ANIICON",
L"HTML",
L"MANIFEST"
};
const UInt32 kFlag = (UInt32)1 << 31;
const UInt32 kMask = ~kFlag;
struct CTableItem
{
UInt32 Offset;
UInt32 ID;
};
const UInt32 kBmpHeaderSize = 14;
const UInt32 kIconHeaderSize = 22;
struct CResItem
{
UInt32 Type;
UInt32 ID;
UInt32 Lang;
UInt32 Size;
UInt32 Offset;
UInt32 HeaderSize;
Byte Header[kIconHeaderSize]; // it must be enough for max size header.
bool Enabled;
bool IsNameEqual(const CResItem &item) const { return Lang == item.Lang; }
UInt32 GetSize() const { return Size + HeaderSize; }
bool IsBmp() const { return Type == 2; }
bool IsIcon() const { return Type == 3; }
bool IsString() const { return Type == 6; }
};
struct CStringItem
{
UInt32 Lang;
UInt32 Size;
CByteDynamicBuffer Buf;
void AddChar(Byte c);
void AddWChar(UInt16 c);
};
void CStringItem::AddChar(Byte c)
{
Buf.EnsureCapacity(Size + 2);
Buf[Size++] = c;
Buf[Size++] = 0;
}
void CStringItem::AddWChar(UInt16 c)
{
if (c == '\n')
{
AddChar('\\');
c = 'n';
}
Buf.EnsureCapacity(Size + 2);
SetUi16(Buf + Size, c);
Size += 2;
}
struct CMixItem
{
int SectionIndex;
int ResourceIndex;
int StringIndex;
bool IsSectionItem() const { return ResourceIndex < 0 && StringIndex < 0; };
};
struct CUsedBitmap
{
CByteBuffer Buf;
public:
void Alloc(size_t size)
{
size = (size + 7) / 8;
Buf.SetCapacity(size);
memset(Buf, 0, size);
}
void Free()
{
Buf.SetCapacity(0);
}
bool SetRange(size_t from, int size)
{
for (int i = 0; i < size; i++)
{
size_t pos = (from + i) >> 3;
Byte mask = (Byte)(1 << ((from + i) & 7));
Byte b = Buf[pos];
if ((b & mask) != 0)
return false;
Buf[pos] = b | mask;
}
return true;
}
};
class CHandler:
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp
{
CMyComPtr<IInStream> _stream;
CObjectVector<CSection> _sections;
UInt32 _peOffset;
CHeader _header;
COptHeader _optHeader;
UInt32 _totalSize;
UInt32 _totalSizeLimited;
CRecordVector<CResItem> _items;
CObjectVector<CStringItem> _strings;
CByteBuffer _buf;
bool _oneLang;
UString _resourceFileName;
CUsedBitmap _usedRes;
bool _parseResources;
CRecordVector<CMixItem> _mixItems;
HRESULT LoadDebugSections(IInStream *stream, bool &thereIsSection);
HRESULT Open2(IInStream *stream, IArchiveOpenCallback *callback);
bool Parse(const Byte *buf, UInt32 size);
void AddResNameToString(UString &s, UInt32 id) const;
UString GetLangPrefix(UInt32 lang);
HRESULT ReadString(UInt32 offset, UString &dest) const;
HRESULT ReadTable(UInt32 offset, CRecordVector<CTableItem> &items);
bool ParseStringRes(UInt32 id, UInt32 lang, const Byte *src, UInt32 size);
HRESULT OpenResources(int sectIndex, IInStream *stream, IArchiveOpenCallback *callback);
void CloseResources();
bool CheckItem(const CSection §, const CResItem &item, size_t offset) const
{
return item.Offset >= sect.Va && offset <= _buf.GetCapacity() && _buf.GetCapacity() - offset >= item.Size;
}
public:
MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};
bool CHandler::Parse(const Byte *buf, UInt32 size)
{
UInt32 i;
if (size < 512)
return false;
_peOffset = Get32(buf + 0x3C);
if (_peOffset >= 0x1000 || _peOffset + 512 > size || (_peOffset & 7) != 0)
return false;
UInt32 pos = _peOffset;
if (!_header.Parse(buf + pos))
return false;
if (_header.OptHeaderSize > 512 || _header.NumSections > NUM_SCAN_SECTIONS_MAX)
return false;
pos += kHeaderSize;
if (!_optHeader.Parse(buf + pos, _header.OptHeaderSize))
return false;
pos += _header.OptHeaderSize;
_totalSize = pos;
for (i = 0; i < _header.NumSections; i++, pos += kSectionSize)
{
CSection sect;
if (pos + kSectionSize > size)
return false;
sect.Parse(buf + pos);
sect.IsRealSect = true;
sect.UpdateTotalSize(_totalSize);
_sections.Add(sect);
}
return true;
}
enum
{
kpidSectAlign = kpidUserDefined,
kpidFileAlign,
kpidLinkerVer,
kpidOsVer,
kpidImageVer,
kpidSubsysVer,
kpidCodeSize,
kpidImageSize,
kpidInitDataSize,
kpidUnInitDataSize,
kpidHeadersSizeUnInitDataSize,
kpidSubSystem,
kpidDllCharacts,
kpidStackReserve,
kpidStackCommit,
kpidHeapReserve,
kpidHeapCommit,
};
STATPROPSTG kArcProps[] =
{
{ NULL, kpidCpu, VT_BSTR},
{ NULL, kpidBit64, VT_BOOL},
{ NULL, kpidCharacts, VT_BSTR},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidPhySize, VT_UI4},
{ NULL, kpidHeadersSize, VT_UI4},
{ NULL, kpidChecksum, VT_UI4},
{ L"Image Size", kpidImageSize, VT_UI4},
{ L"Section Alignment", kpidSectAlign, VT_UI4},
{ L"File Alignment", kpidFileAlign, VT_UI4},
{ L"Code Size", kpidCodeSize, VT_UI4},
{ L"Initialized Data Size", kpidInitDataSize, VT_UI4},
{ L"Uninitialized Data Size", kpidUnInitDataSize, VT_UI4},
{ L"Linker Version", kpidLinkerVer, VT_BSTR},
{ L"OS Version", kpidOsVer, VT_BSTR},
{ L"Image Version", kpidImageVer, VT_BSTR},
{ L"Subsystem Version", kpidSubsysVer, VT_BSTR},
{ L"Subsystem", kpidSubSystem, VT_BSTR},
{ L"DLL Characteristics", kpidDllCharacts, VT_BSTR},
{ L"Stack Reserve", kpidStackReserve, VT_UI8},
{ L"Stack Commit", kpidStackCommit, VT_UI8},
{ L"Heap Reserve", kpidHeapReserve, VT_UI8},
{ L"Heap Commit", kpidHeapCommit, VT_UI8},
};
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidCharacts, VT_BSTR},
{ NULL, kpidOffset, VT_UI8},
{ NULL, kpidVa, VT_UI8}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps_WITH_NAME
static void VerToProp(const CVersion &v, NCOM::CPropVariant &prop)
{
StringToProp(v.GetString(), prop);
}
void TimeToProp(UInt32 unixTime, NCOM::CPropVariant &prop)
{
if (unixTime != 0)
{
FILETIME ft;
NTime::UnixTimeToFileTime(unixTime, ft);
prop = ft;
}
}
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
switch(propID)
{
case kpidSectAlign: prop = _optHeader.SectAlign; break;
case kpidFileAlign: prop = _optHeader.FileAlign; break;
case kpidLinkerVer:
{
CVersion v = { _optHeader.LinkerVerMajor, _optHeader.LinkerVerMinor };
VerToProp(v, prop); break;
break;
}
case kpidOsVer: VerToProp(_optHeader.OsVer, prop); break;
case kpidImageVer: VerToProp(_optHeader.ImageVer, prop); break;
case kpidSubsysVer: VerToProp(_optHeader.SubsysVer, prop); break;
case kpidCodeSize: prop = _optHeader.CodeSize; break;
case kpidInitDataSize: prop = _optHeader.InitDataSize; break;
case kpidUnInitDataSize: prop = _optHeader.UninitDataSize; break;
case kpidImageSize: prop = _optHeader.ImageSize; break;
case kpidPhySize: prop = _totalSize; break;
case kpidHeadersSize: prop = _optHeader.HeadersSize; break;
case kpidChecksum: prop = _optHeader.CheckSum; break;
case kpidCpu: PAIR_TO_PROP(g_MachinePairs, _header.Machine, prop); break;
case kpidBit64: if (_optHeader.Is64Bit()) prop = true; break;
case kpidSubSystem: PAIR_TO_PROP(g_SubSystems, _optHeader.SubSystem, prop); break;
case kpidMTime:
case kpidCTime: TimeToProp(_header.Time, prop); break;
case kpidCharacts: FLAGS_TO_PROP(g_HeaderCharacts, _header.Flags, prop); break;
case kpidDllCharacts: FLAGS_TO_PROP(g_DllCharacts, _optHeader.DllCharacts, prop); break;
case kpidStackReserve: prop = _optHeader.StackReserve; break;
case kpidStackCommit: prop = _optHeader.StackCommit; break;
case kpidHeapReserve: prop = _optHeader.HeapReserve; break;
case kpidHeapCommit: prop = _optHeader.HeapCommit; break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
void CHandler::AddResNameToString(UString &s, UInt32 id) const
{
if ((id & kFlag) != 0)
{
UString name;
if (ReadString(id & kMask, name) == S_OK)
{
if (name.IsEmpty())
s += L"[]";
else
{
if (name.Length() > 1 && name[0] == '"' && name.Back() == '"')
name = name.Mid(1, name.Length() - 2);
s += name;
}
return;
}
}
wchar_t sz[32];
ConvertUInt32ToString(id, sz);
s += sz;
}
UString CHandler::GetLangPrefix(UInt32 lang)
{
UString s = _resourceFileName;
s += WCHAR_PATH_SEPARATOR;
if (!_oneLang)
{
AddResNameToString(s, lang);
s += WCHAR_PATH_SEPARATOR;
}
return s;
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NCOM::CPropVariant prop;
const CMixItem &mixItem = _mixItems[index];
if (mixItem.StringIndex >= 0)
{
const CStringItem &item = _strings[mixItem.StringIndex];
switch(propID)
{
case kpidPath: prop = GetLangPrefix(item.Lang) + L"string.txt"; break;
case kpidSize:
case kpidPackSize:
prop = (UInt64)item.Size; break;
}
}
else if (mixItem.ResourceIndex < 0)
{
const CSection &item = _sections[mixItem.SectionIndex];
switch(propID)
{
case kpidPath: StringToProp(item.Name, prop); break;
case kpidSize: prop = (UInt64)item.VSize; break;
case kpidPackSize: prop = (UInt64)item.GetPackSize(); break;
case kpidOffset: prop = item.Pa; break;
case kpidVa: if (item.IsRealSect) prop = item.Va; break;
case kpidMTime:
case kpidCTime:
TimeToProp(item.IsDebug ? item.Time : _header.Time, prop); break;
case kpidCharacts: if (item.IsRealSect) FLAGS_TO_PROP(g_SectFlags, item.Flags, prop); break;
}
}
else
{
const CResItem &item = _items[mixItem.ResourceIndex];
switch(propID)
{
case kpidPath:
{
UString s = GetLangPrefix(item.Lang);
{
const wchar_t *p = NULL;
if (item.Type < sizeof(g_ResTypes) / sizeof(g_ResTypes[0]))
p = g_ResTypes[item.Type];
if (p != 0)
s += p;
else
AddResNameToString(s, item.Type);
}
s += WCHAR_PATH_SEPARATOR;
AddResNameToString(s, item.ID);
if (item.HeaderSize != 0)
{
if (item.IsBmp())
s += L".bmp";
else if (item.IsIcon())
s += L".ico";
}
prop = s;
break;
}
case kpidSize: prop = (UInt64)item.GetSize(); break;
case kpidPackSize: prop = (UInt64)item.Size; break;
}
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
HRESULT CHandler::LoadDebugSections(IInStream *stream, bool &thereIsSection)
{
thereIsSection = false;
const CDirLink &debugLink = _optHeader.DirItems[kDirLink_Debug];
if (debugLink.Size == 0)
return S_OK;
const unsigned kEntrySize = 28;
UInt32 numItems = debugLink.Size / kEntrySize;
if (numItems * kEntrySize != debugLink.Size || numItems > 16)
return S_FALSE;
UInt64 pa = 0;
int i;
for (i = 0; i < _sections.Size(); i++)
{
const CSection § = _sections[i];
if (sect.Va < debugLink.Va && debugLink.Va + debugLink.Size <= sect.Va + sect.PSize)
{
pa = sect.Pa + (debugLink.Va - sect.Va);
break;
}
}
if (i == _sections.Size())
{
return S_OK;
// Exe for ARM requires S_OK
// return S_FALSE;
}
CByteBuffer buffer;
buffer.SetCapacity(debugLink.Size);
Byte *buf = buffer;
RINOK(stream->Seek(pa, STREAM_SEEK_SET, NULL));
RINOK(ReadStream_FALSE(stream, buf, debugLink.Size));
for (i = 0; i < (int)numItems; i++)
{
CDebugEntry de;
de.Parse(buf);
if (de.Size == 0)
continue;
CSection sect;
sect.Name = ".debug" + GetDecString(i);
sect.IsDebug = true;
sect.Time = de.Time;
sect.Va = de.Va;
sect.Pa = de.Pa;
sect.PSize = sect.VSize = de.Size;
UInt32 totalSize = sect.Pa + sect.PSize;
if (totalSize > _totalSize)
{
_totalSize = totalSize;
_sections.Add(sect);
thereIsSection = true;
}
buf += kEntrySize;
}
return S_OK;
}
HRESULT CHandler::ReadString(UInt32 offset, UString &dest) const
{
if ((offset & 1) != 0 || offset >= _buf.GetCapacity())
return S_FALSE;
size_t rem = _buf.GetCapacity() - offset;
if (rem < 2)
return S_FALSE;
unsigned length = Get16(_buf + offset);
if ((rem - 2) / 2 < length)
return S_FALSE;
dest.Empty();
offset += 2;
for (unsigned i = 0; i < length; i++)
dest += (wchar_t)Get16(_buf + offset + i * 2);
return S_OK;
}
HRESULT CHandler::ReadTable(UInt32 offset, CRecordVector<CTableItem> &items)
{
if ((offset & 3) != 0 || offset >= _buf.GetCapacity())
return S_FALSE;
size_t rem = _buf.GetCapacity() - offset;
if (rem < 16)
return S_FALSE;
items.Clear();
unsigned numNameItems = Get16(_buf + offset + 12);
unsigned numIdItems = Get16(_buf + offset + 14);
unsigned numItems = numNameItems + numIdItems;
if ((rem - 16) / 8 < numItems)
return S_FALSE;
if (!_usedRes.SetRange(offset, 16 + numItems * 8))
return S_FALSE;
offset += 16;
_oneLang = true;
unsigned i;
for (i = 0; i < numItems; i++)
{
CTableItem item;
const Byte *buf = _buf + offset;
offset += 8;
item.ID = Get32(buf + 0);
if (((item.ID & kFlag) != 0) != (i < numNameItems))
return S_FALSE;
item.Offset = Get32(buf + 4);
items.Add(item);
}
return S_OK;
}
static const UInt32 kFileSizeMax = (UInt32)1 << 30;
static const int kNumResItemsMax = (UInt32)1 << 23;
static const int kNumStringLangsMax = 128;
// BITMAPINFOHEADER
struct CBitmapInfoHeader
{
// UInt32 HeaderSize;
UInt32 XSize;
Int32 YSize;
UInt16 Planes;
UInt16 BitCount;
UInt32 Compression;
UInt32 SizeImage;
bool Parse(const Byte *p, size_t size);
};
static const UInt32 kBitmapInfoHeader_Size = 0x28;
bool CBitmapInfoHeader::Parse(const Byte *p, size_t size)
{
if (size < kBitmapInfoHeader_Size || Get32(p) != kBitmapInfoHeader_Size)
return false;
XSize = Get32(p + 4);
YSize = (Int32)Get32(p + 8);
Planes = Get16(p + 12);
BitCount = Get16(p + 14);
Compression = Get32(p + 16);
SizeImage = Get32(p + 20);
return true;
};
static UInt32 GetImageSize(UInt32 xSize, UInt32 ySize, UInt32 bitCount)
{
return ((xSize * bitCount + 7) / 8 + 3) / 4 * 4 * ySize;
}
static UInt32 SetBitmapHeader(Byte *dest, const Byte *src, UInt32 size)
{
CBitmapInfoHeader h;
if (!h.Parse(src, size))
return 0;
if (h.YSize < 0)
h.YSize = -h.YSize;
if (h.XSize > (1 << 26) || h.YSize > (1 << 26) || h.Planes != 1 || h.BitCount > 32 ||
h.Compression != 0) // BI_RGB
return 0;
if (h.SizeImage == 0)
h.SizeImage = GetImageSize(h.XSize, h.YSize, h.BitCount);
UInt32 totalSize = kBmpHeaderSize + size;
UInt32 offBits = totalSize - h.SizeImage;
// BITMAPFILEHEADER
SetUi16(dest, 0x4D42);
SetUi32(dest + 2, totalSize);
SetUi32(dest + 6, 0);
SetUi32(dest + 10, offBits);
return kBmpHeaderSize;
}
static UInt32 SetIconHeader(Byte *dest, const Byte *src, UInt32 size)
{
CBitmapInfoHeader h;
if (!h.Parse(src, size))
return 0;
if (h.YSize < 0)
h.YSize = -h.YSize;
if (h.XSize > (1 << 26) || h.YSize > (1 << 26) || h.Planes != 1 ||
h.Compression != 0) // BI_RGB
return 0;
UInt32 numBitCount = h.BitCount;
if (numBitCount != 1 &&
numBitCount != 4 &&
numBitCount != 8 &&
numBitCount != 24 &&
numBitCount != 32)
return 0;
if ((h.YSize & 1) != 0)
return 0;
h.YSize /= 2;
if (h.XSize > 0x100 || h.YSize > 0x100)
return 0;
UInt32 imageSize;
// imageSize is not correct if AND mask array contains zeros
// in this case it is equal image1Size
// UInt32 imageSize = h.SizeImage;
// if (imageSize == 0)
// {
UInt32 image1Size = GetImageSize(h.XSize, h.YSize, h.BitCount);
UInt32 image2Size = GetImageSize(h.XSize, h.YSize, 1);
imageSize = image1Size + image2Size;
// }
UInt32 numColors = 0;
if (numBitCount < 16)
numColors = 1 << numBitCount;
SetUi16(dest, 0); // Reserved
SetUi16(dest + 2, 1); // RES_ICON
SetUi16(dest + 4, 1); // ResCount
dest[6] = (Byte)h.XSize; // Width
dest[7] = (Byte)h.YSize; // Height
dest[8] = (Byte)numColors; // ColorCount
dest[9] = 0; // Reserved
SetUi32(dest + 10, 0); // Reserved1 / Reserved2
UInt32 numQuadsBytes = numColors * 4;
UInt32 BytesInRes = kBitmapInfoHeader_Size + numQuadsBytes + imageSize;
SetUi32(dest + 14, BytesInRes);
SetUi32(dest + 18, kIconHeaderSize);
/*
Description = DWORDToString(xSize) +
kDelimiterChar + DWORDToString(ySize) +
kDelimiterChar + DWORDToString(numBitCount);
*/
return kIconHeaderSize;
}
bool CHandler::ParseStringRes(UInt32 id, UInt32 lang, const Byte *src, UInt32 size)
{
if ((size & 1) != 0)
return false;
int i;
for (i = 0; i < _strings.Size(); i++)
if (_strings[i].Lang == lang)
break;
if (i == _strings.Size())
{
if (_strings.Size() >= kNumStringLangsMax)
return false;
CStringItem item;
item.Size = 0;
item.Lang = lang;
i = _strings.Add(item);
}
CStringItem &item = _strings[i];
id = (id - 1) << 4;
UInt32 pos = 0;
for (i = 0; i < 16; i++)
{
if (size - pos < 2)
return false;
UInt32 len = Get16(src + pos);
pos += 2;
if (len != 0)
{
if (size - pos < len * 2)
return false;
char temp[32];
ConvertUInt32ToString(id + i, temp);
size_t tempLen = strlen(temp);
size_t j;
for (j = 0; j < tempLen; j++)
item.AddChar(temp[j]);
item.AddChar('\t');
for (j = 0; j < len; j++, pos += 2)
item.AddWChar(Get16(src + pos));
item.AddChar(0x0D);
item.AddChar(0x0A);
}
}
return (size == pos);
}
HRESULT CHandler::OpenResources(int sectionIndex, IInStream *stream, IArchiveOpenCallback *callback)
{
const CSection § = _sections[sectionIndex];
size_t fileSize = sect.PSize; // Maybe we need sect.VSize here !!!
if (fileSize > kFileSizeMax)
return S_FALSE;
{
UInt64 fileSize64 = fileSize;
if (callback)
RINOK(callback->SetTotal(NULL, &fileSize64));
RINOK(stream->Seek(sect.Pa, STREAM_SEEK_SET, NULL));
_buf.SetCapacity(fileSize);
for (size_t pos = 0; pos < fileSize;)
{
UInt64 offset64 = pos;
if (callback)
RINOK(callback->SetCompleted(NULL, &offset64))
size_t rem = MyMin(fileSize - pos, (size_t)(1 << 20));
RINOK(ReadStream_FALSE(stream, _buf + pos, rem));
pos += rem;
}
}
_usedRes.Alloc(fileSize);
CRecordVector<CTableItem> specItems;
RINOK(ReadTable(0, specItems));
_oneLang = true;
bool stringsOk = true;
size_t maxOffset = 0;
for (int i = 0; i < specItems.Size(); i++)
{
const CTableItem &item1 = specItems[i];
if ((item1.Offset & kFlag) == 0)
return S_FALSE;
CRecordVector<CTableItem> specItems2;
RINOK(ReadTable(item1.Offset & kMask, specItems2));
for (int j = 0; j < specItems2.Size(); j++)
{
const CTableItem &item2 = specItems2[j];
if ((item2.Offset & kFlag) == 0)
return S_FALSE;
CRecordVector<CTableItem> specItems3;
RINOK(ReadTable(item2.Offset & kMask, specItems3));
CResItem item;
item.Type = item1.ID;
item.ID = item2.ID;
for (int k = 0; k < specItems3.Size(); k++)
{
if (_items.Size() >= kNumResItemsMax)
return S_FALSE;
const CTableItem &item3 = specItems3[k];
if ((item3.Offset & kFlag) != 0)
return S_FALSE;
if (item3.Offset >= _buf.GetCapacity() || _buf.GetCapacity() - item3.Offset < 16)
return S_FALSE;
const Byte *buf = _buf + item3.Offset;
item.Lang = item3.ID;
item.Offset = Get32(buf + 0);
item.Size = Get32(buf + 4);
// UInt32 codePage = Get32(buf + 8);
if (Get32(buf + 12) != 0)
return S_FALSE;
if (!_items.IsEmpty() && _oneLang && !item.IsNameEqual(_items.Back()))
_oneLang = false;
item.HeaderSize = 0;
size_t offset = item.Offset - sect.Va;
if (offset > maxOffset)
maxOffset = offset;
if (offset + item.Size > maxOffset)
maxOffset = offset + item.Size;
if (CheckItem(sect, item, offset))
{
const Byte *data = _buf + offset;
if (item.IsBmp())
item.HeaderSize = SetBitmapHeader(item.Header, data, item.Size);
else if (item.IsIcon())
item.HeaderSize = SetIconHeader(item.Header, data, item.Size);
else if (item.IsString())
{
if (stringsOk)
stringsOk = ParseStringRes(item.ID, item.Lang, data, item.Size);
}
}
item.Enabled = true;
_items.Add(item);
}
}
}
if (stringsOk && !_strings.IsEmpty())
{
int i;
for (i = 0; i < _items.Size(); i++)
{
CResItem &item = _items[i];
if (item.IsString())
item.Enabled = false;
}
for (i = 0; i < _strings.Size(); i++)
{
if (_strings[i].Size == 0)
continue;
CMixItem mixItem;
mixItem.ResourceIndex = -1;
mixItem.StringIndex = i;
mixItem.SectionIndex = sectionIndex;
_mixItems.Add(mixItem);
}
}
_usedRes.Free();
int numBits = _optHeader.GetNumFileAlignBits();
if (numBits >= 0)
{
UInt32 mask = (1 << numBits) - 1;
size_t end = ((maxOffset + mask) & ~mask);
if (end < sect.VSize)
{
CSection sect2;
sect2.Flags = 0;
sect2.Pa = sect.Pa + (UInt32)maxOffset;
sect2.Va = sect.Va + (UInt32)maxOffset;
sect2.PSize = sect.VSize - (UInt32)maxOffset;
sect2.VSize = sect2.PSize;
sect2.Name = ".rsrc_1";
sect2.Time = 0;
_sections.Add(sect2);
}
}
return S_OK;
}
HRESULT CHandler::Open2(IInStream *stream, IArchiveOpenCallback *callback)
{
const UInt32 kBufSize = 1 << 18;
const UInt32 kSigSize = 2;
CByteBuffer buffer;
buffer.SetCapacity(kBufSize);
Byte *buf = buffer;
size_t processed = kSigSize;
RINOK(ReadStream_FALSE(stream, buf, processed));
if (buf[0] != 'M' || buf[1] != 'Z')
return S_FALSE;
processed = kBufSize - kSigSize;
RINOK(ReadStream(stream, buf + kSigSize, &processed));
processed += kSigSize;
if (!Parse(buf, (UInt32)processed))
return S_FALSE;
bool thereISDebug;
RINOK(LoadDebugSections(stream, thereISDebug));
const CDirLink &certLink = _optHeader.DirItems[kDirLink_Certificate];
if (certLink.Size != 0)
{
CSection sect;
sect.Name = "CERTIFICATE";
sect.Va = 0;
sect.Pa = certLink.Va;
sect.PSize = sect.VSize = certLink.Size;
sect.UpdateTotalSize(_totalSize);
_sections.Add(sect);
}
if (thereISDebug)
{
const UInt32 kAlign = 1 << 12;
UInt32 alignPos = _totalSize & (kAlign - 1);
if (alignPos != 0)
{
UInt32 size = kAlign - alignPos;
RINOK(stream->Seek(_totalSize, STREAM_SEEK_SET, NULL));
buffer.Free();
buffer.SetCapacity(kAlign);
Byte *buf = buffer;
size_t processed = size;
RINOK(ReadStream(stream, buf, &processed));
size_t i;
for (i = 0; i < processed; i++)
{
if (buf[i] != 0)
break;
}
if (processed < size && processed < 100)
_totalSize += (UInt32)processed;
else if (((_totalSize + i) & 0x1FF) == 0 || processed < size)
_totalSize += (UInt32)i;
}
}
if (_header.NumSymbols > 0 && _header.PointerToSymbolTable >= 512)
{
if (_header.NumSymbols >= (1 << 24))
return S_FALSE;
CSection sect;
sect.Name = "COFF_SYMBOLS";
UInt32 size = _header.NumSymbols * 18;
RINOK(stream->Seek((UInt64)_header.PointerToSymbolTable + size, STREAM_SEEK_SET, NULL));
Byte buf[4];
RINOK(ReadStream_FALSE(stream, buf, 4));
UInt32 size2 = Get32(buf);
if (size2 >= (1 << 28))
return S_FALSE;
size += size2;
sect.Va = 0;
sect.Pa = _header.PointerToSymbolTable;
sect.PSize = sect.VSize = size;
sect.UpdateTotalSize(_totalSize);
_sections.Add(sect);
}
UInt64 fileSize;
RINOK(stream->Seek(0, STREAM_SEEK_END, &fileSize));
if (fileSize > _totalSize)
return S_FALSE;
_totalSizeLimited = (_totalSize < fileSize) ? _totalSize : (UInt32)fileSize;
{
CObjectVector<CSection> sections = _sections;
sections.Sort();
UInt32 limit = (1 << 12);
int num = 0;
int numSections = sections.Size();
for (int i = 0; i < numSections; i++)
{
const CSection &s = sections[i];
if (s.Pa > limit)
{
CSection s2;
s2.Pa = s2.Va = limit;
s2.PSize = s2.VSize = s.Pa - limit;
s2.Name = '[';
s2.Name += GetDecString(num++);
s2.Name += ']';
_sections.Add(s2);
limit = s.Pa;
}
UInt32 next = s.Pa + s.PSize;
if (next < s.Pa)
break;
if (next >= limit)
limit = next;
}
}
_parseResources = true;
for (int i = 0; i < _sections.Size(); i++)
{
const CSection § = _sections[i];
CMixItem mixItem;
mixItem.SectionIndex = i;
if (_parseResources && sect.Name == ".rsrc" && _items.IsEmpty())
{
HRESULT res = OpenResources(i, stream, callback);
if (res == S_OK)
{
_resourceFileName = GetUnicodeString(sect.Name);
for (int j = 0; j < _items.Size(); j++)
if (_items[j].Enabled)
{
mixItem.ResourceIndex = j;
mixItem.StringIndex = -1;
_mixItems.Add(mixItem);
}
if (sect.PSize > sect.VSize)
{
int numBits = _optHeader.GetNumFileAlignBits();
if (numBits >= 0)
{
UInt32 mask = (1 << numBits) - 1;
UInt32 end = ((sect.VSize + mask) & ~mask);
if (sect.PSize > end)
{
CSection sect2;
sect2.Flags = 0;
sect2.Pa = sect.Pa + end;
sect2.Va = sect.Va + end;
sect2.PSize = sect.PSize - end;
sect2.VSize = sect2.PSize;
sect2.Name = ".rsrc_2";
sect2.Time = 0;
_sections.Add(sect2);
}
}
}
continue;
}
if (res != S_FALSE)
return res;
CloseResources();
}
mixItem.StringIndex = -1;
mixItem.ResourceIndex = -1;
_mixItems.Add(mixItem);
}
return S_OK;
}
HRESULT CalcCheckSum(ISequentialInStream *stream, UInt32 size, UInt32 excludePos, UInt32 &res)
{
// size &= ~1;
const UInt32 kBufSize = 1 << 23;
CByteBuffer buffer;
buffer.SetCapacity(kBufSize);
Byte *buf = buffer;
UInt32 sum = 0;
UInt32 pos = 0;
for (;;)
{
UInt32 rem = size - pos;
if (rem > kBufSize)
rem = kBufSize;
if (rem == 0)
break;
size_t processed = rem;
RINOK(ReadStream(stream, buf, &processed));
/*
for (; processed < rem; processed++)
buf[processed] = 0;
*/
if ((processed & 1) != 0)
buf[processed] = 0;
for (int j = 0; j < 4; j++)
{
UInt32 p = excludePos + j;
if (pos <= p && p < pos + processed)
buf[p - pos] = 0;
}
for (size_t i = 0; i < processed; i += 2)
{
sum += Get16(buf + i);
sum = (sum + (sum >> 16)) & 0xFFFF;
}
pos += (UInt32)processed;
if (rem != processed)
break;
}
sum += pos;
res = sum;
return S_OK;
}
STDMETHODIMP CHandler::Open(IInStream *inStream, const UInt64 *, IArchiveOpenCallback *callback)
{
COM_TRY_BEGIN
Close();
RINOK(Open2(inStream, callback));
_stream = inStream;
return S_OK;
COM_TRY_END
}
void CHandler::CloseResources()
{
_usedRes.Free();
_items.Clear();
_strings.Clear();
_buf.SetCapacity(0);
}
STDMETHODIMP CHandler::Close()
{
_stream.Release();
_sections.Clear();
_mixItems.Clear();
CloseResources();
return S_OK;
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = _mixItems.Size();
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = _mixItems.Size();
if (numItems == 0)
return S_OK;
UInt64 totalSize = 0;
UInt32 i;
for (i = 0; i < numItems; i++)
{
const CMixItem &mixItem = _mixItems[allFilesMode ? i : indices[i]];
if (mixItem.StringIndex >= 0)
totalSize += _strings[mixItem.StringIndex].Size;
else if (mixItem.ResourceIndex < 0)
totalSize += _sections[mixItem.SectionIndex].GetPackSize();
else
totalSize += _items[mixItem.ResourceIndex].GetSize();
}
extractCallback->SetTotal(totalSize);
UInt64 currentTotalSize = 0;
UInt64 currentItemSize;
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
bool checkSumOK = true;
if (_optHeader.CheckSum != 0 && (int)numItems == _mixItems.Size())
{
UInt32 checkSum = 0;
RINOK(_stream->Seek(0, STREAM_SEEK_SET, NULL));
CalcCheckSum(_stream, _totalSizeLimited, _peOffset + kHeaderSize + 64, checkSum);
checkSumOK = (checkSum == _optHeader.CheckSum);
}
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
streamSpec->SetStream(_stream);
for (i = 0; i < numItems; i++, currentTotalSize += currentItemSize)
{
lps->InSize = lps->OutSize = currentTotalSize;
RINOK(lps->SetCur());
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
UInt32 index = allFilesMode ? i : indices[i];
CMyComPtr<ISequentialOutStream> outStream;
RINOK(extractCallback->GetStream(index, &outStream, askMode));
const CMixItem &mixItem = _mixItems[index];
const CSection § = _sections[mixItem.SectionIndex];
bool isOk = true;
if (mixItem.StringIndex >= 0)
{
const CStringItem &item = _strings[mixItem.StringIndex];
currentItemSize = item.Size;
if (!testMode && !outStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
if (outStream)
RINOK(WriteStream(outStream, item.Buf, item.Size));
}
else if (mixItem.ResourceIndex < 0)
{
currentItemSize = sect.GetPackSize();
if (!testMode && !outStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(_stream->Seek(sect.Pa, STREAM_SEEK_SET, NULL));
streamSpec->Init(currentItemSize);
RINOK(copyCoder->Code(inStream, outStream, NULL, NULL, progress));
isOk = (copyCoderSpec->TotalSize == currentItemSize);
}
else
{
const CResItem &item = _items[mixItem.ResourceIndex];
currentItemSize = item.GetSize();
if (!testMode && !outStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
size_t offset = item.Offset - sect.Va;
if (!CheckItem(sect, item, offset))
isOk = false;
else if (outStream)
{
if (item.HeaderSize != 0)
RINOK(WriteStream(outStream, item.Header, item.HeaderSize));
RINOK(WriteStream(outStream, _buf + offset, item.Size));
}
}
outStream.Release();
RINOK(extractCallback->SetOperationResult(isOk ?
checkSumOK ?
NExtract::NOperationResult::kOK:
NExtract::NOperationResult::kCRCError:
NExtract::NOperationResult::kDataError));
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
COM_TRY_BEGIN
*stream = 0;
const CMixItem &mixItem = _mixItems[index];
const CSection § = _sections[mixItem.SectionIndex];
if (mixItem.IsSectionItem())
return CreateLimitedInStream(_stream, sect.Pa, sect.PSize, stream);
CBufInStream *inStreamSpec = new CBufInStream;
CMyComPtr<ISequentialInStream> streamTemp = inStreamSpec;
CReferenceBuf *referenceBuf = new CReferenceBuf;
CMyComPtr<IUnknown> ref = referenceBuf;
if (mixItem.StringIndex >= 0)
{
const CStringItem &item = _strings[mixItem.StringIndex];
referenceBuf->Buf.SetCapacity(item.Size);
memcpy(referenceBuf->Buf, item.Buf, item.Size);
}
else
{
const CResItem &item = _items[mixItem.ResourceIndex];
size_t offset = item.Offset - sect.Va;
if (!CheckItem(sect, item, offset))
return S_FALSE;
referenceBuf->Buf.SetCapacity(item.HeaderSize + item.Size);
memcpy(referenceBuf->Buf, item.Header, item.HeaderSize);
memcpy(referenceBuf->Buf + item.HeaderSize, _buf + offset, item.Size);
}
inStreamSpec->Init(referenceBuf);
*stream = streamTemp.Detach();
return S_OK;
COM_TRY_END
}
static IInArchive *CreateArc() { return new CHandler; }
static CArcInfo g_ArcInfo =
{ L"PE", L"exe dll sys", 0, 0xDD, { 'P', 'E', 0, 0 }, 4, false, CreateArc, 0 };
REGISTER_ARC(Pe)
}}
<file_sep>/SQLCEHelper/Source/AddOffset.h
#ifndef __ADDOFFSET_H__
#define __ADDOFFSET_H__
ULONG AddOffset(ULONG nCurrent, ULONG nAdd);
#endif
<file_sep>/7-Zip/CPP/7zip/Archive/Wim/WimHandler.cpp
// WimHandler.cpp
#include "StdAfx.h"
#include "Common/IntToString.h"
#include "Common/Defs.h"
#include "Common/ComTry.h"
#include "Common/StringToInt.h"
#include "Common/UTFConvert.h"
#include "Windows/PropVariant.h"
#include "../../Common/StreamUtils.h"
#include "../../Common/ProgressUtils.h"
#include "../../../../C/CpuArch.h"
#include "WimHandler.h"
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
#define Get64(p) GetUi64(p)
using namespace NWindows;
namespace NArchive {
namespace NWim {
#define WIM_DETAILS
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidIsDir, VT_BOOL},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidAttrib, VT_UI4},
{ NULL, kpidMethod, VT_BSTR},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidATime, VT_FILETIME}
#ifdef WIM_DETAILS
, { NULL, kpidVolume, VT_UI4}
, { NULL, kpidOffset, VT_UI8}
, { NULL, kpidLinks, VT_UI4}
#endif
};
STATPROPSTG kArcProps[] =
{
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMethod, VT_BSTR},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidComment, VT_FILETIME},
{ NULL, kpidIsVolume, VT_BOOL},
{ NULL, kpidVolume, VT_UI4},
{ NULL, kpidNumVolumes, VT_UI4}
};
static bool ParseNumber64(const AString &s, UInt64 &res)
{
const char *end;
if (s.Left(2) == "0x")
{
if (s.Length() == 2)
return false;
res = ConvertHexStringToUInt64((const char *)s + 2, &end);
}
else
{
if (s.IsEmpty())
return false;
res = ConvertStringToUInt64(s, &end);
}
return *end == 0;
}
static bool ParseNumber32(const AString &s, UInt32 &res)
{
UInt64 res64;
if (!ParseNumber64(s, res64) || res64 >= ((UInt64)1 << 32))
return false;
res = (UInt32)res64;
return true;
}
void ParseTime(const CXmlItem &item, bool &defined, FILETIME &ft, const AString &s)
{
defined = false;
int cTimeIndex = item.FindSubTag(s);
if (cTimeIndex >= 0)
{
const CXmlItem &timeItem = item.SubItems[cTimeIndex];
UInt32 high = 0, low = 0;
if (ParseNumber32(timeItem.GetSubStringForTag("HIGHPART"), high) &&
ParseNumber32(timeItem.GetSubStringForTag("LOWPART"), low))
{
defined = true;
ft.dwHighDateTime = high;
ft.dwLowDateTime = low;
}
}
}
void CImageInfo::Parse(const CXmlItem &item)
{
ParseTime(item, CTimeDefined, CTime, "CREATIONTIME");
ParseTime(item, MTimeDefined, MTime, "LASTMODIFICATIONTIME");
NameDefined = ConvertUTF8ToUnicode(item.GetSubStringForTag("NAME"), Name);
// IndexDefined = ParseNumber32(item.GetPropertyValue("INDEX"), Index);
}
void CXml::Parse()
{
size_t size = Data.GetCapacity();
if (size < 2 || (size & 1) != 0 || (size > 1 << 24))
return;
const Byte *p = Data;
if (Get16(p) != 0xFEFF)
return;
UString s;
{
wchar_t *chars = s.GetBuffer((int)size / 2 + 1);
for (size_t i = 2; i < size; i += 2)
*chars++ = (wchar_t)Get16(p + i);
*chars = 0;
s.ReleaseBuffer();
}
AString utf;
if (!ConvertUnicodeToUTF8(s, utf))
return;
::CXml xml;
if (!xml.Parse(utf))
return;
if (xml.Root.Name != "WIM")
return;
for (int i = 0; i < xml.Root.SubItems.Size(); i++)
{
const CXmlItem &item = xml.Root.SubItems[i];
if (item.IsTagged("IMAGE"))
{
CImageInfo imageInfo;
imageInfo.Parse(item);
Images.Add(imageInfo);
}
}
}
static const wchar_t *kStreamsNamePrefix = L"Files" WSTRING_PATH_SEPARATOR;
static const wchar_t *kMethodLZX = L"LZX";
static const wchar_t *kMethodXpress = L"XPress";
static const wchar_t *kMethodCopy = L"Copy";
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CImageInfo *image = NULL;
if (m_Xmls.Size() == 1)
{
const CXml &xml = m_Xmls[0];
if (xml.Images.Size() == 1)
image = &xml.Images[0];
}
switch(propID)
{
case kpidSize: prop = m_Database.GetUnpackSize(); break;
case kpidPackSize: prop = m_Database.GetPackSize(); break;
case kpidCTime:
if (m_Xmls.Size() == 1)
{
const CXml &xml = m_Xmls[0];
int index = -1;
for (int i = 0; i < xml.Images.Size(); i++)
{
const CImageInfo &image = xml.Images[i];
if (image.CTimeDefined)
if (index < 0 || ::CompareFileTime(&image.CTime, &xml.Images[index].CTime) < 0)
index = i;
}
if (index >= 0)
prop = xml.Images[index].CTime;
}
break;
case kpidMTime:
if (m_Xmls.Size() == 1)
{
const CXml &xml = m_Xmls[0];
int index = -1;
for (int i = 0; i < xml.Images.Size(); i++)
{
const CImageInfo &image = xml.Images[i];
if (image.MTimeDefined)
if (index < 0 || ::CompareFileTime(&image.MTime, &xml.Images[index].MTime) > 0)
index = i;
}
if (index >= 0)
prop = xml.Images[index].MTime;
}
break;
case kpidComment: if (image != NULL && image->NameDefined) prop = image->Name; break;
case kpidIsVolume:
if (m_Xmls.Size() > 0)
{
UInt16 volIndex = m_Xmls[0].VolIndex;
if (volIndex < m_Volumes.Size())
prop = (m_Volumes[volIndex].Header.NumParts > 1);
}
break;
case kpidVolume:
if (m_Xmls.Size() > 0)
{
UInt16 volIndex = m_Xmls[0].VolIndex;
if (volIndex < m_Volumes.Size())
prop = (UInt32)m_Volumes[volIndex].Header.PartNumber;
}
break;
case kpidNumVolumes: if (m_Volumes.Size() > 0) prop = (UInt32)(m_Volumes.Size() - 1); break;
case kpidMethod:
{
bool lzx = false, xpress = false, copy = false;
for (int i = 0; i < m_Xmls.Size(); i++)
{
const CVolume &vol = m_Volumes[m_Xmls[i].VolIndex];
const CHeader &header = vol.Header;
if (header.IsCompressed())
if (header.IsLzxMode())
lzx = true;
else
xpress = true;
else
copy = true;
}
UString res;
if (lzx)
res = kMethodLZX;
if (xpress)
{
if (!res.IsEmpty())
res += L' ';
res += kMethodXpress;
}
if (copy)
{
if (!res.IsEmpty())
res += L' ';
res += kMethodCopy;
}
prop = res;
}
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
if (index < (UInt32)m_Database.Items.Size())
{
const CItem &item = m_Database.Items[index];
const CStreamInfo *si = NULL;
const CVolume *vol = NULL;
if (item.StreamIndex >= 0)
{
si = &m_Database.Streams[item.StreamIndex];
vol = &m_Volumes[si->PartNumber];
}
switch(propID)
{
case kpidPath:
if (item.HasMetadata)
prop = item.Name;
else
{
wchar_t sz[32];
ConvertUInt64ToString(item.StreamIndex, sz);
UString s = sz;
while (s.Length() < m_NameLenForStreams)
s = L'0' + s;
s = UString(kStreamsNamePrefix) + s;
prop = s;
break;
}
break;
case kpidIsDir: prop = item.isDir(); break;
case kpidAttrib: if (item.HasMetadata) prop = item.Attrib; break;
case kpidCTime: if (item.HasMetadata) prop = item.CTime; break;
case kpidATime: if (item.HasMetadata) prop = item.ATime; break;
case kpidMTime: if (item.HasMetadata) prop = item.MTime; break;
case kpidPackSize: prop = si ? si->Resource.PackSize : (UInt64)0; break;
case kpidSize: prop = si ? si->Resource.UnpackSize : (UInt64)0; break;
case kpidMethod: if (si) prop = si->Resource.IsCompressed() ?
(vol->Header.IsLzxMode() ? kMethodLZX : kMethodXpress) : kMethodCopy; break;
#ifdef WIM_DETAILS
case kpidVolume: if (si) prop = (UInt32)si->PartNumber; break;
case kpidOffset: if (si) prop = (UInt64)si->Resource.Offset; break;
case kpidLinks: prop = si ? (UInt32)si->RefCount : (UInt32)0; break;
#endif
}
}
else
{
index -= m_Database.Items.Size();
{
switch(propID)
{
case kpidPath:
{
wchar_t sz[32];
ConvertUInt64ToString(m_Xmls[index].VolIndex, sz);
UString s = (UString)sz + L".xml";
prop = s;
break;
}
case kpidIsDir: prop = false; break;
case kpidPackSize:
case kpidSize: prop = (UInt64)m_Xmls[index].Data.GetCapacity(); break;
case kpidMethod: prop = L"Copy"; break;
}
}
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
class CVolumeName
{
// UInt32 _volIndex;
UString _before;
UString _after;
public:
CVolumeName() {};
void InitName(const UString &name)
{
// _volIndex = 1;
int dotPos = name.ReverseFind('.');
if (dotPos < 0)
dotPos = name.Length();
_before = name.Left(dotPos);
_after = name.Mid(dotPos);
}
UString GetNextName(UInt32 index)
{
wchar_t s[32];
ConvertUInt64ToString((index), s);
return _before + (UString)s + _after;
}
};
STDMETHODIMP CHandler::Open(IInStream *inStream,
const UInt64 * /* maxCheckStartPosition */,
IArchiveOpenCallback *openArchiveCallback)
{
COM_TRY_BEGIN
Close();
try
{
CMyComPtr<IArchiveOpenVolumeCallback> openVolumeCallback;
CVolumeName seqName;
if (openArchiveCallback != NULL)
openArchiveCallback->QueryInterface(IID_IArchiveOpenVolumeCallback, (void **)&openVolumeCallback);
UInt32 numVolumes = 1;
int firstVolumeIndex = -1;
for (UInt32 i = 1; i <= numVolumes; i++)
{
CMyComPtr<IInStream> curStream;
if (i != 1)
{
UString fullName = seqName.GetNextName(i);
HRESULT result = openVolumeCallback->GetStream(fullName, &curStream);
if (result == S_FALSE)
continue;
if (result != S_OK)
return result;
if (!curStream)
break;
}
else
curStream = inStream;
CHeader header;
HRESULT res = NWim::ReadHeader(curStream, header);
if (res != S_OK)
{
if (i == 1)
return res;
if (res == S_FALSE)
continue;
return res;
}
if (firstVolumeIndex >= 0)
if (!header.AreFromOnArchive(m_Volumes[firstVolumeIndex].Header))
break;
if (m_Volumes.Size() > header.PartNumber && m_Volumes[header.PartNumber].Stream)
break;
CXml xml;
xml.VolIndex = header.PartNumber;
res = OpenArchive(curStream, header, xml.Data, m_Database);
if (res != S_OK)
{
if (i == 1)
return res;
if (res == S_FALSE)
continue;
return res;
}
while (m_Volumes.Size() <= header.PartNumber)
m_Volumes.Add(CVolume());
CVolume &volume = m_Volumes[header.PartNumber];
volume.Header = header;
volume.Stream = curStream;
firstVolumeIndex = header.PartNumber;
bool needAddXml = true;
if (m_Xmls.Size() != 0)
if (xml.Data == m_Xmls[0].Data)
needAddXml = false;
if (needAddXml)
{
xml.Parse();
m_Xmls.Add(xml);
}
if (i == 1)
{
if (header.PartNumber != 1)
break;
if (!openVolumeCallback)
break;
numVolumes = header.NumParts;
{
NCOM::CPropVariant prop;
RINOK(openVolumeCallback->GetProperty(kpidName, &prop));
if (prop.vt != VT_BSTR)
break;
seqName.InitName(prop.bstrVal);
}
}
}
RINOK(SortDatabase(m_Database));
wchar_t sz[32];
ConvertUInt64ToString(m_Database.Streams.Size(), sz);
m_NameLenForStreams = MyStringLen(sz);
}
catch(...)
{
return S_FALSE;
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
m_Database.Clear();
m_Volumes.Clear();
m_Xmls.Clear();
m_NameLenForStreams = 0;
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = m_Database.Items.Size() + m_Xmls.Size();
if (numItems == 0)
return S_OK;
UInt32 i;
UInt64 totalSize = 0;
for (i = 0; i < numItems; i++)
{
UInt32 index = allFilesMode ? i : indices[i];
if (index < (UInt32)m_Database.Items.Size())
{
int streamIndex = m_Database.Items[index].StreamIndex;
if (streamIndex >= 0)
{
const CStreamInfo &si = m_Database.Streams[streamIndex];
totalSize += si.Resource.UnpackSize;
}
}
else
totalSize += m_Xmls[index - (UInt32)m_Database.Items.Size()].Data.GetCapacity();
}
RINOK(extractCallback->SetTotal(totalSize));
UInt64 currentTotalPacked = 0;
UInt64 currentTotalUnPacked = 0;
UInt64 currentItemUnPacked, currentItemPacked;
int prevSuccessStreamIndex = -1;
CUnpacker unpacker;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
for (i = 0; i < numItems; currentTotalUnPacked += currentItemUnPacked,
currentTotalPacked += currentItemPacked)
{
currentItemUnPacked = 0;
currentItemPacked = 0;
lps->InSize = currentTotalPacked;
lps->OutSize = currentTotalUnPacked;
RINOK(lps->SetCur());
UInt32 index = allFilesMode ? i : indices[i];
i++;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
CMyComPtr<ISequentialOutStream> realOutStream;
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
if (index >= (UInt32)m_Database.Items.Size())
{
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
const CByteBuffer &data = m_Xmls[index - (UInt32)m_Database.Items.Size()].Data;
currentItemUnPacked = data.GetCapacity();
if (realOutStream)
{
RINOK(WriteStream(realOutStream, (const Byte *)data, data.GetCapacity()));
realOutStream.Release();
}
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
const CItem &item = m_Database.Items[index];
int streamIndex = item.StreamIndex;
if (streamIndex < 0)
{
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(item.HasStream() ?
NExtract::NOperationResult::kDataError :
NExtract::NOperationResult::kOK));
continue;
}
const CStreamInfo &si = m_Database.Streams[streamIndex];
currentItemUnPacked = si.Resource.UnpackSize;
currentItemPacked = si.Resource.PackSize;
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
Int32 opRes = NExtract::NOperationResult::kOK;
if (streamIndex != prevSuccessStreamIndex || realOutStream)
{
Byte digest[20];
const CVolume &vol = m_Volumes[si.PartNumber];
HRESULT res = unpacker.Unpack(vol.Stream, si.Resource, vol.Header.IsLzxMode(),
realOutStream, progress, digest);
if (res == S_OK)
{
if (memcmp(digest, si.Hash, kHashSize) == 0)
prevSuccessStreamIndex = streamIndex;
else
opRes = NExtract::NOperationResult::kCRCError;
}
else if (res == S_FALSE)
opRes = NExtract::NOperationResult::kDataError;
else
return res;
}
realOutStream.Release();
RINOK(extractCallback->SetOperationResult(opRes));
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = m_Database.Items.Size() + m_Xmls.Size();
return S_OK;
}
}}
<file_sep>/FingerSuite/SetupDLL/setup.cpp
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this sample source code is subject to the terms of the Microsoft
// license agreement under which you licensed this sample source code. If
// you did not accept the terms of the license agreement, you are not
// authorized to use this sample source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the LICENSE.RTF on your install media or the root of your tools installation.
// THE SAMPLE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES OR INDEMNITIES.
//
// ************************************************************
// setup.cpp
//
// Implementation of DllMain and setup functions
//
//
// ************************************************************
#include "stdafx.h"
#define ARRAYSIZE(x) (sizeof(x)/sizeof((x)[0]))
HINSTANCE g_hinstModule;
// dbg
HWND g_hwndParent;
WCHAR g_szDbg[MAX_PATH];
// fine dbg
DWORD CheckRealDPI(HWND hwndParent)
{
DWORD nSystemDPI = 0;
{
TCHAR szGetRealDPI[MAX_PATH + 40];
PROCESS_INFORMATION pi;
::StringCchCat(szGetRealDPI, ARRAYSIZE(szGetRealDPI), _T("\\Application Data\\FingerSuite\\GetRealDPI.EXE"));
::CreateProcess(szGetRealDPI, NULL, NULL, NULL, NULL, 0, NULL, NULL, NULL, &pi);
::WaitForSingleObject(pi.hProcess, 10000);
::GetExitCodeProcess(pi.hProcess, &nSystemDPI);
::CloseHandle(pi.hProcess);
}
return nSystemDPI;
}
void DeletePngs(DWORD nSystemDPI, LPCTSTR pszInstallDir, LPCTSTR pszAppName)
{
WCHAR szSearch[MAX_PATH + 40];
if (nSystemDPI == 96)
{
wsprintf(szSearch, L"%s\\%s\\skins\\default\\*_vga.png", pszInstallDir, pszAppName);
}
else if (nSystemDPI == 192)
{
wsprintf(szSearch, L"%s\\%s\\skins\\default\\*_qvga.png", pszInstallDir, pszAppName);
}
else
return;
WIN32_FIND_DATA fd;
WCHAR szFileName[MAX_PATH + 40];
HANDLE hFind = FindFirstFile(szSearch, &fd);
if (hFind != INVALID_HANDLE_VALUE)
{
do
{
wsprintf(szFileName, L"%s\\%s\\skins\\default\\%s", pszInstallDir, pszAppName, fd.cFileName);
DeleteFile(szFileName);
} while (FindNextFile(hFind, &fd));
}
}
void DeleteMUIs(DWORD nLangID, LPCTSTR pszInstallDir, LPCTSTR pszAppName)
{
WCHAR szSearch[MAX_PATH + 40];
wsprintf(szSearch, L"%s\\%s\\%s.exe.%04x.mui", pszInstallDir, pszAppName, pszAppName, nLangID);
//wsprintf(g_szDbg, L"mui=%s", szSearch);
//MessageBox(g_hwndParent, g_szDbg, L"", MB_ICONINFORMATION);
WIN32_FIND_DATA fd;
HANDLE hFind = FindFirstFile(szSearch, &fd);
if (hFind == INVALID_HANDLE_VALUE)
{
// default to english
WCHAR szEnglishMUI[MAX_PATH + 40];
wsprintf(szEnglishMUI, L"%s\\%s\\%s.exe.0409.mui", pszInstallDir, pszAppName, pszAppName);
CopyFile(szEnglishMUI, szSearch, FALSE);
}
}
BOOL APIENTRY DllMain(
HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
g_hinstModule = (HINSTANCE)hModule;
break;
}
return TRUE;
}
// **************************************************************************
// Function Name: Install_Init
//
// Purpose: processes the push message.
//
// Arguments:
// IN HWND hwndParent handle to the parent window
// IN BOOL fFirstCall indicates that this is the first time this function is being called
// IN BOOL fPreviouslyInstalled indicates that the current application is already installed
// IN LPCTSTR pszInstallDir name of the user-selected install directory of the application
//
// Return Values:
// codeINSTALL_INIT
// returns install status
//
// Description:
// The Install_Init function is called before installation begins.
// User will be prompted to confirm installation.
// **************************************************************************
SETUP_API codeINSTALL_INIT Install_Init(
HWND hwndParent,
BOOL fFirstCall, // is this the first time this function is being called?
BOOL fPreviouslyInstalled,
LPCTSTR pszInstallDir
)
{
//WCHAR szKeyName[] = L"Software\\FingerMenu";
//RegDeleteKey(HKEY_LOCAL_MACHINE, szKeyName);
return codeINSTALL_INIT_CONTINUE;
}
// **************************************************************************
// Function Name: Install_Exit
//
// Purpose: processes the push message.
//
// Arguments:
// IN HWND hwndParent handle to the parent window
// IN LPCTSTR pszInstallDir name of the user-selected install directory of the application
//
// Return Values:
// codeINSTALL_EXIT
// returns install status
//
// Description:
// Register query client with the PushRouter as part of installation.
// Only the first two parameters really count.
// **************************************************************************
SETUP_API codeINSTALL_EXIT Install_Exit(
HWND hwndParent,
LPCTSTR pszInstallDir, // final install directory
WORD cFailedDirs,
WORD cFailedFiles,
WORD cFailedRegKeys,
WORD cFailedRegVals,
WORD cFailedShortcuts
)
{
//WCHAR szStartupFile[] = L"\\Windows\\Startup\\FingerMenu.lnk";
//if (MessageBox(hwndParent, L"Autostart FingerMenu on boot?", L"Autostart", MB_ICONINFORMATION | MB_YESNO) == IDNO)
//{
// DeleteFile(szStartupFile);
//}
g_hwndParent = hwndParent;
DWORD nSystemDPI = CheckRealDPI(hwndParent);
// delete useless pngs
WCHAR szProgramFiles[MAX_PATH];
SHGetSpecialFolderPath(hwndParent, szProgramFiles, CSIDL_PROGRAM_FILES, FALSE);
DeletePngs(nSystemDPI, szProgramFiles, L"FingerMenu");
DeletePngs(nSystemDPI, szProgramFiles, L"FingerMsgbox");
// delete useless languages
LANGID lLang = GetSystemDefaultUILanguage();
DeleteMUIs(lLang, szProgramFiles, L"FingerMenu");
DeleteMUIs(lLang, szProgramFiles, L"FingerMsgbox");
// TODO set locales
return codeINSTALL_EXIT_DONE;
}
// **************************************************************************
// Function Name: Uninstall_Init
//
// Purpose: processes the push message.
//
// Arguments:
// IN HWND hwndParent handle to the parent window
// IN LPCTSTR pszInstallDir name of the user-selected install directory of the application
//
// Return Values:
// codeUNINSTALL_INIT
// returns uninstall status
//
// Description:
// Query the device data using the query xml in the push message,
// and send the query results back to the server.
// **************************************************************************
SETUP_API codeUNINSTALL_INIT Uninstall_Init(
HWND hwndParent,
LPCTSTR pszInstallDir
)
{
// close programs
HWND hWndDest = ::FindWindow(L"FINGER_MENU", NULL);
if (hWndDest != NULL)
{
::PostMessage(hWndDest, WM_CLOSE, 0, 0);
}
hWndDest = ::FindWindow(L"FINGER_MSGBOX", NULL);
if (hWndDest != NULL)
{
::PostMessage(hWndDest, WM_CLOSE, 0, 0);
}
return codeUNINSTALL_INIT_CONTINUE;
}
// **************************************************************************
// Function Name: Uninstall_Exit
//
// Purpose: processes the push message.
//
// Arguments:
// IN HWND hwndParent handle to the parent window
//
// Return Values:
// codeUNINSTALL_EXIT
// returns uninstall status
//
// Description:
// Query the device data using the query xml in the push message,
// and send the query results back to the server.
// **************************************************************************
SETUP_API codeUNINSTALL_EXIT Uninstall_Exit(
HWND hwndParent
)
{
WCHAR szStartup[MAX_PATH];
SHGetSpecialFolderPath(hwndParent, szStartup, CSIDL_STARTUP, FALSE);
WCHAR szLnk[MAX_PATH + 40];
wsprintf(szLnk, L"%s\\FingerMenu.lnk", szStartup);
DeleteFile(szLnk);
wsprintf(szLnk, L"%s\\FingerMsgbox.lnk", szStartup);
DeleteFile(szLnk);
return codeUNINSTALL_EXIT_DONE;
}
<file_sep>/7-Zip/CPP/7zip/Archive/NtfsHandler.cpp
// NtfsHandler.cpp
#include "StdAfx.h"
// #define SHOW_DEBUG_INFO
// #define SHOW_DEBUG_INFO2
#if defined(SHOW_DEBUG_INFO) || defined(SHOW_DEBUG_INFO2)
#include <stdio.h>
#endif
#include "../../../C/CpuArch.h"
#include "Common/Buffer.h"
#include "Common/ComTry.h"
#include "Common/IntToString.h"
#include "Common/MyCom.h"
#include "Common/StringConvert.h"
#include "Windows/PropVariant.h"
#include "Windows/Time.h"
#include "../Common/ProgressUtils.h"
#include "../Common/RegisterArc.h"
#include "../Common/StreamUtils.h"
#include "../Compress/CopyCoder.h"
#include "Common/DummyOutStream.h"
#ifdef SHOW_DEBUG_INFO
#define PRF(x) x
#else
#define PRF(x)
#endif
#ifdef SHOW_DEBUG_INFO2
#define PRF2(x) x
#else
#define PRF2(x)
#endif
#define Get16(p) GetUi16(p)
#define Get32(p) GetUi32(p)
#define Get64(p) GetUi64(p)
#define G16(p, dest) dest = Get16(p);
#define G32(p, dest) dest = Get32(p);
#define G64(p, dest) dest = Get64(p);
namespace NArchive {
namespace Ntfs {
static const UInt32 kNumSysRecs = 16;
static const UInt32 kRecIndex_Volume = 3;
static const UInt32 kRecIndex_BadClus = 8;
struct CHeader
{
Byte SectorSizeLog;
Byte ClusterSizeLog;
// Byte MediaType;
UInt32 NumHiddenSectors;
UInt64 NumClusters;
UInt64 MftCluster;
UInt64 SerialNumber;
UInt16 SectorsPerTrack;
UInt16 NumHeads;
UInt64 GetPhySize() const { return NumClusters << ClusterSizeLog; }
UInt32 ClusterSize() const { return (UInt32)1 << ClusterSizeLog; }
bool Parse(const Byte *p);
};
static int GetLog(UInt32 num)
{
for (int i = 0; i < 31; i++)
if (((UInt32)1 << i) == num)
return i;
return -1;
}
bool CHeader::Parse(const Byte *p)
{
if (p[0x1FE] != 0x55 || p[0x1FF] != 0xAA)
return false;
int codeOffset = 0;
switch (p[0])
{
case 0xE9: codeOffset = 3 + (Int16)Get16(p + 1); break;
case 0xEB: if (p[2] != 0x90) return false; codeOffset = 2 + (signed char)p[1]; break;
default: return false;
}
Byte sectorsPerClusterLog;
if (memcmp(p + 3, "NTFS ", 8) != 0)
return false;
{
int s = GetLog(Get16(p + 11));
if (s < 9 || s > 12)
return false;
SectorSizeLog = (Byte)s;
s = GetLog(p[13]);
if (s < 0)
return false;
sectorsPerClusterLog = (Byte)s;
ClusterSizeLog = SectorSizeLog + sectorsPerClusterLog;
}
for (int i = 14; i < 21; i++)
if (p[i] != 0)
return false;
// MediaType = p[21];
if (Get16(p + 22) != 0) // NumFatSectors
return false;
G16(p + 24, SectorsPerTrack);
G16(p + 26, NumHeads);
G32(p + 28, NumHiddenSectors);
if (Get32(p + 32) != 0) // NumSectors32
return false;
// DriveNumber = p[0x24];
if (p[0x25] != 0) // CurrentHead
return false;
/*
NTFS-HDD: p[0x26] = 0x80
NTFS-FLASH: p[0x26] = 0
*/
if (p[0x26] != 0x80 && p[0x26] != 0) // ExtendedBootSig
return false;
if (p[0x27] != 0) // reserved
return false;
UInt64 numSectors = Get64(p + 0x28);
NumClusters = numSectors >> sectorsPerClusterLog;
G64(p + 0x30, MftCluster);
// G64(p + 0x38, Mft2Cluster);
G64(p + 0x48, SerialNumber);
UInt32 numClustersInMftRec;
UInt32 numClustersInIndexBlock;
G32(p + 0x40, numClustersInMftRec);
G32(p + 0x44, numClustersInIndexBlock);
return (numClustersInMftRec < 256 && numClustersInIndexBlock < 256);
}
struct CMftRef
{
UInt64 Val;
UInt64 GetIndex() const { return Val & (((UInt64)1 << 48) - 1); }
UInt16 GetNumber() const { return (UInt16)(Val >> 48); }
bool IsBaseItself() const { return Val == 0; }
};
#define ATNAME(n) ATTR_TYPE_ ## n
#define DEF_ATTR_TYPE(v, n) ATNAME(n) = v
typedef enum
{
DEF_ATTR_TYPE(0x00, UNUSED),
DEF_ATTR_TYPE(0x10, STANDARD_INFO),
DEF_ATTR_TYPE(0x20, ATTRIBUTE_LIST),
DEF_ATTR_TYPE(0x30, FILE_NAME),
DEF_ATTR_TYPE(0x40, OBJECT_ID),
DEF_ATTR_TYPE(0x50, SECURITY_DESCRIPTOR),
DEF_ATTR_TYPE(0x60, VOLUME_NAME),
DEF_ATTR_TYPE(0x70, VOLUME_INFO),
DEF_ATTR_TYPE(0x80, DATA),
DEF_ATTR_TYPE(0x90, INDEX_ROOT),
DEF_ATTR_TYPE(0xA0, INDEX_ALLOCATION),
DEF_ATTR_TYPE(0xB0, BITMAP),
DEF_ATTR_TYPE(0xC0, REPARSE_POINT),
DEF_ATTR_TYPE(0xD0, EA_INFO),
DEF_ATTR_TYPE(0xE0, EA),
DEF_ATTR_TYPE(0xF0, PROPERTY_SET),
DEF_ATTR_TYPE(0x100, LOGGED_UTILITY_STREAM),
DEF_ATTR_TYPE(0x1000, FIRST_USER_DEFINED_ATTRIBUTE)
};
static const Byte kFileNameType_Posix = 0;
static const Byte kFileNameType_Win32 = 1;
static const Byte kFileNameType_Dos = 2;
static const Byte kFileNameType_Win32Dos = 3;
struct CFileNameAttr
{
CMftRef ParentDirRef;
// UInt64 CTime;
// UInt64 MTime;
// UInt64 ThisRecMTime;
// UInt64 ATime;
// UInt64 AllocatedSize;
// UInt64 DataSize;
// UInt16 PackedEaSize;
UString Name;
UInt32 Attrib;
Byte NameType;
bool IsDos() const { return NameType == kFileNameType_Dos; }
bool Parse(const Byte *p, unsigned size);
};
static void GetString(const Byte *p, unsigned length, UString &res)
{
wchar_t *s = res.GetBuffer(length);
for (unsigned i = 0; i < length; i++)
s[i] = Get16(p + i * 2);
s[length] = 0;
res.ReleaseBuffer();
}
bool CFileNameAttr::Parse(const Byte *p, unsigned size)
{
if (size < 0x42)
return false;
G64(p + 0x00, ParentDirRef.Val);
// G64(p + 0x08, CTime);
// G64(p + 0x10, MTime);
// G64(p + 0x18, ThisRecMTime);
// G64(p + 0x20, ATime);
// G64(p + 0x28, AllocatedSize);
// G64(p + 0x30, DataSize);
G32(p + 0x38, Attrib);
// G16(p + 0x3C, PackedEaSize);
NameType = p[0x41];
unsigned length = p[0x40];
if (0x42 + length > size)
return false;
GetString(p + 0x42, length, Name);
return true;
}
struct CSiAttr
{
UInt64 CTime;
UInt64 MTime;
// UInt64 ThisRecMTime;
UInt64 ATime;
UInt32 Attrib;
/*
UInt32 MaxVersions;
UInt32 Version;
UInt32 ClassId;
UInt32 OwnerId;
UInt32 SecurityId;
UInt64 QuotaCharged;
*/
bool Parse(const Byte *p, unsigned size);
};
bool CSiAttr::Parse(const Byte *p, unsigned size)
{
if (size < 0x24)
return false;
G64(p + 0x00, CTime);
G64(p + 0x08, MTime);
// G64(p + 0x10, ThisRecMTime);
G64(p + 0x18, ATime);
G32(p + 0x20, Attrib);
return true;
}
static const UInt64 kEmptyExtent = (UInt64)(Int64)-1;
struct CExtent
{
UInt64 Virt;
UInt64 Phy;
bool IsEmpty() const { return Phy == kEmptyExtent; }
};
struct CVolInfo
{
Byte MajorVer;
Byte MinorVer;
// UInt16 Flags;
bool Parse(const Byte *p, unsigned size);
};
bool CVolInfo::Parse(const Byte *p, unsigned size)
{
if (size < 12)
return false;
MajorVer = p[8];
MinorVer = p[9];
// Flags = Get16(p + 10);
return true;
}
struct CAttr
{
UInt32 Type;
// UInt32 Length;
UString Name;
// UInt16 Flags;
// UInt16 Instance;
CByteBuffer Data;
Byte NonResident;
// Non-Resident
Byte CompressionUnit;
UInt64 LowVcn;
UInt64 HighVcn;
UInt64 AllocatedSize;
UInt64 Size;
UInt64 PackSize;
UInt64 InitializedSize;
// Resident
// UInt16 ResidentFlags;
bool IsCompressionUnitSupported() const { return CompressionUnit == 0 || CompressionUnit == 4; }
UInt32 Parse(const Byte *p, unsigned size);
bool ParseFileName(CFileNameAttr &a) const { return a.Parse(Data, (unsigned)Data.GetCapacity()); }
bool ParseSi(CSiAttr &a) const { return a.Parse(Data, (unsigned)Data.GetCapacity()); }
bool ParseVolInfo(CVolInfo &a) const { return a.Parse(Data, (unsigned)Data.GetCapacity()); }
bool ParseExtents(CRecordVector<CExtent> &extents, UInt64 numClustersMax, int compressionUnit) const;
UInt64 GetSize() const { return NonResident ? Size : Data.GetCapacity(); }
UInt64 GetPackSize() const
{
if (!NonResident)
return Data.GetCapacity();
if (CompressionUnit != 0)
return PackSize;
return AllocatedSize;
}
};
#define RINOZ(x) { int __tt = (x); if (__tt != 0) return __tt; }
static int CompareAttr(void *const *elem1, void *const *elem2, void *)
{
const CAttr &a1 = *(*((const CAttr **)elem1));
const CAttr &a2 = *(*((const CAttr **)elem2));
RINOZ(MyCompare(a1.Type, a2.Type));
RINOZ(MyCompare(a1.Name, a2.Name));
return MyCompare(a1.LowVcn, a2.LowVcn);
}
UInt32 CAttr::Parse(const Byte *p, unsigned size)
{
if (size < 4)
return 0;
G32(p, Type);
if (Type == 0xFFFFFFFF)
return 4;
if (size < 0x18)
return 0;
PRF(printf(" T=%2X", Type));
UInt32 length = Get32(p + 0x04);
PRF(printf(" L=%3d", length));
if (length > size)
return 0;
NonResident = p[0x08];
{
int nameLength = p[9];
UInt32 nameOffset = Get16(p + 0x0A);
if (nameLength != 0)
{
if (nameOffset + nameLength * 2 > length)
return 0;
GetString(p + nameOffset, nameLength, Name);
PRF(printf(" N=%S", Name));
}
}
// G16(p + 0x0C, Flags);
// G16(p + 0x0E, Instance);
// PRF(printf(" F=%4X", Flags));
// PRF(printf(" Inst=%d", Instance));
UInt32 dataSize;
UInt32 offs;
if (NonResident)
{
if (length < 0x40)
return 0;
PRF(printf(" NR"));
G64(p + 0x10, LowVcn);
G64(p + 0x18, HighVcn);
G64(p + 0x28, AllocatedSize);
G64(p + 0x30, Size);
G64(p + 0x38, InitializedSize);
G16(p + 0x20, offs);
CompressionUnit = p[0x22];
PackSize = Size;
if (CompressionUnit != 0)
{
if (length < 0x48)
return 0;
G64(p + 0x40, PackSize);
PRF(printf(" PS=%I64x", PackSize));
}
// PRF(printf("\n"));
PRF(printf(" ASize=%4I64d", AllocatedSize));
PRF(printf(" Size=%I64d", Size));
PRF(printf(" IS=%I64d", InitializedSize));
PRF(printf(" Low=%I64d", LowVcn));
PRF(printf(" High=%I64d", HighVcn));
PRF(printf(" CU=%d", (int)CompressionUnit));
dataSize = length - offs;
}
else
{
if (length < 0x18)
return 0;
PRF(printf(" RES"));
dataSize = Get32(p + 0x10);
PRF(printf(" dataSize=%3d", dataSize));
offs = Get16(p + 0x14);
// G16(p + 0x16, ResidentFlags);
// PRF(printf(" ResFlags=%4X", ResidentFlags));
}
if (offs > length || dataSize > length || length - dataSize < offs)
return 0;
Data.SetCapacity(dataSize);
memcpy(Data, p + offs, dataSize);
#ifdef SHOW_DEBUG_INFO
PRF(printf(" : "));
for (unsigned i = 0; i < Data.GetCapacity(); i++)
{
PRF(printf(" %02X", (int)Data[i]));
}
#endif
return length;
}
bool CAttr::ParseExtents(CRecordVector<CExtent> &extents, UInt64 numClustersMax, int compressionUnit) const
{
const Byte *p = Data;
unsigned size = (unsigned)Data.GetCapacity();
UInt64 vcn = LowVcn;
UInt64 lcn = 0;
UInt64 highVcn1 = HighVcn + 1;
if (LowVcn != extents.Back().Virt || highVcn1 > (UInt64)1 << 63)
return false;
extents.DeleteBack();
PRF2(printf("\n# ParseExtents # LowVcn = %4I64X # HighVcn = %4I64X", LowVcn, HighVcn));
while (size > 0)
{
Byte b = *p++;
size--;
if (b == 0)
break;
UInt32 num = b & 0xF;
if (num == 0 || num > 8 || num > size)
return false;
int i;
UInt64 vSize = p[num - 1];
for (i = (int)num - 2; i >= 0; i--)
vSize = (vSize << 8) | p[i];
if (vSize == 0)
return false;
p += num;
size -= num;
if ((highVcn1 - vcn) < vSize)
return false;
num = (b >> 4) & 0xF;
if (num > 8 || num > size)
return false;
CExtent e;
e.Virt = vcn;
if (num == 0)
{
if (compressionUnit == 0)
return false;
e.Phy = kEmptyExtent;
}
else
{
Int64 v = (signed char)p[num - 1];
for (i = (int)num - 2; i >= 0; i--)
v = (v << 8) | p[i];
p += num;
size -= num;
lcn += v;
if (lcn > numClustersMax)
return false;
e.Phy = lcn;
}
extents.Add(e);
vcn += vSize;
}
CExtent e;
e.Phy = kEmptyExtent;
e.Virt = vcn;
extents.Add(e);
return (highVcn1 == vcn);
}
static const UInt64 kEmptyTag = (UInt64)(Int64)-1;
static const int kNumCacheChunksLog = 1;
static const UInt32 kNumCacheChunks = (1 << kNumCacheChunksLog);
class CInStream:
public IInStream,
public CMyUnknownImp
{
UInt64 _virtPos;
UInt64 _physPos;
UInt64 _curRem;
bool _sparseMode;
size_t _compressedPos;
UInt64 _tags[kNumCacheChunks];
int _chunkSizeLog;
CByteBuffer _inBuf;
CByteBuffer _outBuf;
public:
CMyComPtr<IInStream> Stream;
UInt64 Size;
UInt64 InitializedSize;
int BlockSizeLog;
int CompressionUnit;
bool InUse;
CRecordVector<CExtent> Extents;
HRESULT SeekToPhys() { return Stream->Seek(_physPos, STREAM_SEEK_SET, NULL); }
UInt32 GetCuSize() const { return (UInt32)1 << (BlockSizeLog + CompressionUnit); }
HRESULT InitAndSeek(int compressionUnit)
{
CompressionUnit = compressionUnit;
if (compressionUnit != 0)
{
UInt32 cuSize = GetCuSize();
_inBuf.SetCapacity(cuSize);
_chunkSizeLog = BlockSizeLog + CompressionUnit;
_outBuf.SetCapacity(kNumCacheChunks << _chunkSizeLog);
}
for (int i = 0; i < kNumCacheChunks; i++)
_tags[i] = kEmptyTag;
_sparseMode = false;
_curRem = 0;
_virtPos = 0;
_physPos = 0;
const CExtent &e = Extents[0];
if (!e.IsEmpty())
_physPos = e.Phy << BlockSizeLog;
return SeekToPhys();
}
MY_UNKNOWN_IMP1(IInStream)
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
};
static size_t Lznt1Dec(Byte *dest, size_t outBufLim, size_t destLen, const Byte *src, size_t srcLen)
{
size_t destSize = 0;
while (destSize < destLen)
{
if (srcLen < 2 || (destSize & 0xFFF) != 0)
break;
UInt32 v = Get16(src);
if (v == 0)
break;
src += 2;
srcLen -= 2;
UInt32 comprSize = (v & 0xFFF) + 1;
if (comprSize > srcLen)
break;
srcLen -= comprSize;
if ((v & 0x8000) == 0)
{
if (comprSize != (1 << 12))
break;
memcpy(dest + destSize, src, comprSize);
src += comprSize;
destSize += comprSize;
}
else
{
if (destSize + (1 << 12) > outBufLim || (src[0] & 1) != 0)
return 0;
int numDistBits = 4;
UInt32 sbOffset = 0;
UInt32 pos = 0;
do
{
comprSize--;
for (UInt32 mask = src[pos++] | 0x100; mask > 1 && comprSize > 0; mask >>= 1)
{
if ((mask & 1) == 0)
{
if (sbOffset >= (1 << 12))
return 0;
dest[destSize++] = src[pos++];
sbOffset++;
comprSize--;
}
else
{
if (comprSize < 2)
return 0;
UInt32 v = Get16(src + pos);
pos += 2;
comprSize -= 2;
while (((sbOffset - 1) >> numDistBits) != 0)
numDistBits++;
UInt32 len = (v & (0xFFFF >> numDistBits)) + 3;
if (sbOffset + len > (1 << 12))
return 0;
UInt32 dist = (v >> (16 - numDistBits));
if (dist >= sbOffset)
return 0;
Int32 offs = -1 - dist;
Byte *p = dest + destSize;
for (UInt32 t = 0; t < len; t++)
p[t] = p[t + offs];
destSize += len;
sbOffset += len;
}
}
}
while (comprSize > 0);
src += pos;
}
}
return destSize;
}
STDMETHODIMP CInStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
if (processedSize != NULL)
*processedSize = 0;
if (_virtPos >= Size)
return (Size == _virtPos) ? S_OK: E_FAIL;
if (size == 0)
return S_OK;
UInt64 rem = Size - _virtPos;
if (size > rem)
size = (UInt32)rem;
if (_virtPos >= InitializedSize)
{
memset((Byte *)data, 0, size);
_virtPos += size;
*processedSize = size;
return S_OK;
}
rem = InitializedSize - _virtPos;
if (size > rem)
size = (UInt32)rem;
while (_curRem == 0)
{
UInt64 cacheTag = _virtPos >> _chunkSizeLog;
UInt32 cacheIndex = (UInt32)cacheTag & (kNumCacheChunks - 1);
if (_tags[cacheIndex] == cacheTag)
{
UInt32 chunkSize = (UInt32)1 << _chunkSizeLog;
UInt32 offset = (UInt32)_virtPos & (chunkSize - 1);
UInt32 cur = MyMin(chunkSize - offset, size);
memcpy(data, _outBuf + (cacheIndex << _chunkSizeLog) + offset, cur);
*processedSize = cur;
_virtPos += cur;
return S_OK;
}
PRF2(printf("\nVirtPos = %6d", _virtPos));
UInt32 comprUnitSize = (UInt32)1 << CompressionUnit;
UInt64 virtBlock = _virtPos >> BlockSizeLog;
UInt64 virtBlock2 = virtBlock & ~((UInt64)comprUnitSize - 1);
int left = 0, right = Extents.Size();
for (;;)
{
int mid = (left + right) / 2;
if (mid == left)
break;
if (virtBlock2 < Extents[mid].Virt)
right = mid;
else
left = mid;
}
bool isCompressed = false;
UInt64 virtBlock2End = virtBlock2 + comprUnitSize;
if (CompressionUnit != 0)
for (int i = left; i < Extents.Size(); i++)
{
const CExtent &e = Extents[i];
if (e.Virt >= virtBlock2End)
break;
if (e.IsEmpty())
{
isCompressed = true;
break;
}
}
int i;
for (i = left; Extents[i + 1].Virt <= virtBlock; i++);
_sparseMode = false;
if (!isCompressed)
{
const CExtent &e = Extents[i];
UInt64 newPos = (e.Phy << BlockSizeLog) + _virtPos - (e.Virt << BlockSizeLog);
if (newPos != _physPos)
{
_physPos = newPos;
RINOK(SeekToPhys());
}
UInt64 next = Extents[i + 1].Virt;
if (next > virtBlock2End)
next &= ~((UInt64)comprUnitSize - 1);
next <<= BlockSizeLog;
if (next > Size)
next = Size;
_curRem = next - _virtPos;
break;
}
bool thereArePhy = false;
for (int i2 = left; i2 < Extents.Size(); i2++)
{
const CExtent &e = Extents[i2];
if (e.Virt >= virtBlock2End)
break;
if (!e.IsEmpty())
{
thereArePhy = true;
break;
}
}
if (!thereArePhy)
{
_curRem = (Extents[i + 1].Virt << BlockSizeLog) - _virtPos;
_sparseMode = true;
break;
}
size_t offs = 0;
UInt64 curVirt = virtBlock2;
for (i = left; i < Extents.Size(); i++)
{
const CExtent &e = Extents[i];
if (e.IsEmpty())
break;
if (e.Virt >= virtBlock2End)
return S_FALSE;
UInt64 newPos = (e.Phy + (curVirt - e.Virt)) << BlockSizeLog;
if (newPos != _physPos)
{
_physPos = newPos;
RINOK(SeekToPhys());
}
UInt64 numChunks = Extents[i + 1].Virt - curVirt;
if (curVirt + numChunks > virtBlock2End)
numChunks = virtBlock2End - curVirt;
size_t compressed = (size_t)numChunks << BlockSizeLog;
RINOK(ReadStream_FALSE(Stream, _inBuf + offs, compressed));
curVirt += numChunks;
_physPos += compressed;
offs += compressed;
}
size_t destLenMax = GetCuSize();
size_t destLen = destLenMax;
UInt64 rem = Size - (virtBlock2 << BlockSizeLog);
if (destLen > rem)
destLen = (size_t)rem;
Byte *dest = _outBuf + (cacheIndex << _chunkSizeLog);
size_t destSizeRes = Lznt1Dec(dest, destLenMax, destLen, _inBuf, offs);
_tags[cacheIndex] = cacheTag;
// some files in Vista have destSize > destLen
if (destSizeRes < destLen)
{
memset(dest, 0, destLenMax);
if (InUse)
return S_FALSE;
}
}
if (size > _curRem)
size = (UInt32)_curRem;
HRESULT res = S_OK;
if (_sparseMode)
memset(data, 0, size);
else
{
res = Stream->Read(data, size, &size);
_physPos += size;
}
if (processedSize != NULL)
*processedSize = size;
_virtPos += size;
_curRem -= size;
return res;
}
STDMETHODIMP CInStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)
{
UInt64 newVirtPos = offset;
switch(seekOrigin)
{
case STREAM_SEEK_SET: break;
case STREAM_SEEK_CUR: newVirtPos += _virtPos; break;
case STREAM_SEEK_END: newVirtPos += Size; break;
default: return STG_E_INVALIDFUNCTION;
}
if (_virtPos != newVirtPos)
_curRem = 0;
_virtPos = newVirtPos;
if (newPosition)
*newPosition = newVirtPos;
return S_OK;
}
class CByteBufStream:
public IInStream,
public CMyUnknownImp
{
UInt64 _virtPos;
public:
CByteBuffer Buf;
void Init() { _virtPos = 0; }
MY_UNKNOWN_IMP1(IInStream)
STDMETHOD(Read)(void *data, UInt32 size, UInt32 *processedSize);
STDMETHOD(Seek)(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition);
};
STDMETHODIMP CByteBufStream::Read(void *data, UInt32 size, UInt32 *processedSize)
{
if (processedSize != NULL)
*processedSize = 0;
if (_virtPos >= Buf.GetCapacity())
return (_virtPos == Buf.GetCapacity()) ? S_OK: E_FAIL;
UInt64 rem = Buf.GetCapacity() - _virtPos;
if (rem < size)
size = (UInt32)rem;
memcpy(data, Buf + (size_t)_virtPos, size);
if (processedSize != NULL)
*processedSize = size;
_virtPos += size;
return S_OK;
}
STDMETHODIMP CByteBufStream::Seek(Int64 offset, UInt32 seekOrigin, UInt64 *newPosition)
{
switch(seekOrigin)
{
case STREAM_SEEK_SET: _virtPos = offset; break;
case STREAM_SEEK_CUR: _virtPos += offset; break;
case STREAM_SEEK_END: _virtPos = Buf.GetCapacity() + offset; break;
default: return STG_E_INVALIDFUNCTION;
}
if (newPosition)
*newPosition = _virtPos;
return S_OK;
}
HRESULT DataParseExtents(int clusterSizeLog, const CObjectVector<CAttr> attrs,
int attrIndex, int attrIndexLim, UInt64 numPhysClusters, CRecordVector<CExtent> &Extents)
{
CExtent e;
e.Virt = 0;
e.Phy = kEmptyExtent;
Extents.Add(e);
const CAttr &attr0 = attrs[attrIndex];
if (attr0.AllocatedSize < attr0.Size ||
(attrs[attrIndexLim - 1].HighVcn + 1) != (attr0.AllocatedSize >> clusterSizeLog) ||
(attr0.AllocatedSize & ((1 << clusterSizeLog) - 1)) != 0)
return S_FALSE;
for (int i = attrIndex; i < attrIndexLim; i++)
if (!attrs[i].ParseExtents(Extents, numPhysClusters, attr0.CompressionUnit))
return S_FALSE;
UInt64 packSizeCalc = 0;
for (int k = 0; k < Extents.Size(); k++)
{
CExtent &e = Extents[k];
if (!e.IsEmpty())
packSizeCalc += (Extents[k + 1].Virt - e.Virt) << clusterSizeLog;
PRF2(printf("\nSize = %4I64X", Extents[k + 1].Virt - e.Virt));
PRF2(printf(" Pos = %4I64X", e.Phy));
}
if (attr0.CompressionUnit != 0)
{
if (packSizeCalc != attr0.PackSize)
return S_FALSE;
}
else
{
if (packSizeCalc != attr0.AllocatedSize)
return S_FALSE;
}
return S_OK;
}
struct CDataRef
{
int Start;
int Num;
};
static const UInt32 kMagic_FILE = 0x454c4946;
static const UInt32 kMagic_BAAD = 0x44414142;
struct CMftRec
{
UInt32 Magic;
// UInt64 Lsn;
UInt16 SeqNumber;
UInt16 Flags;
// UInt16 LinkCount;
// UInt16 NextAttrInstance;
CMftRef BaseMftRef;
// UInt32 ThisRecNumber;
UInt32 MyNumNameLinks;
CObjectVector<CAttr> DataAttrs;
CObjectVector<CFileNameAttr> FileNames;
CRecordVector<CDataRef> DataRefs;
CSiAttr SiAttr;
void MoveAttrsFrom(CMftRec &src)
{
DataAttrs += src.DataAttrs;
FileNames += src.FileNames;
src.DataAttrs.ClearAndFree();
src.FileNames.ClearAndFree();
}
UInt64 GetPackSize() const
{
UInt64 res = 0;
for (int i = 0; i < DataRefs.Size(); i++)
res += DataAttrs[DataRefs[i].Start].GetPackSize();
return res;
}
bool Parse(Byte *p, int sectorSizeLog, UInt32 numSectors, UInt32 recNumber, CObjectVector<CAttr> *attrs);
bool IsEmpty() const { return (Magic <= 2); }
bool IsFILE() const { return (Magic == kMagic_FILE); }
bool IsBAAD() const { return (Magic == kMagic_BAAD); }
bool InUse() const { return (Flags & 1) != 0; }
bool IsDir() const { return (Flags & 2) != 0; }
void ParseDataNames();
HRESULT GetStream(IInStream *mainStream, int dataIndex,
int clusterSizeLog, UInt64 numPhysClusters, IInStream **stream) const;
UInt64 GetSize(int dataIndex) const { return DataAttrs[DataRefs[dataIndex].Start].GetSize(); }
CMftRec(): MyNumNameLinks(0) {}
};
void CMftRec::ParseDataNames()
{
DataRefs.Clear();
DataAttrs.Sort(CompareAttr, 0);
for (int i = 0; i < DataAttrs.Size();)
{
CDataRef ref;
ref.Start = i;
for (i++; i < DataAttrs.Size(); i++)
if (DataAttrs[ref.Start].Name != DataAttrs[i].Name)
break;
ref.Num = i - ref.Start;
DataRefs.Add(ref);
}
}
HRESULT CMftRec::GetStream(IInStream *mainStream, int dataIndex,
int clusterSizeLog, UInt64 numPhysClusters, IInStream **destStream) const
{
*destStream = 0;
CByteBufStream *streamSpec = new CByteBufStream;
CMyComPtr<IInStream> streamTemp = streamSpec;
if (dataIndex < 0)
return E_FAIL;
if (dataIndex < DataRefs.Size())
{
const CDataRef &ref = DataRefs[dataIndex];
int numNonResident = 0;
int i;
for (i = ref.Start; i < ref.Start + ref.Num; i++)
if (DataAttrs[i].NonResident)
numNonResident++;
const CAttr &attr0 = DataAttrs[ref.Start];
if (numNonResident != 0 || ref.Num != 1)
{
if (numNonResident != ref.Num || !attr0.IsCompressionUnitSupported())
return S_FALSE;
CInStream *streamSpec = new CInStream;
CMyComPtr<IInStream> streamTemp = streamSpec;
RINOK(DataParseExtents(clusterSizeLog, DataAttrs, ref.Start, ref.Start + ref.Num, numPhysClusters, streamSpec->Extents));
streamSpec->Size = attr0.Size;
streamSpec->InitializedSize = attr0.InitializedSize;
streamSpec->Stream = mainStream;
streamSpec->BlockSizeLog = clusterSizeLog;
streamSpec->InUse = InUse();
RINOK(streamSpec->InitAndSeek(attr0.CompressionUnit));
*destStream = streamTemp.Detach();
return S_OK;
}
streamSpec->Buf = attr0.Data;
}
streamSpec->Init();
*destStream = streamTemp.Detach();
return S_OK;
}
bool CMftRec::Parse(Byte *p, int sectorSizeLog, UInt32 numSectors, UInt32 recNumber,
CObjectVector<CAttr> *attrs)
{
G32(p, Magic);
if (!IsFILE())
return IsEmpty() || IsBAAD();
UInt32 usaOffset;
UInt32 numUsaItems;
G16(p + 0x04, usaOffset);
G16(p + 0x06, numUsaItems);
if ((usaOffset & 1) != 0 || usaOffset + numUsaItems * 2 > ((UInt32)1 << sectorSizeLog) - 2 ||
numUsaItems == 0 || numUsaItems - 1 != numSectors)
return false;
UInt16 usn = Get16(p + usaOffset);
// PRF(printf("\nusn = %d", usn));
for (UInt32 i = 1; i < numUsaItems; i++)
{
void *pp = p + (i << sectorSizeLog) - 2;
if (Get16(pp) != usn)
return false;
SetUi16(pp, Get16(p + usaOffset + i * 2));
}
// G64(p + 0x08, Lsn);
G16(p + 0x10, SeqNumber);
// G16(p + 0x12, LinkCount);
// PRF(printf(" L=%d", LinkCount));
UInt32 attrOffs = Get16(p + 0x14);
G16(p + 0x16, Flags);
PRF(printf(" F=%4X", Flags));
UInt32 bytesInUse = Get32(p + 0x18);
UInt32 bytesAlloc = Get32(p + 0x1C);
G64(p + 0x20, BaseMftRef.Val);
if (BaseMftRef.Val != 0)
{
PRF(printf(" BaseRef=%d", (int)BaseMftRef.Val));
// return false; // Check it;
}
// G16(p + 0x28, NextAttrInstance);
if (usaOffset >= 0x30)
if (Get32(p + 0x2C) != recNumber) // NTFS 3.1+
return false;
UInt32 limit = numSectors << sectorSizeLog;
if (attrOffs >= limit || (attrOffs & 7) != 0 || bytesInUse > limit
|| bytesAlloc != limit)
return false;
for (UInt32 t = attrOffs; t < limit;)
{
CAttr attr;
// PRF(printf("\n %2d:", Attrs.Size()));
PRF(printf("\n"));
UInt32 length = attr.Parse(p + t, limit - t);
if (length == 0 || limit - t < length)
return false;
t += length;
if (attr.Type == 0xFFFFFFFF)
break;
switch(attr.Type)
{
case ATTR_TYPE_FILE_NAME:
{
CFileNameAttr fna;
if (!attr.ParseFileName(fna))
return false;
FileNames.Add(fna);
PRF(printf(" flags = %4x", (int)fna.NameType));
PRF(printf("\n %S", fna.Name));
break;
}
case ATTR_TYPE_STANDARD_INFO:
if (!attr.ParseSi(SiAttr))
return false;
break;
case ATTR_TYPE_DATA:
DataAttrs.Add(attr);
break;
default:
if (attrs)
attrs->Add(attr);
break;
}
}
return true;
}
struct CItem
{
int RecIndex;
int DataIndex;
CMftRef ParentRef;
UString Name;
UInt32 Attrib;
bool IsDir() const { return (DataIndex < 0); }
};
struct CDatabase
{
CHeader Header;
CObjectVector<CItem> Items;
CObjectVector<CMftRec> Recs;
CMyComPtr<IInStream> InStream;
IArchiveOpenCallback *OpenCallback;
CByteBuffer ByteBuf;
CObjectVector<CAttr> VolAttrs;
~CDatabase() { ClearAndClose(); }
void Clear();
void ClearAndClose();
UString GetItemPath(Int32 index) const;
HRESULT Open();
HRESULT ReadDir(Int32 parent, UInt32 cluster, int level);
HRESULT SeekToCluster(UInt64 cluster);
int FindMtfRec(const CMftRef &ref) const
{
UInt64 val = ref.GetIndex();
int left = 0, right = Items.Size();
while (left != right)
{
int mid = (left + right) / 2;
UInt64 midValue = Items[mid].RecIndex;
if (val == midValue)
return mid;
if (val < midValue)
right = mid;
else
left = mid + 1;
}
return -1;
}
};
HRESULT CDatabase::SeekToCluster(UInt64 cluster)
{
return InStream->Seek(cluster << Header.ClusterSizeLog, STREAM_SEEK_SET, NULL);
}
void CDatabase::Clear()
{
Items.Clear();
Recs.Clear();
}
void CDatabase::ClearAndClose()
{
Clear();
InStream.Release();
}
#define MY_DIR_PREFIX(x) L"[" x L"]" WSTRING_PATH_SEPARATOR
UString CDatabase::GetItemPath(Int32 index) const
{
const CItem *item = &Items[index];
UString name = item->Name;
for (int j = 0; j < 256; j++)
{
CMftRef ref = item->ParentRef;
index = FindMtfRec(ref);
if (ref.GetIndex() == 5)
return name;
if (index < 0 || Recs[Items[index].RecIndex].SeqNumber != ref.GetNumber())
return MY_DIR_PREFIX(L"UNKNOWN") + name;
item = &Items[index];
name = item->Name + WCHAR_PATH_SEPARATOR + name;
}
return MY_DIR_PREFIX(L"BAD") + name;
}
HRESULT CDatabase::Open()
{
Clear();
static const UInt32 kHeaderSize = 512;
Byte buf[kHeaderSize];
RINOK(ReadStream_FALSE(InStream, buf, kHeaderSize));
if (!Header.Parse(buf))
return S_FALSE;
UInt64 fileSize;
RINOK(InStream->Seek(0, STREAM_SEEK_END, &fileSize));
if (fileSize < Header.GetPhySize())
return S_FALSE;
SeekToCluster(Header.MftCluster);
CMftRec mftRec;
UInt32 numSectorsInRec;
int recSizeLog;
CMyComPtr<IInStream> mftStream;
{
UInt32 blockSize = 1 << 12;
ByteBuf.SetCapacity(blockSize);
RINOK(ReadStream_FALSE(InStream, ByteBuf, blockSize));
UInt32 allocSize = Get32(ByteBuf + 0x1C);
recSizeLog = GetLog(allocSize);
if (recSizeLog < Header.SectorSizeLog)
return false;
numSectorsInRec = 1 << (recSizeLog - Header.SectorSizeLog);
if (!mftRec.Parse(ByteBuf, Header.SectorSizeLog, numSectorsInRec, NULL, 0))
return S_FALSE;
if (!mftRec.IsFILE())
return S_FALSE;
mftRec.ParseDataNames();
if (mftRec.DataRefs.IsEmpty())
return S_FALSE;
RINOK(mftRec.GetStream(InStream, 0, Header.ClusterSizeLog, Header.NumClusters, &mftStream));
if (!mftStream)
return S_FALSE;
}
UInt64 mftSize = mftRec.DataAttrs[0].Size;
if ((mftSize >> 4) > Header.GetPhySize())
return S_FALSE;
UInt64 numFiles = mftSize >> recSizeLog;
if (numFiles > (1 << 30))
return S_FALSE;
if (OpenCallback)
{
RINOK(OpenCallback->SetTotal(&numFiles, &mftSize));
}
const UInt32 kBufSize = (1 << 15);
if (kBufSize < (1 << recSizeLog))
return S_FALSE;
ByteBuf.SetCapacity((size_t)kBufSize);
Recs.Reserve((int)numFiles);
for (UInt64 pos64 = 0;;)
{
if (OpenCallback)
{
// Sleep(0);
UInt64 numFiles = Recs.Size();
RINOK(OpenCallback->SetCompleted(&numFiles, &pos64));
}
UInt32 readSize = kBufSize;
UInt64 rem = mftSize - pos64;
if (readSize > rem)
readSize = (UInt32)rem;
if (readSize < ((UInt32)1 << recSizeLog))
break;
RINOK(ReadStream_FALSE(mftStream, ByteBuf, (size_t)readSize));
pos64 += readSize;
for (int i = 0; ((UInt32)(i + 1) << recSizeLog) <= readSize; i++)
{
PRF(printf("\n---------------------"));
PRF(printf("\n%5d:", Recs.Size()));
Byte *p = ByteBuf + ((UInt32)i << recSizeLog);
CMftRec rec;
if (!rec.Parse(p, Header.SectorSizeLog, numSectorsInRec, (UInt32)Recs.Size(),
(Recs.Size() == kRecIndex_Volume) ? &VolAttrs: NULL))
return S_FALSE;
Recs.Add(rec);
}
}
int i;
for (i = 0; i < Recs.Size(); i++)
{
CMftRec &rec = Recs[i];
if (!rec.BaseMftRef.IsBaseItself())
{
UInt64 refIndex = rec.BaseMftRef.GetIndex();
if (refIndex > (UInt32)Recs.Size())
return S_FALSE;
CMftRec &refRec = Recs[(int)refIndex];
bool moveAttrs = (refRec.SeqNumber == rec.BaseMftRef.GetNumber() && refRec.BaseMftRef.IsBaseItself());
if (rec.InUse() && refRec.InUse())
{
if (!moveAttrs)
return S_FALSE;
}
else if (rec.InUse() || refRec.InUse())
moveAttrs = false;
if (moveAttrs)
refRec.MoveAttrsFrom(rec);
}
}
for (i = 0; i < Recs.Size(); i++)
Recs[i].ParseDataNames();
for (i = 0; i < Recs.Size(); i++)
{
CMftRec &rec = Recs[i];
if (!rec.IsFILE() || !rec.BaseMftRef.IsBaseItself())
continue;
int numNames = 0;
// printf("\n%4d: ", i);
for (int t = 0; t < rec.FileNames.Size(); t++)
{
const CFileNameAttr &fna = rec.FileNames[t];
// printf("%4d %S | ", (int)fna.NameType, fna.Name);
if (fna.IsDos())
continue;
int numDatas = rec.DataRefs.Size();
// For hard linked files we show substreams only for first Name.
if (numDatas > 1 && numNames > 0)
numDatas = 1;
numNames++;
if (rec.IsDir())
{
CItem item;
item.Name = fna.Name;
item.RecIndex = i;
item.DataIndex = -1;
item.ParentRef = fna.ParentDirRef;
item.Attrib = rec.SiAttr.Attrib | 0x10;
// item.Attrib = fna.Attrib;
Items.Add(item);
}
for (int di = 0; di < numDatas; di++)
{
CItem item;
item.Name = fna.Name;
item.Attrib = rec.SiAttr.Attrib;
const UString &subName = rec.DataAttrs[rec.DataRefs[di].Start].Name;
if (!subName.IsEmpty())
{
// $BadClus:$Bad is sparse file for all clusters. So we skip it.
if (i == kRecIndex_BadClus && subName == L"$Bad")
continue;
item.Name += L":";
item.Name += subName;
item.Attrib = fna.Attrib;
}
PRF(printf("\n%3d", i));
PRF(printf(" attrib=%2x", rec.SiAttr.Attrib));
PRF(printf(" %S", item.Name));
item.RecIndex = i;
item.DataIndex = di;
item.ParentRef = fna.ParentDirRef;
Items.Add(item);
rec.MyNumNameLinks++;
}
}
rec.FileNames.ClearAndFree();
}
return S_OK;
}
class CHandler:
public IInArchive,
public IInArchiveGetStream,
public CMyUnknownImp,
CDatabase
{
public:
MY_UNKNOWN_IMP2(IInArchive, IInArchiveGetStream)
INTERFACE_IInArchive(;)
STDMETHOD(GetStream)(UInt32 index, ISequentialInStream **stream);
};
STDMETHODIMP CHandler::GetStream(UInt32 index, ISequentialInStream **stream)
{
COM_TRY_BEGIN
IInStream *stream2;
const CItem &item = Items[index];
const CMftRec &rec = Recs[item.RecIndex];
HRESULT res = rec.GetStream(InStream, item.DataIndex, Header.ClusterSizeLog, Header.NumClusters, &stream2);
*stream = (ISequentialInStream *)stream2;
return res;
COM_TRY_END
}
STATPROPSTG kProps[] =
{
{ NULL, kpidPath, VT_BSTR},
{ NULL, kpidIsDir, VT_BOOL},
{ NULL, kpidSize, VT_UI8},
{ NULL, kpidPackSize, VT_UI8},
{ NULL, kpidMTime, VT_FILETIME},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidATime, VT_FILETIME},
{ NULL, kpidAttrib, VT_UI4},
{ NULL, kpidLinks, VT_UI4}
};
STATPROPSTG kArcProps[] =
{
{ NULL, kpidVolumeName, VT_BSTR},
{ NULL, kpidFileSystem, VT_BSTR},
{ NULL, kpidClusterSize, VT_UI4},
{ NULL, kpidPhySize, VT_UI8},
{ NULL, kpidHeadersSize, VT_UI8},
{ NULL, kpidCTime, VT_FILETIME},
{ NULL, kpidSectorSize, VT_UI4},
{ NULL, kpidId, VT_UI8}
// { NULL, kpidSectorsPerTrack, VT_UI4},
// { NULL, kpidNumHeads, VT_UI4},
// { NULL, kpidHiddenSectors, VT_UI4}
};
IMP_IInArchive_Props
IMP_IInArchive_ArcProps
static void NtfsTimeToProp(UInt64 t, NWindows::NCOM::CPropVariant &prop)
{
FILETIME ft;
ft.dwLowDateTime = (DWORD)t;
ft.dwHighDateTime = (DWORD)(t >> 32);
prop = ft;
}
STDMETHODIMP CHandler::GetArchiveProperty(PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CMftRec *volRec = (Recs.Size() > kRecIndex_Volume ? &Recs[kRecIndex_Volume] : NULL);
switch(propID)
{
case kpidClusterSize: prop = Header.ClusterSize(); break;
case kpidPhySize: prop = Header.GetPhySize(); break;
/*
case kpidHeadersSize:
{
UInt64 val = 0;
for (int i = 0; i < kNumSysRecs; i++)
{
printf("\n%2d: %8I64d ", i, Recs[i].GetPackSize());
if (i == 8)
i = i
val += Recs[i].GetPackSize();
}
prop = val;
break;
}
*/
case kpidCTime: if (volRec) NtfsTimeToProp(volRec->SiAttr.CTime, prop); break;break;
case kpidVolumeName:
{
for (int i = 0; i < VolAttrs.Size(); i++)
{
const CAttr &attr = VolAttrs[i];
if (attr.Type == ATTR_TYPE_VOLUME_NAME)
{
UString name;
GetString(attr.Data, (int)attr.Data.GetCapacity() / 2, name);
prop = name;
break;
}
}
break;
}
case kpidFileSystem:
{
AString s = "NTFS";
for (int i = 0; i < VolAttrs.Size(); i++)
{
const CAttr &attr = VolAttrs[i];
if (attr.Type == ATTR_TYPE_VOLUME_INFO)
{
CVolInfo vi;
if (attr.ParseVolInfo(vi))
{
s += ' ';
char temp[16];
ConvertUInt32ToString(vi.MajorVer, temp);
s += temp;
s += '.';
ConvertUInt32ToString(vi.MinorVer, temp);
s += temp;
}
break;
}
}
prop = s;
break;
}
case kpidSectorSize: prop = (UInt32)1 << Header.SectorSizeLog; break;
case kpidId: prop = Header.SerialNumber; break;
// case kpidMediaType: prop = Header.MediaType; break;
// case kpidSectorsPerTrack: prop = Header.SectorsPerTrack; break;
// case kpidNumHeads: prop = Header.NumHeads; break;
// case kpidHiddenSectors: prop = Header.NumHiddenSectors; break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetProperty(UInt32 index, PROPID propID, PROPVARIANT *value)
{
COM_TRY_BEGIN
NWindows::NCOM::CPropVariant prop;
const CItem &item = Items[index];
const CMftRec &rec = Recs[item.RecIndex];
const CAttr *data= NULL;
if (item.DataIndex >= 0)
data = &rec.DataAttrs[rec.DataRefs[item.DataIndex].Start];
switch(propID)
{
case kpidPath:
{
UString name = GetItemPath(index);
const wchar_t *prefix = NULL;
if (!rec.InUse())
prefix = MY_DIR_PREFIX(L"DELETED");
else if (item.RecIndex < kNumSysRecs)
prefix = MY_DIR_PREFIX(L"SYSTEM");
if (prefix)
name = prefix + name;
prop = name;
break;
}
case kpidIsDir: prop = item.IsDir(); break;
case kpidMTime: NtfsTimeToProp(rec.SiAttr.MTime, prop); break;
case kpidCTime: NtfsTimeToProp(rec.SiAttr.CTime, prop); break;
case kpidATime: NtfsTimeToProp(rec.SiAttr.ATime, prop); break;
case kpidAttrib:
prop = item.Attrib;
break;
case kpidLinks: prop = rec.MyNumNameLinks; break;
case kpidSize: if (data) prop = data->GetSize(); break;
case kpidPackSize: if (data) prop = data->GetPackSize(); break;
}
prop.Detach(value);
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::Open(IInStream *stream, const UInt64 *, IArchiveOpenCallback *callback)
{
COM_TRY_BEGIN
{
OpenCallback = callback;
InStream = stream;
HRESULT res;
try
{
res = CDatabase::Open();
if (res == S_OK)
return S_OK;
}
catch(...)
{
Close();
throw;
}
Close();
return res;
}
COM_TRY_END
}
STDMETHODIMP CHandler::Close()
{
ClearAndClose();
return S_OK;
}
STDMETHODIMP CHandler::Extract(const UInt32 *indices, UInt32 numItems,
Int32 testMode, IArchiveExtractCallback *extractCallback)
{
COM_TRY_BEGIN
bool allFilesMode = (numItems == (UInt32)-1);
if (allFilesMode)
numItems = Items.Size();
if (numItems == 0)
return S_OK;
UInt32 i;
UInt64 totalSize = 0;
for (i = 0; i < numItems; i++)
{
const CItem &item = Items[allFilesMode ? i : indices[i]];
const CMftRec &rec = Recs[item.RecIndex];
if (!rec.IsDir())
totalSize += rec.GetSize(item.DataIndex);
}
RINOK(extractCallback->SetTotal(totalSize));
UInt64 totalPackSize;
totalSize = totalPackSize = 0;
CByteBuffer buf;
UInt32 clusterSize = Header.ClusterSize();
buf.SetCapacity(clusterSize);
NCompress::CCopyCoder *copyCoderSpec = new NCompress::CCopyCoder();
CMyComPtr<ICompressCoder> copyCoder = copyCoderSpec;
CLocalProgress *lps = new CLocalProgress;
CMyComPtr<ICompressProgressInfo> progress = lps;
lps->Init(extractCallback, false);
CDummyOutStream *outStreamSpec = new CDummyOutStream;
CMyComPtr<ISequentialOutStream> outStream(outStreamSpec);
for (i = 0; i < numItems; i++)
{
lps->InSize = totalPackSize;
lps->OutSize = totalSize;
RINOK(lps->SetCur());
CMyComPtr<ISequentialOutStream> realOutStream;
Int32 askMode = testMode ?
NExtract::NAskMode::kTest :
NExtract::NAskMode::kExtract;
Int32 index = allFilesMode ? i : indices[i];
RINOK(extractCallback->GetStream(index, &realOutStream, askMode));
const CItem &item = Items[index];
if (item.IsDir())
{
RINOK(extractCallback->PrepareOperation(askMode));
RINOK(extractCallback->SetOperationResult(NExtract::NOperationResult::kOK));
continue;
}
if (!testMode && !realOutStream)
continue;
RINOK(extractCallback->PrepareOperation(askMode));
outStreamSpec->SetStream(realOutStream);
realOutStream.Release();
outStreamSpec->Init();
const CMftRec &rec = Recs[item.RecIndex];
const CAttr &data = rec.DataAttrs[rec.DataRefs[item.DataIndex].Start];
int res = NExtract::NOperationResult::kDataError;
{
CMyComPtr<IInStream> inStream;
HRESULT hres = rec.GetStream(InStream, item.DataIndex, Header.ClusterSizeLog, Header.NumClusters, &inStream);
if (hres == S_FALSE)
res = NExtract::NOperationResult::kUnSupportedMethod;
else
{
RINOK(hres);
if (inStream)
{
HRESULT hres = copyCoder->Code(inStream, outStream, NULL, NULL, progress);
if (hres != S_OK && hres != S_FALSE)
{
RINOK(hres);
}
if (/* copyCoderSpec->TotalSize == item.GetSize() && */ hres == S_OK)
res = NExtract::NOperationResult::kOK;
}
}
}
totalPackSize += data.GetPackSize();
totalSize += data.GetSize();
outStreamSpec->ReleaseStream();
RINOK(extractCallback->SetOperationResult(res));
}
return S_OK;
COM_TRY_END
}
STDMETHODIMP CHandler::GetNumberOfItems(UInt32 *numItems)
{
*numItems = Items.Size();
return S_OK;
}
static IInArchive *CreateArc() { return new CHandler; }
static CArcInfo g_ArcInfo =
{ L"NTFS", L"ntfs img", 0, 0xD9, { 'N', 'T', 'F', 'S', ' ', ' ', ' ', ' ', 0 }, 9, false, CreateArc, 0 };
REGISTER_ARC(Fat)
}}
<file_sep>/FBReader/zlibrary/ui/src/qt4/dialogs/ZLQtSelectionDialog.h
/*
* Copyright (C) 2004-2010 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
* 02110-1301, USA.
*/
#ifndef __ZLQTSELECTIONDIALOG_H__
#define __ZLQTSELECTIONDIALOG_H__
#include <string>
#include <map>
#include <QtGui/QDialog>
#include <QtGui/QPainter>
#include <QtGui/QListWidget>
#include "../../../../core/src/desktop/dialogs/ZLDesktopSelectionDialog.h"
class QVBox;
class QLineEdit;
class ZLQtSelectionDialogItem : public QListWidgetItem {
public:
ZLQtSelectionDialogItem(QListWidget *listWidget, const ZLTreeNodePtr node);
ZLTreeNodePtr node() const { return myNode; }
private:
ZLTreeNodePtr myNode;
};
class ZLQListWidget : public QListWidget {
Q_OBJECT
public:
ZLQListWidget(QWidget *parent);
Q_SIGNALS:
void returnPressed();
private:
void keyPressEvent(QKeyEvent *event);
};
class ZLQtSelectionDialog : public QDialog, public ZLDesktopSelectionDialog {
Q_OBJECT
public:
ZLQtSelectionDialog(const std::string &caption, ZLTreeHandler &handler);
~ZLQtSelectionDialog();
bool run();
private:
QIcon &getIcon(const ZLTreeNodePtr node);
protected:
void keyPressEvent(QKeyEvent *event);
void setSize(int width, int height) { QDialog::resize(width, height); }
int width() const { return QDialog::width(); }
int height() const { return QDialog::height(); }
void exitDialog();
void updateStateLine();
void updateList();
void selectItem(int index);
private Q_SLOTS:
void runNodeSlot();
void accept();
private:
QLineEdit *myStateLine;
ZLQListWidget *myListWidget;
std::map<std::string,QIcon*> myIcons;
};
#endif /* __ZLQTSELECTIONDIALOG_H__ */
<file_sep>/7-Zip/CPP/7zip/Crypto/ZipCrypto.cpp
// Crypto/ZipCrypto.cpp
#include "StdAfx.h"
#include "../../../C/7zCrc.h"
#include "../Common/StreamUtils.h"
#include "RandGen.h"
#include "ZipCrypto.h"
namespace NCrypto {
namespace NZip {
void CCipher::UpdateKeys(Byte b)
{
Keys[0] = CRC_UPDATE_BYTE(Keys[0], b);
Keys[1] += Keys[0] & 0xff;
Keys[1] = Keys[1] * 134775813L + 1;
Keys[2] = CRC_UPDATE_BYTE(Keys[2], (Byte)(Keys[1] >> 24));
}
void CCipher::SetPassword(const Byte *password, UInt32 passwordLen)
{
Keys[0] = 305419896L;
Keys[1] = 591751049L;
Keys[2] = 878082192L;
for (UInt32 i = 0; i < passwordLen; i++)
UpdateKeys(password[i]);
}
Byte CCipher::DecryptByteSpec()
{
UInt32 temp = Keys[2] | 2;
return (Byte)((temp * (temp ^ 1)) >> 8);
}
Byte CCipher::DecryptByte(Byte b)
{
Byte c = (Byte)(b ^ DecryptByteSpec());
UpdateKeys(c);
return c;
}
Byte CCipher::EncryptByte(Byte b)
{
Byte c = (Byte)(b ^ DecryptByteSpec());
UpdateKeys(b);
return c;
}
void CCipher::DecryptHeader(Byte *buf)
{
for (unsigned i = 0; i < kHeaderSize; i++)
buf[i] = DecryptByte(buf[i]);
}
void CCipher::EncryptHeader(Byte *buf)
{
for (unsigned i = 0; i < kHeaderSize; i++)
buf[i] = EncryptByte(buf[i]);
}
STDMETHODIMP CEncoder::CryptoSetPassword(const Byte *data, UInt32 size)
{
_cipher.SetPassword(data, size);
return S_OK;
}
STDMETHODIMP CEncoder::CryptoSetCRC(UInt32 crc)
{
_crc = crc;
return S_OK;
}
STDMETHODIMP CEncoder::Init()
{
return S_OK;
}
HRESULT CEncoder::WriteHeader(ISequentialOutStream *outStream)
{
Byte header[kHeaderSize];
g_RandomGenerator.Generate(header, kHeaderSize - 2);
header[kHeaderSize - 1] = Byte(_crc >> 24);
header[kHeaderSize - 2] = Byte(_crc >> 16);
_cipher.EncryptHeader(header);
return WriteStream(outStream, header, kHeaderSize);
}
STDMETHODIMP_(UInt32) CEncoder::Filter(Byte *data, UInt32 size)
{
UInt32 i;
for (i = 0; i < size; i++)
data[i] = _cipher.EncryptByte(data[i]);
return i;
}
STDMETHODIMP CDecoder::CryptoSetPassword(const Byte *data, UInt32 size)
{
_cipher.SetPassword(data, size);
return S_OK;
}
HRESULT CDecoder::ReadHeader(ISequentialInStream *inStream)
{
Byte header[kHeaderSize];
RINOK(ReadStream_FAIL(inStream, header, kHeaderSize));
_cipher.DecryptHeader(header);
return S_OK;
}
STDMETHODIMP CDecoder::Init()
{
return S_OK;
}
STDMETHODIMP_(UInt32) CDecoder::Filter(Byte *data, UInt32 size)
{
UInt32 i;
for (i = 0; i < size; i++)
data[i] = _cipher.DecryptByte(data[i]);
return i;
}
}}
<file_sep>/7-Zip/CPP/7zip/UI/FileManager/PluginInterface.h
// PluginInterface.h
#ifndef __PLUGININTERFACE_H
#define __PLUGININTERFACE_H
#include "Common/MyString.h"
// {23170F69-40C1-278D-0000-000100010000}
DEFINE_GUID(IID_IInitContextMenu,
0x23170F69, 0x40C1, 0x278D, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00);
MIDL_INTERFACE("23170F69-40C1-278D-0000-000100010000")
IInitContextMenu: public IUnknown
{
public:
STDMETHOD(InitContextMenu)(const wchar_t *aFolder, const wchar_t **aNames, UINT32 aNumFiles) PURE;
};
// {23170F69-40C1-278D-0000-000100020100}
DEFINE_GUID(IID_IPluginOptionsCallback,
0x23170F69, 0x40C1, 0x278D, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00);
MIDL_INTERFACE("23170F69-40C1-278D-0000-000100020000")
IPluginOptionsCallback: public IUnknown
{
public:
STDMETHOD(GetProgramFolderPath)(BSTR *value) PURE;
STDMETHOD(GetProgramPath)(BSTR *value) PURE;
STDMETHOD(GetRegistryCUPath)(BSTR *value) PURE;
};
// {23170F69-40C1-278D-0000-000100020000}
DEFINE_GUID(IID_IPluginOptions,
0x23170F69, 0x40C1, 0x278D, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x00, 0x00);
MIDL_INTERFACE("23170F69-40C1-278D-0000-000100020000")
IPluginOptions: public IUnknown
{
public:
STDMETHOD(PluginOptions)(HWND hWnd, IPluginOptionsCallback *callback) PURE;
// STDMETHOD(GetFileExtensions)(BSTR *extensions) PURE;
};
#endif
<file_sep>/SQLCEHelper/Source/AddOffset.cpp
#include "stdafx.h"
#include "AddOffset.h"
ULONG AddOffset(ULONG nCurrent, ULONG nAdd)
{
struct foobar
{
char foo;
long bar;
};
ULONG nAlign = offsetof(foobar, bar),
nRet,
nMod;
nRet = nCurrent + nAdd;
nMod = nRet % nAlign;
if(nMod)
nRet += nAlign - nMod;
return nRet;
}
<file_sep>/FingerSuite/FingerSuiteCPL/Commons.h
#pragma once
#define UWM_UPDATECONFIGURATION_MSG _T("UWM_UPDATECONFIGURATION-44E531B1_14D3_11d5_A025_006067718D04")
<file_sep>/7-Zip/CPP/7zip/Archive/Rar/RarIn.cpp
// Archive/RarIn.cpp
#include "StdAfx.h"
#include "../../../../C/7zCrc.h"
#include "Common/StringConvert.h"
#include "Common/UTFConvert.h"
#include "../../Common/LimitedStreams.h"
#include "../../Common/StreamUtils.h"
#include "../Common/FindSignature.h"
#include "RarIn.h"
namespace NArchive {
namespace NRar {
void CInArchive::ThrowExceptionWithCode(
CInArchiveException::CCauseType cause)
{
throw CInArchiveException(cause);
}
HRESULT CInArchive::Open(IInStream *inStream, const UInt64 *searchHeaderSizeLimit)
{
try
{
Close();
HRESULT res = Open2(inStream, searchHeaderSizeLimit);
if (res == S_OK)
return res;
Close();
return res;
}
catch(...) { Close(); throw; }
}
void CInArchive::Close()
{
m_Stream.Release();
}
static inline bool TestMarkerCandidate(const void *aTestBytes)
{
for (UInt32 i = 0; i < NHeader::kMarkerSize; i++)
if (((const Byte *)aTestBytes)[i] != NHeader::kMarker[i])
return false;
return true;
}
HRESULT CInArchive::FindAndReadMarker(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
{
RINOK(FindSignatureInStream(stream,
NHeader::kMarker, NHeader::kMarkerSize,
searchHeaderSizeLimit, m_ArchiveStartPosition));
m_Stream = stream;
m_Position = m_ArchiveStartPosition + NHeader::kMarkerSize;
return m_Stream->Seek(m_Position, STREAM_SEEK_SET, NULL);
}
void CInArchive::ThrowUnexpectedEndOfArchiveException()
{
ThrowExceptionWithCode(CInArchiveException::kUnexpectedEndOfArchive);
}
bool CInArchive::ReadBytesAndTestSize(void *data, UInt32 size)
{
if (m_CryptoMode)
{
const Byte *bufData = m_DecryptedDataAligned;
UInt32 bufSize = m_DecryptedDataSize;
UInt32 i;
for (i = 0; i < size && m_CryptoPos < bufSize; i++)
((Byte *)data)[i] = bufData[m_CryptoPos++];
return (i == size);
}
return (ReadStream_FALSE(m_Stream, data, size) == S_OK);
}
void CInArchive::ReadBytesAndTestResult(void *data, UInt32 size)
{
if(!ReadBytesAndTestSize(data,size))
ThrowUnexpectedEndOfArchiveException();
}
HRESULT CInArchive::ReadBytes(void *data, UInt32 size, UInt32 *processedSize)
{
size_t realProcessedSize = size;
HRESULT result = ReadStream(m_Stream, data, &realProcessedSize);
if (processedSize != NULL)
*processedSize = (UInt32)realProcessedSize;
AddToSeekValue(realProcessedSize);
return result;
}
static UInt32 CrcUpdateUInt16(UInt32 crc, UInt16 v)
{
crc = CRC_UPDATE_BYTE(crc, (Byte)(v & 0xFF));
crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 8) & 0xFF));
return crc;
}
static UInt32 CrcUpdateUInt32(UInt32 crc, UInt32 v)
{
crc = CRC_UPDATE_BYTE(crc, (Byte)(v & 0xFF));
crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 8) & 0xFF));
crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 16) & 0xFF));
crc = CRC_UPDATE_BYTE(crc, (Byte)((v >> 24) & 0xFF));
return crc;
}
HRESULT CInArchive::Open2(IInStream *stream, const UInt64 *searchHeaderSizeLimit)
{
m_CryptoMode = false;
RINOK(stream->Seek(0, STREAM_SEEK_SET, &m_StreamStartPosition));
m_Position = m_StreamStartPosition;
RINOK(FindAndReadMarker(stream, searchHeaderSizeLimit));
Byte buf[NHeader::NArchive::kArchiveHeaderSize];
UInt32 processedSize;
ReadBytes(buf, sizeof(buf), &processedSize);
if (processedSize != sizeof(buf))
return S_FALSE;
m_CurData = buf;
m_CurPos = 0;
m_PosLimit = sizeof(buf);
m_ArchiveHeader.CRC = ReadUInt16();
m_ArchiveHeader.Type = ReadByte();
m_ArchiveHeader.Flags = ReadUInt16();
m_ArchiveHeader.Size = ReadUInt16();
m_ArchiveHeader.Reserved1 = ReadUInt16();
m_ArchiveHeader.Reserved2 = ReadUInt32();
m_ArchiveHeader.EncryptVersion = 0;
UInt32 crc = CRC_INIT_VAL;
crc = CRC_UPDATE_BYTE(crc, m_ArchiveHeader.Type);
crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Flags);
crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Size);
crc = CrcUpdateUInt16(crc, m_ArchiveHeader.Reserved1);
crc = CrcUpdateUInt32(crc, m_ArchiveHeader.Reserved2);
if (m_ArchiveHeader.IsThereEncryptVer() && m_ArchiveHeader.Size > NHeader::NArchive::kArchiveHeaderSize)
{
ReadBytes(&m_ArchiveHeader.EncryptVersion, 1, &processedSize);
if (processedSize != 1)
return S_FALSE;
crc = CRC_UPDATE_BYTE(crc, m_ArchiveHeader.EncryptVersion);
}
if(m_ArchiveHeader.CRC != (CRC_GET_DIGEST(crc) & 0xFFFF))
ThrowExceptionWithCode(CInArchiveException::kArchiveHeaderCRCError);
if (m_ArchiveHeader.Type != NHeader::NBlockType::kArchiveHeader)
return S_FALSE;
m_ArchiveCommentPosition = m_Position;
m_SeekOnArchiveComment = true;
return S_OK;
}
void CInArchive::SkipArchiveComment()
{
if (!m_SeekOnArchiveComment)
return;
AddToSeekValue(m_ArchiveHeader.Size - m_ArchiveHeader.GetBaseSize());
m_SeekOnArchiveComment = false;
}
void CInArchive::GetArchiveInfo(CInArchiveInfo &archiveInfo) const
{
archiveInfo.StartPosition = m_ArchiveStartPosition;
archiveInfo.Flags = m_ArchiveHeader.Flags;
archiveInfo.CommentPosition = m_ArchiveCommentPosition;
archiveInfo.CommentSize = (UInt16)(m_ArchiveHeader.Size - NHeader::NArchive::kArchiveHeaderSize);
}
static void DecodeUnicodeFileName(const char *name, const Byte *encName,
int encSize, wchar_t *unicodeName, int maxDecSize)
{
int encPos = 0;
int decPos = 0;
int flagBits = 0;
Byte flags = 0;
Byte highByte = encName[encPos++];
while (encPos < encSize && decPos < maxDecSize)
{
if (flagBits == 0)
{
flags = encName[encPos++];
flagBits = 8;
}
switch(flags >> 6)
{
case 0:
unicodeName[decPos++] = encName[encPos++];
break;
case 1:
unicodeName[decPos++] = (wchar_t)(encName[encPos++] + (highByte << 8));
break;
case 2:
unicodeName[decPos++] = (wchar_t)(encName[encPos] + (encName[encPos + 1] << 8));
encPos += 2;
break;
case 3:
{
int length = encName[encPos++];
if (length & 0x80)
{
Byte correction = encName[encPos++];
for (length = (length & 0x7f) + 2;
length > 0 && decPos < maxDecSize; length--, decPos++)
unicodeName[decPos] = (wchar_t)(((name[decPos] + correction) & 0xff) + (highByte << 8));
}
else
for (length += 2; length > 0 && decPos < maxDecSize; length--, decPos++)
unicodeName[decPos] = name[decPos];
}
break;
}
flags <<= 2;
flagBits -= 2;
}
unicodeName[decPos < maxDecSize ? decPos : maxDecSize - 1] = 0;
}
void CInArchive::ReadName(CItemEx &item, int nameSize)
{
item.UnicodeName.Empty();
if (nameSize > 0)
{
m_NameBuffer.EnsureCapacity(nameSize + 1);
char *buffer = (char *)m_NameBuffer;
for (int i = 0; i < nameSize; i++)
buffer[i] = ReadByte();
int mainLen;
for (mainLen = 0; mainLen < nameSize; mainLen++)
if (buffer[mainLen] == '\0')
break;
buffer[mainLen] = '\0';
item.Name = buffer;
if(item.HasUnicodeName())
{
if(mainLen < nameSize)
{
int unicodeNameSizeMax = MyMin(nameSize, (0x400));
_unicodeNameBuffer.EnsureCapacity(unicodeNameSizeMax + 1);
DecodeUnicodeFileName(buffer, (const Byte *)buffer + mainLen + 1,
nameSize - (mainLen + 1), _unicodeNameBuffer, unicodeNameSizeMax);
item.UnicodeName = _unicodeNameBuffer;
}
else if (!ConvertUTF8ToUnicode(item.Name, item.UnicodeName))
item.UnicodeName.Empty();
}
}
else
item.Name.Empty();
}
Byte CInArchive::ReadByte()
{
if (m_CurPos >= m_PosLimit)
throw CInArchiveException(CInArchiveException::kIncorrectArchive);
return m_CurData[m_CurPos++];
}
UInt16 CInArchive::ReadUInt16()
{
UInt16 value = 0;
for (int i = 0; i < 2; i++)
{
Byte b = ReadByte();
value |= (UInt16(b) << (8 * i));
}
return value;
}
UInt32 CInArchive::ReadUInt32()
{
UInt32 value = 0;
for (int i = 0; i < 4; i++)
{
Byte b = ReadByte();
value |= (UInt32(b) << (8 * i));
}
return value;
}
void CInArchive::ReadTime(Byte mask, CRarTime &rarTime)
{
rarTime.LowSecond = (Byte)(((mask & 4) != 0) ? 1 : 0);
int numDigits = (mask & 3);
rarTime.SubTime[0] = rarTime.SubTime[1] = rarTime.SubTime[2] = 0;
for (int i = 0; i < numDigits; i++)
rarTime.SubTime[3 - numDigits + i] = ReadByte();
}
void CInArchive::ReadHeaderReal(CItemEx &item)
{
item.Flags = m_BlockHeader.Flags;
item.PackSize = ReadUInt32();
item.Size = ReadUInt32();
item.HostOS = ReadByte();
item.FileCRC = ReadUInt32();
item.MTime.DosTime = ReadUInt32();
item.UnPackVersion = ReadByte();
item.Method = ReadByte();
int nameSize = ReadUInt16();
item.Attrib = ReadUInt32();
item.MTime.LowSecond = 0;
item.MTime.SubTime[0] =
item.MTime.SubTime[1] =
item.MTime.SubTime[2] = 0;
if((item.Flags & NHeader::NFile::kSize64Bits) != 0)
{
item.PackSize |= ((UInt64)ReadUInt32() << 32);
item.Size |= ((UInt64)ReadUInt32() << 32);
}
ReadName(item, nameSize);
if (item.HasSalt())
for (int i = 0; i < sizeof(item.Salt); i++)
item.Salt[i] = ReadByte();
// some rar archives have HasExtTime flag without field.
if (m_CurPos < m_PosLimit && item.HasExtTime())
{
Byte accessMask = (Byte)(ReadByte() >> 4);
Byte b = ReadByte();
Byte modifMask = (Byte)(b >> 4);
Byte createMask = (Byte)(b & 0xF);
if ((modifMask & 8) != 0)
ReadTime(modifMask, item.MTime);
item.CTimeDefined = ((createMask & 8) != 0);
if (item.CTimeDefined)
{
item.CTime.DosTime = ReadUInt32();
ReadTime(createMask, item.CTime);
}
item.ATimeDefined = ((accessMask & 8) != 0);
if (item.ATimeDefined)
{
item.ATime.DosTime = ReadUInt32();
ReadTime(accessMask, item.ATime);
}
}
UInt16 fileHeaderWithNameSize = (UInt16)m_CurPos;
item.Position = m_Position;
item.MainPartSize = fileHeaderWithNameSize;
item.CommentSize = (UInt16)(m_BlockHeader.HeadSize - fileHeaderWithNameSize);
if (m_CryptoMode)
item.AlignSize = (UInt16)((16 - ((m_BlockHeader.HeadSize) & 0xF)) & 0xF);
else
item.AlignSize = 0;
AddToSeekValue(m_BlockHeader.HeadSize);
}
void CInArchive::AddToSeekValue(UInt64 addValue)
{
m_Position += addValue;
}
HRESULT CInArchive::GetNextItem(CItemEx &item, ICryptoGetTextPassword *getTextPassword, bool &decryptionError)
{
decryptionError = false;
if (m_SeekOnArchiveComment)
SkipArchiveComment();
for (;;)
{
if(!SeekInArchive(m_Position))
return S_FALSE;
if (!m_CryptoMode && (m_ArchiveHeader.Flags &
NHeader::NArchive::kBlockHeadersAreEncrypted) != 0)
{
m_CryptoMode = false;
if (getTextPassword == 0)
return S_FALSE;
if(!SeekInArchive(m_Position))
return S_FALSE;
if (!m_RarAES)
{
m_RarAESSpec = new NCrypto::NRar29::CDecoder;
m_RarAES = m_RarAESSpec;
}
m_RarAESSpec->SetRar350Mode(m_ArchiveHeader.IsEncryptOld());
// Salt
const UInt32 kSaltSize = 8;
Byte salt[kSaltSize];
if(!ReadBytesAndTestSize(salt, kSaltSize))
return S_FALSE;
m_Position += kSaltSize;
RINOK(m_RarAESSpec->SetDecoderProperties2(salt, kSaltSize))
// Password
<PASSWORD>STR password;
RINOK(getTextPassword->CryptoGetTextPassword(&password))
UString unicodePassword(<PASSWORD>);
CByteBuffer buffer;
const UInt32 sizeInBytes = unicodePassword.Length() * 2;
buffer.SetCapacity(sizeInBytes);
for (int i = 0; i < unicodePassword.Length(); i++)
{
wchar_t c = unicodePassword[i];
((Byte *)buffer)[i * 2] = (Byte)c;
((Byte *)buffer)[i * 2 + 1] = (Byte)(c >> 8);
}
RINOK(m_RarAESSpec->CryptoSetPassword((const Byte *)buffer, sizeInBytes));
const UInt32 kDecryptedBufferSize = (1 << 12);
if (m_DecryptedData.GetCapacity() == 0)
{
const UInt32 kAlign = 16;
m_DecryptedData.SetCapacity(kDecryptedBufferSize + kAlign);
m_DecryptedDataAligned = (Byte *)((ptrdiff_t)((Byte *)m_DecryptedData + kAlign - 1) & ~(ptrdiff_t)(kAlign - 1));
}
RINOK(m_RarAES->Init());
size_t decryptedDataSizeT = kDecryptedBufferSize;
RINOK(ReadStream(m_Stream, m_DecryptedDataAligned, &decryptedDataSizeT));
m_DecryptedDataSize = (UInt32)decryptedDataSizeT;
m_DecryptedDataSize = m_RarAES->Filter(m_DecryptedDataAligned, m_DecryptedDataSize);
m_CryptoMode = true;
m_CryptoPos = 0;
}
m_FileHeaderData.EnsureCapacity(7);
if(!ReadBytesAndTestSize((Byte *)m_FileHeaderData, 7))
return S_FALSE;
m_CurData = (Byte *)m_FileHeaderData;
m_CurPos = 0;
m_PosLimit = 7;
m_BlockHeader.CRC = ReadUInt16();
m_BlockHeader.Type = ReadByte();
m_BlockHeader.Flags = ReadUInt16();
m_BlockHeader.HeadSize = ReadUInt16();
if (m_BlockHeader.HeadSize < 7)
ThrowExceptionWithCode(CInArchiveException::kIncorrectArchive);
if (m_BlockHeader.Type == NHeader::NBlockType::kEndOfArchive)
return S_FALSE;
if (m_BlockHeader.Type == NHeader::NBlockType::kFileHeader)
{
m_FileHeaderData.EnsureCapacity(m_BlockHeader.HeadSize);
m_CurData = (Byte *)m_FileHeaderData;
m_PosLimit = m_BlockHeader.HeadSize;
ReadBytesAndTestResult(m_CurData + m_CurPos, m_BlockHeader.HeadSize - 7);
ReadHeaderReal(item);
if ((CrcCalc(m_CurData + 2,
m_BlockHeader.HeadSize - item.CommentSize - 2) & 0xFFFF) != m_BlockHeader.CRC)
ThrowExceptionWithCode(CInArchiveException::kFileHeaderCRCError);
FinishCryptoBlock();
m_CryptoMode = false;
SeekInArchive(m_Position); // Move Position to compressed Data;
AddToSeekValue(item.PackSize); // m_Position points to next header;
return S_OK;
}
if (m_CryptoMode && m_BlockHeader.HeadSize > (1 << 10))
{
decryptionError = true;
return S_FALSE;
}
if ((m_BlockHeader.Flags & NHeader::NBlock::kLongBlock) != 0)
{
m_FileHeaderData.EnsureCapacity(7 + 4);
m_CurData = (Byte *)m_FileHeaderData;
ReadBytesAndTestResult(m_CurData + m_CurPos, 4); // test it
m_PosLimit = 7 + 4;
UInt32 dataSize = ReadUInt32();
AddToSeekValue(dataSize);
if (m_CryptoMode && dataSize > (1 << 27))
{
decryptionError = true;
return S_FALSE;
}
m_CryptoPos = m_BlockHeader.HeadSize;
}
else
m_CryptoPos = 0;
AddToSeekValue(m_BlockHeader.HeadSize);
FinishCryptoBlock();
m_CryptoMode = false;
}
}
bool CInArchive::SeekInArchive(UInt64 position)
{
UInt64 newPosition;
m_Stream->Seek(position, STREAM_SEEK_SET, &newPosition);
return newPosition == position;
}
ISequentialInStream* CInArchive::CreateLimitedStream(UInt64 position, UInt64 size)
{
CLimitedSequentialInStream *streamSpec = new CLimitedSequentialInStream;
CMyComPtr<ISequentialInStream> inStream(streamSpec);
SeekInArchive(position);
streamSpec->SetStream(m_Stream);
streamSpec->Init(size);
return inStream.Detach();
}
}}
<file_sep>/FBReaderJ/jni/Android.mk
LOCAL_PATH := $(call my-dir)
#############################################
# 调试信息: TRUE=打印日志
DEBUG := true
LDDEBUG :=
DEBUG_FLAG :=
$(info ============================================)
DMODE := $(shell echo $(DEBUG) | tr a-z A-Z)
ifeq ($(DMODE),TRUE)
$(eval LDDEBUG := -llog)
$(eval DEBUG_FLAG := -DDEBUG_LOG)
$(info LOG_MODE = debug)
else
$(info LOG_MODE = release)
endif
$(info ============================================)
COMMON_CFLAGS := -fsigned-char $(DEBUG_FLAG)
#############################################
#
include $(CLEAR_VARS)
LOCAL_MODULE := DeflatingDecompressor
LOCAL_SRC_FILES := DeflatingDecompressor/DeflatingDecompressor.cpp
LOCAL_LDLIBS := -lz
LOCAL_CFLAGS += $(COMMON_CFLAGS)
LOCAL_LDLIBS += $(LDDEBUG)
include $(BUILD_SHARED_LIBRARY)
#############################################
#
include $(CLEAR_VARS)
LOCAL_MODULE := LineBreak
LOCAL_SRC_FILES := LineBreak/LineBreaker.cpp LineBreak/liblinebreak-2.0/linebreak.c LineBreak/liblinebreak-2.0/linebreakdata.c LineBreak/liblinebreak-2.0/linebreakdef.c
LOCAL_CFLAGS += $(COMMON_CFLAGS)
LOCAL_LDLIBS += $(LDDEBUG)
include $(BUILD_SHARED_LIBRARY)
#############################################
#
include $(CLEAR_VARS)
LOCAL_MODULE := TxtParser
LOCAL_SRC_FILES := TxtParser/TxtParser.cpp
LOCAL_CFLAGS += $(COMMON_CFLAGS)
LOCAL_LDLIBS += $(LDDEBUG)
include $(BUILD_SHARED_LIBRARY)
<file_sep>/FingerSuite/Common/fngrscrl.h
#ifndef __FNGRSCRL_H__
#define __FNGRSCRL_H__
#pragma once
#ifndef __cplusplus
#error ATL requires C++ compilation (use a .cpp suffix)
#endif
#ifndef __ATLAPP_H__
#error fngrscrl.h requires atlapp.h to be included first
#endif
#ifndef __ATLWIN_H__
#error fngrscrl.h requires atlwin.h to be included first
#endif
#ifndef __FNGRBUFDC_H__
#error fngrscrl.h requires fngrbufdc.h to be included first
#endif
#define IDT_TIMER_ANIMATION 10001
#define TMR_INTERVAL 10
#define IDT_TIMER_AUTOSCROLL 10002
#define TMR_INTERVAL 10
#define UM_SCRL_NOTIFY WM_USER + 100001
///////////////////////////////////////////////////////////////////////////////
// Classes in this file:
//
// CFingerScrollImpl<T>
template <class T, bool t_bBuffered = false, bool t_bNotifyParentWnd = false>
class CFingerScrollImpl
{
public:
CFingerScrollImpl()
{
Reset();
}
~CFingerScrollImpl()
{
T* pT = static_cast<T*>(this);
if (::IsWindow(pT->m_hWnd))
pT->KillTimer(IDT_TIMER_ANIMATION);
}
// Overrideables
void DoPaint(CDCHandle /*dc*/)
{
// must be implemented in a derived class
ATLASSERT(FALSE);
}
void DoScroll(int /*yOffset*/)
{
// can be override
}
void ScrollTo(int offset)
{
m_offsetScrollTo = offset;
if (m_offsetScrollTo < 0)
m_offsetScrollTo = 0;
if (m_offsetScrollTo > m_scrollableAreaHeight)
m_offsetScrollTo = m_scrollableAreaHeight;
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
//m_velocity = 1;
pT->SetTimer(IDT_TIMER_AUTOSCROLL, TMR_INTERVAL);
}
void SetFingerScrollRegion(int scrollableAreaHeight, int clientAreaHeight)
{
Reset();
m_scrollableAreaHeight = max(scrollableAreaHeight - clientAreaHeight, 0);
m_clientAreaHeight = clientAreaHeight;
}
int GetScrollableAreaHeight()
{
return m_scrollableAreaHeight;
}
void SetMaxVelocity(int value)
{
m_maxVelocity = value;
}
int GetOffset()
{
return m_offset;
}
void SetThreshold(int value)
{
m_threshold = value;
}
int GetThreshold()
{
return m_threshold;
}
BOOL IsScrolling()
{
return ((m_velocity > 0) || m_bMouseIsDown);
}
BEGIN_MSG_MAP(CFingerScrollImpl)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnLButtonDown)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnMouseMove)
MESSAGE_HANDLER(WM_LBUTTONUP, OnLButtonUp)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_PAINT, OnPaint)
MESSAGE_HANDLER(WM_CAPTURECHANGED, OnCaptureChanged)
END_MSG_MAP()
LRESULT OnLButtonDown(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
m_bMouseIsDown = TRUE;
m_tMouseDown = ::GetTickCount();
pT->KillTimer(IDT_TIMER_ANIMATION);
pT->KillTimer(IDT_TIMER_AUTOSCROLL);
m_mouseDown.x = LOWORD(lParam);
m_mouseDown.y = HIWORD(lParam);
m_mousePrev = m_mouseDown;
return 0;
}
LRESULT OnMouseMove(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
int distanceY = m_mousePrev.y - HIWORD(lParam);
if (abs(distanceY) > m_threshold)
{
ModifyOffset(distanceY, FALSE);
ClipScrollPosition();
m_mousePrev.x = LOWORD(lParam);
m_mousePrev.y = HIWORD(lParam);
UpdateLayout();
}
return 0;
}
LRESULT OnLButtonUp(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
int y = HIWORD(lParam);
// Did the click end on the same item it started on?
BOOL sameY = (y == m_mouseDown.y);
if (!(sameY) && (::GetTickCount() - m_tMouseDown < 500) )
{
m_velocity = m_mouseDown.y - y;
pT->SetTimer(IDT_TIMER_ANIMATION, TMR_INTERVAL);
}
m_mouseDown.y = -1;
m_bMouseIsDown = FALSE;
UpdateLayout();
return 0;
}
LRESULT OnTimer(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
if (wParam == IDT_TIMER_ANIMATION)
{
if (m_velocity == 0)
{
pT->KillTimer(IDT_TIMER_ANIMATION);
}
if (!m_bMouseIsDown && (m_velocity != 0))
{
m_velocity = min(m_velocity, m_maxVelocity);
m_velocity = max(m_velocity, -m_maxVelocity);
ModifyOffset(m_velocity, FALSE);
ClipScrollPosition();
// Slow down
if (((++m_timerCount) % 10) == 0)
{
if (m_velocity < 0)
{
//m_velocity ++;
m_velocity = m_velocity / 2;
}
else if (m_velocity > 0)
{
//m_velocity --;
m_velocity = m_velocity / 2;
}
}
UpdateLayout();
}
//wprintf(L"m_velocity = %d\n", m_velocity);
}
if (wParam == IDT_TIMER_AUTOSCROLL)
{
int velocity = m_offsetScrollTo - m_offset;
velocity = min(velocity, m_maxVelocity);
velocity = max(velocity, -m_maxVelocity);
ModifyOffset(velocity, FALSE);
if (m_offset < 0)
{
velocity = 0;
ModifyOffset(0, TRUE);
}
else if (m_offset > m_scrollableAreaHeight)
{
velocity = 0;
ModifyOffset(m_scrollableAreaHeight, TRUE);
}
if (velocity != 0)
UpdateLayout();
else
pT->KillTimer(IDT_TIMER_AUTOSCROLL);
}
return 0;
}
LRESULT OnPaint(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
if(wParam != NULL)
{
CDCHandle dc = (HDC)wParam;
POINT ptViewportOrg = { 0, 0 };
dc.SetViewportOrg(0, -m_offset, &ptViewportOrg);
pT->DoPaint(dc);
dc.SetViewportOrg(ptViewportOrg);
}
else
{
if (t_bBuffered)
{
CBufferedPaintDC dc(pT->m_hWnd, -m_offset);
dc.SetViewportOrg(0, -m_offset);
pT->DoPaint(dc.m_hDC);
}
else
{
CPaintDC dc(pT->m_hWnd);
dc.SetViewportOrg(0, -m_offset);
pT->DoPaint(dc.m_hDC);
}
}
return 0;
}
LRESULT OnCaptureChanged(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
{
m_bMouseIsDown = FALSE;
return 0;
}
private:
void Reset()
{
//m_maxVelocity = 15;
m_velocity = 0;
ModifyOffset(0, TRUE);
m_timerCount = 0;
m_mouseDown.x = -1; m_mouseDown.y = -1;
m_mousePrev.x = -1; m_mousePrev.y = -1;
m_t1 = ::GetTickCount();
//m_bMiddlePosNotified = FALSE;
}
/*
void ClipVelocity()
{
m_velocity = min(m_velocity, m_maxVelocity);
m_velocity = max(m_velocity, -m_maxVelocity);
}
*/
void ClipScrollPosition()
{
if (m_offset < 0)
{
ModifyOffset(0, TRUE);
m_velocity = 0;
}
else if (m_offset > m_scrollableAreaHeight)
{
ModifyOffset(m_scrollableAreaHeight, TRUE);
m_velocity = 0;
}
}
void UpdateLayout()
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
pT->InvalidateRect(NULL, TRUE);
DWORD t2 = ::GetTickCount();
if (t2 - m_t1 > 50) // ms elapsed
{
m_t1 = ::GetTickCount();
pT->UpdateWindow();
}
}
void ModifyOffset(int value, BOOL bAbsolute)
{
T* pT = static_cast<T*>(this);
if (bAbsolute)
m_offset = value;
else
{
m_offset += value;
//pT->DoScroll(value); TODO
}
if ((t_bNotifyParentWnd) && (::IsWindow(pT->m_hWnd)))
::SendMessage(pT->GetParent(), UM_SCRL_NOTIFY, (WPARAM)m_offset, 0);
}
protected:
// nuovi
POINT m_mouseDown;
POINT m_mousePrev;
int m_scrollableAreaHeight;
int m_clientAreaHeight;
BOOL m_bMouseIsDown;
//BOOL m_bMiddlePosNotified;
int m_maxVelocity;
int m_velocity;
int m_offset;
int m_timerCount;
DWORD m_t1;
int m_offsetScrollTo;
DWORD m_tMouseDown;
int m_threshold;
//HWND m_hWndNotify;
};
/*
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
template <class T>
class CFingerScrollItemImpl
{
public:
CFingerScrollItemImpl()
{
m_top = 0;
}
~CFingerScrollItemImpl() {}
BEGIN_MSG_MAP(CFingerScrollItemImpl)
MESSAGE_HANDLER(WM_WINDOWPOSCHANGED, OnWindowPosChanged)
MESSAGE_HANDLER(WM_LBUTTONDOWN, OnForwardMessage)
MESSAGE_HANDLER(WM_MOUSEMOVE, OnForwardMessage)
MESSAGE_HANDLER(WM_LBUTTONUP, OnForwardMessage)
END_MSG_MAP()
LRESULT OnWindowPosChanged(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
LPWINDOWPOS lpwp = (LPWINDOWPOS) lParam;
m_top = lpwp->y;
return 0;
}
LRESULT OnForwardMessage(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
T* pT = static_cast<T*>(this);
ATLASSERT(::IsWindow(pT->m_hWnd));
int y = m_top + HIWORD(lParam);
pT->GetParent().SendMessage(uMsg, wParam, (LPARAM)MAKELONG(0, y)); // no matter on x position
return 0;
}
protected:
int m_top;
};
*/
#endif // __FNGRSCRL_H__ | ea613c6a4d531be9b5d41ced98df1a91320c59cc | [
"Makefile",
"INI",
"Java",
"C",
"C++"
] | 136 | C++ | f059074251/interested | b5a26ad732f8ffdca64cbbadf9625dd35c9cdcb2 | 939f938109853da83741ee03aca161bfa9ce0976 | |
refs/heads/master | <file_sep>import os
import docker
from docker.errors import BuildError
from patchworkdocker.errors import PatchworkDockerError
class DockerBuildError(PatchworkDockerError):
"""
Docker build error.
"""
def build_docker_image(image_name: str, context: str, dockerfile: str):
"""
Builds a Docker image with the given tag from the given Dockerfile in the given context.
:param image_name: image tag (can optionally include a version tag)
:param context: context to build the image in (absolute file path)
:param dockerfile: Dockerfile to build the image from (absolute file path)
:raises BuildFailedError: raised if an error occurs during the build
"""
if not os.path.isabs(context):
raise ValueError(f"Context location must be absolute: {context}")
if not os.path.isabs(dockerfile):
raise ValueError(f"Dockerfile location must be absolute: {dockerfile}")
client = docker.from_env()
try:
client.images.build(path=context, dockerfile=dockerfile, tag=image_name)
except BuildError as e:
raise DockerBuildError(f"Error building image: {image_name}") from e
<file_sep>ARG baseImage=python:3.8
FROM ${baseImage}
ENV INSTALL_DIRECTORY=/usr/local/src/patchwork-docker
ENV PYTHONPATH=${INSTALL_DIRECTORY}
COPY requirements.txt /tmp/requirements.txt
RUN pip install -r /tmp/requirements.txt
COPY . "${INSTALL_DIRECTORY}"
# TODO: Install into CLI
ENTRYPOINT ["python", "/usr/local/src/patchwork-docker/patchworkdocker/cli.py"]
CMD ["--help"]
<file_sep>#!/usr/bin/env bash
set -eu -o pipefail
shopt -s expand_aliases
WORKDIR="/root"
BASE_IMAGE="${BASE_IMAGE:-python:3.7}"
DOCKER_VERSION="${DOCKER_VERSION:-18.06.1-ce}"
userArguments="$@"
# Not assuming jq is installed on the machine
alias djq="docker run --rm -i endeveit/docker-jq jq"
# Bash implementation of `readlink` (which is not on OSX)
function readlinkx {
echo "$(cd "$(dirname "$1")"; pwd)/$(basename "$1")"
}
# Creates mount Docker CLI setting for the given location
function createMountSetting {
location="$1"
if [[ "${location}" != /* ]]; then
mountLocation="${WORKDIR}/$(echo "${location}" | sed -e 's/^[\.\/]*//g')"
else
mountLocation="${location}"
fi
echo "-v $(readlinkx ${location}):${mountLocation}"
}
>&2 echo "Building Docker image for patchworkdocker (BASE_IMAGE=${BASE_IMAGE}; DOCKER_VERSION=${DOCKER_VERSION})"
docker build -t patchworkdocker \
--build-arg baseImage="${BASE_IMAGE}" --build-arg "dockerVersion=${DOCKER_VERSION}" . > /dev/null
>&2 echo "Determining configuration"
configuration=$(docker run --rm -i patchworkdocker --dry-run ${userArguments})
if [[ ! "${configuration}" =~ ^{.* ]]; then
# Dry run not written JSON (probably written help)
>&2 echo "${configuration}"
exit 0
fi
>&2 echo "Configuration: ${configuration}"
>&2 echo "Preparing inputs"
inputLocations="$(echo ${configuration} | djq -r '[.additional_files, .patches | keys] | flatten | .[]')"
echo "${inputLocations}" | while read location; do
if [[ ! -e "${location}" ]]; then
>&2 echo "Input location does not exist: ${location}"
exit 1
fi
done
>&2 echo "Inputs: $(echo ${inputLocations} | sed 's/\n/ /g')"
>&2 echo "Preparing outputs"
buildLocation=$(echo "${configuration}" | djq -r '.build_location')
if [[ "${buildLocation}" == "null" ]]; then
buildLocation=$(mktemp -d /tmp/patchworkdocker.XXXXXX)
trap "rm -rf ${buildLocation}" EXIT
userArguments="${userArguments} --build-location ${buildLocation}"
fi
outputLocations="${buildLocation}"
>&2 echo "Outputs: $(echo ${outputLocations} | sed 's/\n/ /g')"
>&2 echo "Running patchworkdocker..."
docker run --rm -i -v /var/run/docker.sock:/var/run/docker.sock:ro \
$(echo "${outputLocations}" | while read location; do echo "$(createMountSetting ${location}) "; done) \
$(echo "${inputLocations}" | while read location; do echo "$(createMountSetting ${location}):ro "; done) \
patchworkdocker ${userArguments}
<file_sep>from setuptools import setup, find_packages
from patchworkdocker.meta import VERSION, DESCRIPTION, PACKAGE_NAME, EXECUTABLE_NAME
setup(
name=PACKAGE_NAME,
version=VERSION,
author="<NAME>",
author_email="<EMAIL>",
packages=find_packages(exclude=["tests"]),
install_requires=open("requirements.txt", "r").readlines(),
url="https://github.com/colin-nolan/patchwork-docker",
license="MIT",
description=DESCRIPTION,
long_description=open("README.md", "r").read(),
long_description_content_type="text/markdown",
entry_points={
"console_scripts": [
f"{EXECUTABLE_NAME}={PACKAGE_NAME}.cli:entrypoint"
]
},
zip_safe=True
)
<file_sep>../../subrepos/colin-nolan/key_value_string_parser.py/key_value_string_parser.py<file_sep>import os
import shutil
from typing import Dict, Optional
from frozendict import frozendict
from logzero import logger
from patchworkdocker.docker_images import build_docker_image
from patchworkdocker.importers import ImporterFactory
from patchworkdocker.modifiers import copy_file, apply_patch, change_base_image
_importer_factory = ImporterFactory()
class PatchworkDocker:
"""
Builds patchwork Docker images.
"""
@property
def dockerfile_location(self) -> str:
return self._dockerfile_location
@dockerfile_location.setter
def dockerfile_location(self, location: str):
if os.path.isabs(location):
raise ValueError(f"Dockerfile location must be relative to the context root: {location}")
self._dockerfile_location = location
def __init__(self, import_repository_from: str, *, additional_files: Dict[str, Optional[str]]=(),
patches: Dict[str, str]=frozendict(), dockerfile_location: str="Dockerfile", base_image: str=None):
"""
Constructor.
:param import_repository_from: where to import the starting materials for the image from
:param additional_files: files to add to the build context, where the key is the location on the host and the
value (if given) is the relative location in the build context (added in the order given, overwrites possible)
:param patches: patches to apply to files in the build context, where the key is the location of the patch file
and the value is the location of the file to apply it to, relative to the build context root (applied in the
order given)
:param dockerfile_location: location of the Dockerfile to build, relative to the root of the repository
:param base_image: Docker base image to change to
"""
self._dockerfile_location = None
self.import_repository_from = import_repository_from
self.additional_files = additional_files
self.patches = patches
self.dockerfile_location = dockerfile_location
self.base_image = base_image
def build(self, image_name: str, build_directory: str=None):
"""
Builds the patchworked Docker image.
:param image_name: image tag (can optionally include a version tag)
:param build_directory: directory to build in
"""
repository_location = self.prepare(build_directory)
dockerfile_location = os.path.join(repository_location, self.dockerfile_location)
try:
build_docker_image(image_name, repository_location, dockerfile_location)
finally:
if build_directory is None:
logger.info(f"Removing temp build directory: {repository_location}")
shutil.rmtree(repository_location)
else:
logger.info(f"Not removing build directory as directory was given by the user: {repository_location}")
def prepare(self, build_directory: str=None) -> str:
"""
Prepare a directory with the patched build materials.
:param build_directory: the directory to load the patched build context in
:return: the location of the build directory
"""
if build_directory is not None:
build_directory = os.path.abspath(build_directory)
if len(os.listdir(path=build_directory)) > 0:
raise ValueError(f"Build directory {build_directory} is not empty")
repository_location = _importer_factory.create(self.import_repository_from).load(
self.import_repository_from, build_directory)
logger.info(f"Imported repository at {self.import_repository_from} to {repository_location}")
for src, dest in self.additional_files.items():
src = os.path.abspath(src)
if dest is None:
dest = os.path.basename(src)
if os.path.isabs(dest):
raise ValueError(f"Destination must be relative to the root of the context: {dest}")
dest = os.path.join(repository_location, dest)
os.path.exists(src), os.path.exists(dest)
logger.info(f"{'Overwriting' if os.path.exists(dest) else 'Creating'} {dest} with {src}")
copy_file(src, dest)
for src, dest in self.patches.items():
src = os.path.abspath(src)
dest = os.path.join(repository_location, dest)
os.path.exists(src), os.path.exists(dest)
logger.info(f"Patching {dest} with {src}")
apply_patch(src, dest)
if self.base_image is not None:
logger.info(f"Setting base image to {self.base_image}")
dockerfile_location = os.path.join(repository_location, self.dockerfile_location)
change_base_image(dockerfile_location, self.base_image)
return repository_location
<file_sep>[](https://travis-ci.org/colin-nolan/patchwork-docker)
[](https://codecov.io/gh/colin-nolan/patchwork-docker)
# Patchwork Docker
## Purpose
Allows a Docker build to be easily changed, without having to clone and modify an existing build repository.
## Features
All with a single command, the tool can:
- Build images from a different base image.
- Add/override files in the build context.
- Apply patches to the Dockerfile or other files in the build context.
- Define a different Dockerfile.
## Use Cases
A few basic use cases (`./docker-run.sh` can be used instead of `patchworkdocker`):
- To change a base image from `debian:stretch` to `python:3.7-stretch` so as to get the latest version of Python in the
image with no hassle:
```bash
patchworkdocker build \
--base-image python:3.7-stretch \
example:1.0.0 https://github.com/example/docker-example.git
```
- Add an alternate Dockerfile to a pre-existing context:
```bash
patchworkdocker build \
--additional-file Dockerfile:Dockerfile.example \
--dockerfile Dockerfile.example \
https://github.com/example/docker-example.git example:1.0.0
```
- Change the URL of a piece of software that gets installed into a Docker image:
```bash
patchworkdocker build \
--dockerfile 3.7/stretch/Dockerfile \
--patch change-install-url.patch:Dockerfile \
https://github.com/docker-library/python.git example:1.0.0
```
Raspberry Pi users may find this tool particularly useful as, outside the official images, there is often need to
change image build in order to get them to work on the non-standard rpi architectures.
## Installation
Prerequisites
- Docker
- Python 3.7+ (optional, as can be run entirely from Docker if you don't have Python 3.7)
The tool can be installed directly from GitHub:
```bash
pip install git+https://github.com/colin-nolan/patchwork-docker@master#egg=patchworkdocker
```
## Usage
Up-to-date usage information can be seen with:
```bash
patchworkdocker --help
patchworkdocker build --help
```
## Legal
This work is in no way related to the company that I work for.
<file_sep>import os
import shutil
import unittest
from pathlib import Path
from patchworkdocker.modifiers import copy_file, apply_patch
from patchworkdocker.tests._common import TestWithTempFiles
_RESOURCES_LOCATION = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
_EXAMPLE_FILE_NAME = "test-file"
_EXAMPLE_FILE_NAME_2 = "test-file-2"
class TestCopyFile(TestWithTempFiles):
"""
Tests for `copy_file`.
"""
def setUp(self):
super().setUp()
self.src_directory = self.temp_manager.create_temp_directory()
self.dest_directory = self.temp_manager.create_temp_directory()
def test_empty_src_to_empty_dest(self):
copy_file(self.src_directory, self.dest_directory)
self.assertEquals(0, len(os.listdir(self.dest_directory)))
def test_src_to_empty_dest(self):
Path(os.path.join(self.src_directory, _EXAMPLE_FILE_NAME)).touch()
copy_file(self.src_directory, self.dest_directory)
self.assertTrue(os.path.exists(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME)))
self.assertEquals(1, len(os.listdir(self.dest_directory)))
def test_src_to_dest(self):
Path(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME_2)).touch()
Path(os.path.join(self.src_directory, _EXAMPLE_FILE_NAME)).touch()
copy_file(self.src_directory, self.dest_directory)
self.assertTrue(os.path.exists(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME)))
self.assertEquals(2, len(os.listdir(self.dest_directory)))
def test_src_to_dest_with_directory_merge(self):
Path(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME_2)).touch()
Path(os.path.join(self.src_directory, _EXAMPLE_FILE_NAME)).touch()
copy_file(self.src_directory, self.dest_directory)
self.assertTrue(os.path.exists(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME)))
self.assertEquals(2, len(os.listdir(self.dest_directory)))
def test_src_file_to_empty_dest(self):
file_location = os.path.join(self.src_directory, _EXAMPLE_FILE_NAME)
Path(file_location).touch()
copy_file(file_location, self.dest_directory)
self.assertTrue(os.path.exists(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME)))
self.assertEquals(1, len(os.listdir(self.dest_directory)))
def test_src_file_to_dest_with_overwrite(self):
file_location = os.path.join(self.src_directory, _EXAMPLE_FILE_NAME)
print("1", file=open(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME), "w"), end="")
print("1", file=open(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME_2), "w"), end="")
print("2", file=open(file_location, "w"), end="")
copy_file(file_location, self.dest_directory)
self.assertEquals("2", open(os.path.join(self.dest_directory, _EXAMPLE_FILE_NAME), "r").read())
self.assertEquals(2, len(os.listdir(self.dest_directory)))
class TestApplyPatch(TestWithTempFiles):
"""
Tests for `apply_patch`.
"""
_DOCKERFILE_NAME = "Dockerfile"
_EXAMPLE_DOCKERFILE_LOCATION = os.path.join(_RESOURCES_LOCATION, "patching", _DOCKERFILE_NAME)
def setUp(self):
super().setUp()
temp_directory = self.temp_manager.create_temp_directory()
self._dockerfile_location = os.path.join(temp_directory, TestApplyPatch._DOCKERFILE_NAME)
shutil.copyfile(TestApplyPatch._EXAMPLE_DOCKERFILE_LOCATION, self._dockerfile_location)
def test_change_from(self):
patched_content = self._apply(f"{_RESOURCES_LOCATION}/patching/from-change.patch")
self.assertTrue(patched_content.startswith("FROM arm32v7/ubuntu:16.04"))
def test_add_and_remove(self):
patched_content = self._apply(f"{_RESOURCES_LOCATION}/patching/add-and-remove.patch")
self.assertTrue("RUN /other.sh" in patched_content)
self.assertTrue("COPY . /data" not in patched_content)
def _apply(self, patch_location: str) -> str:
"""
Applies the given patch to the example Docker file.
:param patch_location: the location of the patch to apply
:return: the contents of the example Docker file after the patch has been applied
"""
apply_patch(patch_location, self._dockerfile_location)
with open(self._dockerfile_location, "r") as file:
return file.read()
if __name__ == "__main__":
unittest.main()
<file_sep>import os
from abc import ABCMeta, abstractmethod
from distutils import dir_util
from tempfile import mkdtemp
from urllib.parse import urldefrag, urlparse
from git import Repo
class Importer(metaclass=ABCMeta):
"""
Imports a Docker build directory.
"""
@abstractmethod
def _load(self, origin: str, load_directory: str) -> str:
"""
Loads the build directory from the given origin into the given directory.
:param origin: where to import materials from
:param load_directory: the directory in which imported materials should be saved
:return: directory containing the loaded content
"""
def load(self, origin: str, load_directory: str=None) -> str:
"""
Loads build directory from the given origin into a load directory, which can be specified or is a generated
temp directory if `None`.
The returned directory is not cleaned up automatically.
:param origin: where to import materials from
:param load_directory: the directory in which imported materials should be saved
:return: directory containing the loaded content
"""
if load_directory is None:
load_directory = mkdtemp()
return self._load(origin, load_directory)
class GitImporter(Importer):
"""
Imports content from a git repository.
For a specific commit, branch or tag, set the fragment, e.g. http://example.com/repo.git#branch_tag_or_commit.
"""
def _load(self, origin: str, load_directory: str) -> str:
origin, branch = urldefrag(origin)
repository = Repo.clone_from(url=origin, to_path=load_directory)
if branch != "":
if branch not in repository.heads:
branch_reference = None
for reference in repository.refs:
if reference.name == f"origin/{branch}":
branch_reference = reference
break
if branch_reference is not None:
commit = branch_reference.commit
else:
commit = repository.commit(branch)
repository.create_head(path=branch, commit=commit)
repository.heads[branch].checkout()
return load_directory
class FileSystemImporter(Importer):
"""
Imports content from the local file system.
"""
def _load(self, origin: str, load_directory: str) -> str:
dir_util.copy_tree(origin, load_directory)
return load_directory
class ImporterFactory:
"""
Importer factory, which can create the correct importer for an origin.
"""
def create(self, origin: str) -> Importer:
"""
Create an importer determined by analysis of the given origin.
:param origin: where to import materials from
:return: importer for the given origin
"""
if os.path.exists(origin):
return FileSystemImporter()
parsed_origin = urlparse(origin)
if parsed_origin.scheme == "git" or parsed_origin.path.endswith(".git"):
# XXX: it is possible that there's a Git repo at a location that does not have these attributes...
return GitImporter()
raise NotImplementedError(f"No importer implemented to work with: {origin}")
<file_sep>class PatchworkDockerError(Exception):
"""
Base error for all exceptions raised by this module.
"""
<file_sep># Copyright (c) 2018 Genome Research Limited
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import json
from argparse import Action
from json import JSONDecodeError
class KeyValueStringParserAction(Action):
"""
Parses input in the form `xxx:yyy` or a stringified JSON map as a key value pair.
Accepts multiple key-value pairs in stringified JSON map.
e.g.
```
parser.add_argument(f"-{MY_SHORT_PARAMETER}", f"--{MY_LONG_PARAMETER}", action=StringDictParseAction)
```
"""
def __call__(self, parser, namespace, values, option_string=None):
try:
value_as_json = json.loads(values)
if type(value_as_json) is not dict:
raise ValueError(f"Not an acceptable JSON value: {values}")
getattr(namespace, self.dest, {}).update(value_as_json)
except JSONDecodeError:
if ":" not in values:
raise ValueError(f"Unable to parse: {values}. Must be in form \"xxx:yyy\"")
key, value = values.split(":")
getattr(namespace, self.dest, {})[key] = value
<file_sep>import os
import shutil
import unittest
import docker
from capturewrap import CaptureWrapBuilder, CaptureResult
from patchworkdocker.cli import main
from patchworkdocker.tests._common import TestWithTempFiles, EXAMPLE_BUILD_DIRECTORY, create_image_name
class CliTest(TestWithTempFiles):
"""
TODO
"""
def setUp(self) -> None:
super().setUp()
self.capture_wrap_builder = CaptureWrapBuilder(capture_stdout=True, capture_stderr=True)
self.capture_wrap_builder.capture_exceptions = lambda e: isinstance(e, SystemExit)
def test_no_arguments(self):
self.capture_wrap_builder.capture_exceptions = True
result = self._call_wrapped_main([])
self.assertNotEqual(result.exception.code, 0)
self.assertTrue(result.stderr.startswith("usage:"))
def test_help(self):
result = self._call_wrapped_main(["--help"])
self.assertEqual(result.exception.code, 0)
self.assertTrue(result.stdout.startswith("usage:"))
def test_invalid_action(self):
result = self._call_wrapped_main(["invalid"])
self.assertNotEqual(result.exception.code, 0)
def test_basic_prepare(self):
result = self._call_wrapped_main(["prepare", EXAMPLE_BUILD_DIRECTORY])
directory = result.stdout.strip()
try:
self.assertTrue(os.path.exists(directory))
finally:
shutil.rmtree(directory, ignore_errors=True)
def test_basic_build(self):
image_name = create_image_name()
client = docker.from_env()
expected_output = open(os.path.join(EXAMPLE_BUILD_DIRECTORY, "hello-world.txt"), "rb").read()
try:
self._call_wrapped_main(["build", EXAMPLE_BUILD_DIRECTORY, image_name])
output = client.containers.run(image_name)
self.assertEqual(expected_output, output)
finally:
client.images.remove(image_name, force=True)
def _call_wrapped_main(self, *args, **kwargs) -> CaptureResult:
wrapped_main = self.capture_wrap_builder.build(main)
return wrapped_main(*args, **kwargs)
if __name__ == "__main__":
unittest.main()
<file_sep>#!/usr/bin/env bash
set -euf -o pipefail
# Remove old test coverage data
python -m coverage erase
# Run tests
PYTHONPATH=. python -m coverage run -m unittest discover -v -s patchworkdocker/tests
PYTHONPATH=. python -m coverage run patchworkdocker/cli.py -h
python -m coverage run setup.py -q install
# Generate coverage reports
python -m coverage combine -a
python -m coverage report
python -m coverage xml
<file_sep>import os
import unittest
from abc import abstractmethod
from pathlib import Path
from typing import TypeVar, Generic, Optional
from patchworkdocker.importers import GitImporter, Importer, FileSystemImporter
from patchworkdocker.tests._common import TestWithTempFiles, EXAMPLE_GIT_REPOSITORY
ImporterType = TypeVar("ImporterType", bound=Importer)
class _TestImporter(Generic[ImporterType], TestWithTempFiles):
"""
Tests for `ImporterType`.
"""
@property
@abstractmethod
def importer(self) -> ImporterType:
"""
Gets an instance of the importer under test.
:return: the importer to test
"""
def setUp(self):
super().setUp()
self._importer: Optional[Importer] = None
self._paths = []
def load(self, origin: str) -> str:
"""
Uses the importer under test and calls loads with the given origin. The returned path is removed on tear down.
:param origin: the origin to load from
:return: the path of where the import has been loaded to
"""
path = self.importer.load(origin)
self.temp_manager._temp_directories.add(path)
return path
class TestGitImporter(_TestImporter[GitImporter]):
"""
Tests for `GitImporter`.
"""
@property
def importer(self) -> ImporterType:
if self._importer is None:
self._importer = GitImporter()
return self._importer
def test_load(self):
path = self.load(EXAMPLE_GIT_REPOSITORY)
self.assertTrue(os.path.exists(os.path.join(path, "a/d.txt")))
def test_load_commit(self):
path = self.load(f"{EXAMPLE_GIT_REPOSITORY}#e22fcb940d5356f8dc57fa99d7a6cb4ecdc04b66")
self.assertTrue(os.path.exists(os.path.join(path, "b.txt")))
def test_load_branch(self):
path = self.load(f"{EXAMPLE_GIT_REPOSITORY}#develop")
self.assertTrue(os.path.exists(os.path.join(path, "develop.txt")))
def test_load_tag(self):
path = self.load(f"{EXAMPLE_GIT_REPOSITORY}#1.0")
self.assertTrue(os.path.exists(os.path.join(path, "b.txt")))
class TestFileSystemImporter(_TestImporter[GitImporter]):
"""
Tests for `FileSystemImporter`.
"""
_EXAMPLE_FILE = "test.txt"
@property
def importer(self) -> ImporterType:
if self._importer is None:
self._importer = FileSystemImporter()
return self._importer
def setUp(self):
super().setUp()
self.test_directory = self.temp_manager.create_temp_directory()
Path(os.path.join(self.test_directory, TestFileSystemImporter._EXAMPLE_FILE)).touch()
def test_load(self):
path = self.load(self.test_directory)
self.assertTrue(os.path.exists(os.path.join(path, TestFileSystemImporter._EXAMPLE_FILE)))
if __name__ == "__main__":
unittest.main()
<file_sep>GitPython
patch==1.*
logzero
frozendict
docker
<file_sep>PACKAGE_NAME = "patchworkdocker"
VERSION = "0.0.0"
DESCRIPTION = "TODO"
EXECUTABLE_NAME = "patchworkdocker"
<file_sep>import os
from abc import ABCMeta
from unittest import TestCase
from temphelpers import TempManager
from uuid import uuid4
from patchworkdocker.meta import PACKAGE_NAME
EXAMPLE_GIT_REPOSITORY = "https://github.com/colin-nolan/test-repository.git"
EXAMPLE_BUILD_DIRECTORY = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "building")
class TestWithTempFiles(TestCase, metaclass=ABCMeta):
"""
Base class for tests that use temp files.
"""
def setUp(self):
self.temp_manager = TempManager()
def tearDown(self):
self.temp_manager.tear_down()
def create_image_name():
"""
TODO
:return:
"""
return f"{PACKAGE_NAME}-test:{str(uuid4())}"
<file_sep>#!/usr/bin/env bash
set -euf -o pipefail
scriptDirectory="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
testDirectory="${scriptDirectory}"
# Note: `mktemp` creates temps in directory that cannot be mounted by default on Mac
tempDirectory="/tmp/patchwork-docker-${RANDOM}"
trap "echo ${tempDirectory} && rm -rf ${tempDirectory}" INT TERM HUP EXIT
mkdir "${tempDirectory}"
# XXX: could use docker-compose to build
docker build -t patchworkdocker -f Dockerfile .
docker build -t patchworkdocker-tests -f Dockerfile.test .
docker run --rm -it \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-v "${testDirectory}:${testDirectory}" \
-v "${tempDirectory}:${tempDirectory}" \
-e TMPDIR="${tempDirectory}" \
--entrypoint=bash \
-w "${testDirectory}" \
patchworkdocker-tests ./run-tests.sh
<file_sep>import os
import unittest
import uuid
import docker
from patchworkdocker.docker_images import build_docker_image
from patchworkdocker.tests._common import TestWithTempFiles, EXAMPLE_BUILD_DIRECTORY
class TestBuildDockerImage(TestWithTempFiles):
"""
Test `build_docker_image`.
"""
def setUp(self):
super().setUp()
self._docker_client = docker.from_env()
self._docker_image = f"{__name__}-{uuid.uuid4()}"
def tearDown(self):
super().tearDown()
self._docker_client.images.remove(self._docker_image)
def test_build_docker_image(self):
build_docker_image(self._docker_image, EXAMPLE_BUILD_DIRECTORY, os.path.join(EXAMPLE_BUILD_DIRECTORY, "Dockerfile"))
contents = self._docker_client.containers.run(self._docker_image, "cat /test.txt", remove=True).decode("UTF8")
self.assertEqual(contents, open(os.path.join(EXAMPLE_BUILD_DIRECTORY, "hello-world.txt"), "r").read())
if __name__ == "__main__":
unittest.main()
<file_sep>FROM ubuntu:16.04
COPY . /data
WORKDIR /data
RUN ./setup-1.sh \
&& ./setup-2.sh
ENTRYPOINT ["./entrypoint.sh"]
CMD ["--help"]
<file_sep>import dataclasses
import json
import logging
import sys
from argparse import ArgumentParser
from dataclasses import dataclass
from enum import Enum, unique
from typing import List, Dict, Optional, Union
import logzero
from logzero import logger
from patchworkdocker._external.key_value_string_parser import KeyValueStringParserAction
from patchworkdocker._external.verbosity_argument_parser import verbosity_parser_configuration, VERBOSE_PARAMETER_KEY, \
get_verbosity, DEFAULT_LOG_VERBOSITY_KEY
from patchworkdocker.core import PatchworkDocker
from patchworkdocker.meta import EXECUTABLE_NAME, DESCRIPTION, VERSION
ACTION_PARAMETER = "action"
IMPORT_REPOSITORY_FROM_PARAMETER = "context"
ADDITIONAL_FILES_LONG_PARAMETER = "additional-file"
ADDITIONAL_FILES_SHORT_PARAMETER = "f"
PATCHES_LONG_PARAMETER = "patch"
PATCHES_SHORT_PARAMETER = "p"
DOCKERFILE_LOCATION_LONG_PARAMETER = "dockerfile"
DOCKERFILE_LOCATION_SHORT_PARAMETER = "d"
IMAGE_NAME_PARAMETER = "image-name"
BUILD_LOCATION_LONG_PARAMETER = "build-location"
BUILD_LOCATION_SHORT_PARAMETER = "b"
VERBOSITY_SHORT_PARAMETER = verbosity_parser_configuration[VERBOSE_PARAMETER_KEY]
DRY_RUN_LONG_PARAMETER = "dry-run"
BASE_IMAGE_SHORT_PARAMETER = "i"
BASE_IMAGE_LONG_PARAMETER = "base-image"
DEFAULT_ADDITIONAL_FILES = {}
DEFAULT_PATCHES = {}
DEFAULT_DOCKERFILE_LOCATION = "Dockerfile"
DEFAULT_VERBOSITY = verbosity_parser_configuration[DEFAULT_LOG_VERBOSITY_KEY]
@unique
class ActionValue(Enum):
"""
Program action.
"""
BUILD = "build"
PREPARE = "prepare"
@dataclass
class BaseCliConfiguration:
"""
Base CLI configuration.
"""
log_verbosity: int
dry_run: bool
@dataclass
class SubcommandCliConfiguration(BaseCliConfiguration):
"""
CLI configuration for subcommands.
"""
additional_files: Dict[str, str]
patches: Dict[str, str]
dockerfile_location: str
build_location: Optional[str]
import_from: str
base_image: str
@dataclass
class PrepareCliConfiguration(SubcommandCliConfiguration):
"""
CLI configuration for preparing a patchwork Docker build.
"""
@dataclass
class BuildCliConfiguration(SubcommandCliConfiguration):
"""
CLI configuration for building a patchwork Docker image.
"""
image_name: str
def _create_parser() -> ArgumentParser:
"""
Creates an argument parser.
:return: the created parser
"""
parser = ArgumentParser(prog=EXECUTABLE_NAME, description=f"{DESCRIPTION} (v{VERSION})")
parser.add_argument(f"-{VERBOSITY_SHORT_PARAMETER}", action="count", default=0,
help="increase the level of log verbosity (add multiple increase further)")
parser.add_argument(f"--{DRY_RUN_LONG_PARAMETER}", action="store_true", default=False, help="")
subparsers = parser.add_subparsers(dest=ACTION_PARAMETER, help="TODO")
def take_context_arguments(parser: ArgumentParser):
parser.add_argument(IMPORT_REPOSITORY_FROM_PARAMETER, help="TODO")
def take_common_arguments(parser: ArgumentParser):
parser.add_argument(f"-{ADDITIONAL_FILES_SHORT_PARAMETER}", f"--{ADDITIONAL_FILES_LONG_PARAMETER}",
action=KeyValueStringParserAction, default=DEFAULT_ADDITIONAL_FILES,
help="Files to add to the build context (will override existing files). Input in the form:")
parser.add_argument(f"-{PATCHES_SHORT_PARAMETER}", f"--{PATCHES_LONG_PARAMETER}",
action=KeyValueStringParserAction, help="TODO", default=DEFAULT_PATCHES)
parser.add_argument(f"-{DOCKERFILE_LOCATION_SHORT_PARAMETER}", f"--{DOCKERFILE_LOCATION_LONG_PARAMETER}",
help="TODO", default=DEFAULT_DOCKERFILE_LOCATION)
parser.add_argument(f"-{BUILD_LOCATION_SHORT_PARAMETER}", f"--{BUILD_LOCATION_LONG_PARAMETER}",
help="TODO", default=None)
parser.add_argument(f"-{BASE_IMAGE_SHORT_PARAMETER}", f"--{BASE_IMAGE_LONG_PARAMETER}",
help="TODO", default=None)
build_parser = subparsers.add_parser(ActionValue.BUILD.value, help="TODO")
take_context_arguments(build_parser)
build_parser.add_argument(IMAGE_NAME_PARAMETER, help="TODO")
take_common_arguments(build_parser)
prepare_parser = subparsers.add_parser(ActionValue.PREPARE.value, help="TODO")
take_context_arguments(prepare_parser)
take_common_arguments(prepare_parser)
return parser
def parse_cli_configuration(arguments: List[str]) -> BaseCliConfiguration:
"""
Parses the given CLI arguments.
:param arguments: the arguments from the CLI
:return: parsed configuration
"""
# XXX: Setting a value other than the display string seems to be non-trivial: https://bugs.python.org/issue23487
parsed_arguments = _create_parser().parse_args(arguments)
parsed_arguments = {x.replace("_", "-"): y for x, y in vars(parsed_arguments).items()}
action_value = parsed_arguments[ACTION_PARAMETER]
if action_value is None:
logger.error("No action specified")
_create_parser().print_help(sys.stderr)
exit(1)
parsed_arguments[ACTION_PARAMETER] = ActionValue(action_value)
cli_configuration_class = {
ActionValue.BUILD: BuildCliConfiguration,
ActionValue.PREPARE: PrepareCliConfiguration
}[parsed_arguments[ACTION_PARAMETER]]
extra_configuration = {}
if issubclass(cli_configuration_class, BuildCliConfiguration):
extra_configuration["image_name"] = parsed_arguments[IMAGE_NAME_PARAMETER]
cli_configuration = cli_configuration_class(
log_verbosity=get_verbosity(parsed_arguments),
dry_run=parsed_arguments[DRY_RUN_LONG_PARAMETER],
additional_files=parsed_arguments[ADDITIONAL_FILES_LONG_PARAMETER],
patches=parsed_arguments[PATCHES_LONG_PARAMETER],
dockerfile_location=parsed_arguments[DOCKERFILE_LOCATION_LONG_PARAMETER],
build_location=parsed_arguments[BUILD_LOCATION_LONG_PARAMETER],
import_from=parsed_arguments[IMPORT_REPOSITORY_FROM_PARAMETER],
base_image=parsed_arguments[BASE_IMAGE_LONG_PARAMETER],
**extra_configuration
)
return cli_configuration
def _set_log_level(level: int):
"""
Sets the log level to that given.
:param level: log level to set
"""
logzero.loglevel(level)
if level == logging.WARNING:
logger.warning("There are not likely to be many WARN level logs: consider increasing the verbosity by adding"
f"more -{VERBOSITY_SHORT_PARAMETER}")
def print_configuration(configuration: BaseCliConfiguration):
"""
Prints information about the given configuration to stdout.
:param configuration: configuration to output
"""
configuration_as_json = json.dumps(dataclasses.asdict(configuration))
print(configuration_as_json)
def build(core: PatchworkDocker, configuration: BuildCliConfiguration):
"""
Builds patchwork Docker image with the given configuration.
:param core: patchwork Docker core
:param configuration: build configuration
:return:
"""
core.build(configuration.image_name, configuration.build_location)
def prepare(core: PatchworkDocker, configuration: PrepareCliConfiguration):
"""
Prepares for patchwork Docker build.
:param core: patchwork Docker core
:param configuration: build configuration
:return:
"""
output = core.prepare(configuration.build_location)
print(output)
def main(cli_arguments: List[str]):
"""
Main.
:param cli_arguments: arguments passed in via the CLI
:raises SystemExit: always raised
"""
cli_configuration = parse_cli_configuration(cli_arguments)
if cli_configuration.log_verbosity:
_set_log_level(cli_configuration.log_verbosity)
if cli_configuration.dry_run:
print_configuration(cli_configuration)
exit(0)
# XXX: Ideally, we would use `configuration: Intersect[ContextUsingCliConfiguration, SubcommandCliConfiguration]
# but multiple bounds are sadly not supported in Python's type hinting: https://github.com/python/typing/issues/213
def create_core(configuration: Union[PrepareCliConfiguration, BuildCliConfiguration]) -> PatchworkDocker:
return PatchworkDocker(configuration.import_from, additional_files=configuration.additional_files,
patches=configuration.patches, dockerfile_location=configuration.dockerfile_location,
base_image=cli_configuration.base_image)
{
BuildCliConfiguration: lambda: build(create_core(cli_configuration), cli_configuration),
PrepareCliConfiguration: lambda: prepare(create_core(cli_configuration), cli_configuration),
}[type(cli_configuration)]()
def entrypoint():
"""
Entry-point to be used by CLI.
"""
logger.setLevel(DEFAULT_VERBOSITY)
main(sys.argv[1:])
if __name__ == "__main__":
entrypoint()
<file_sep>FROM alpine
ADD hello-world.txt /test.txt
CMD cat /test.txt<file_sep>import fileinput
import itertools
import os
import shutil
from distutils import dir_util
from tempfile import TemporaryDirectory
from patch import fromfile
def copy_file(file: str, destination: str):
"""
Copy the given file (which could be a directory) to the given destination.
:param file: the file (which could be a directory) to copy
:param destination: where to copy the file to
"""
if not os.path.exists(file):
raise FileExistsError(f"Cannot copy file {file} as it does not exist")
if os.path.isfile(file):
shutil.copy(file, destination)
else:
dir_util.copy_tree(file, destination)
def apply_patch(patch_file: str, target_file: str):
"""
Applies the given patch file (plain, git, mercurial or svn styles accepted) to the given target file.
To create a compatible patch between two files, you could use:
```
diff -uNr src_1 src_2
```
:param patch_file: the patch to apply
:param target_file: the patch target
"""
patch_set = fromfile(patch_file)
if not patch_set:
raise SyntaxError(f"Could not parse contents of patch file: {patch_file}")
hunks = list(itertools.chain(*[item.hunks for item in patch_set.items]))
with TemporaryDirectory() as temp_directory:
temp_file = os.path.join(temp_directory, os.path.basename(target_file))
patch_set.write_hunks(target_file, os.path.join(temp_file), hunks)
shutil.move(temp_file, target_file)
def change_base_image(dockerfile_location: str, desired_base: str):
"""
TODO
:param dockerfile_location:
:param desired_base:
:return:
"""
changed = False
for line in fileinput.input(dockerfile_location, inplace=True):
if line.upper().startswith("FROM"):
assert not changed
print(f"FROM {desired_base}")
changed = True
else:
print(line, end="")
if not changed:
raise ValueError(f"Dockerfile did not contain FROM line: {dockerfile_location}")
| 140b9a12e31420d74e18a0da404b205e36a9727b | [
"Markdown",
"Python",
"Text",
"Dockerfile",
"Shell"
] | 23 | Python | colin-nolan/patchwork-docker | fd5fff5d5ece03457d41bf7f616a70c0b4300a5d | d60e0d55aeb9e3fae37f85140ee8222d137fb591 | |
refs/heads/master | <file_sep>package com.sdcuike.gradlelearning.controller;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author sdcuike
* @date 2018/4/23
*/
@RestController
@RequestMapping("/demo")
public class DemoController {
@PostMapping("/test")
public DemoResponseDto test(@RequestBody DemoRequestDto demoRequestDto) {
return new DemoResponseDto(0, "");
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class DemoRequestDto {
private String name;
private Integer age;
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public static class DemoResponseDto {
private Integer code;
private String msg;
}
}
<file_sep>buildscript {
ext {
springBootVersion = '2.0.1.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
classpath 'com.webcohesion.enunciate:enunciate-lombok:2.10.1'
}
}
plugins {
id 'io.franzbecker.gradle-lombok' version '1.13'
id "com.webcohesion.enunciate" version "2.10.1"
}
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
group = 'com.sdcuike'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compileOnly('org.projectlombok:lombok')
testCompile('org.springframework.boot:spring-boot-starter-test')
}
tasks.enunciate {
File enunciateDistDir = file("src/main/resources/static/docs/api")
doFirst {
project.delete("build/enunciate")
enunciateDistDir.deleteDir()
enunciateDistDir.mkdirs()
}
export("docs", enunciateDistDir)
}
assemble {
doFirst {
enunciate.execute()
}
}<file_sep># gradle-learning
## enunciate文档自动生成(集成lombok)
- [文档访问地址:本地启动](http://localhost:8080/docs/api/index.html)
- [上述文档可进入swagger 界面](http://localhost:8080/docs/api/ui/index.html)
##
[https://github.com/sdcuike/gradle-learning/tree/enunciate文档自动生成-集成lombok](https://github.com/sdcuike/gradle-learning/tree/enunciate文档自动生成-集成lombok)<file_sep>rootProject.name = 'gradle-learning'
<file_sep>package com.sdcuike.gradlelearning;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @author sdcuike
* @date 2018/4/23
*/
@SpringBootApplication
public class GradleLearningApplication {
public static void main(String[] args) {
SpringApplication.run(GradleLearningApplication.class, args);
}
}
| 5e55797c588912ce79e6aaa66e1e384ebec13edb | [
"Markdown",
"Java",
"Gradle"
] | 5 | Java | sdcuike/gradle-learning | 2b0cc9a9d744685b445309d3e295d04b3bf3db63 | 89ab1732f90888f1b6fec45e138c7f85065544ad | |
refs/heads/master | <repo_name>ck4957/.NET-Projects<file_sep>/LibrarySystem/OnlyBook/Repository/IAuthorRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OnlyBook.Models;
namespace OnlyBook.Repository
{
public interface IAuthorRepository
{
Author Add(Author author);
IEnumerable<Author> GetAll();
Author GetById(int id);
Author GetByName(string authorName);
void Delete(Author author);
void Update(Author author);
void AddBooktoAuthor(Author author);
}
}
<file_sep>/LibrarySystem/OnlyBook/Repository/ILibraryRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OnlyBook.Models;
namespace OnlyBook.Repository
{
public interface ILibraryRepository
{
Library Add(Library library);
IEnumerable<Library> GetAll();
Library GetById(int id);
void Delete(Library library);
void Update(Library library);
}
}
<file_sep>/LibrarySystem/OnlyBook/Repository/IPatronRepository.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using OnlyBook.Models;
namespace OnlyBook.Repository
{
public interface IPatronRepository
{
Patron Add(Patron patron);
IEnumerable<Patron> GetAll();
Patron GetById(int id);
void Delete(Patron patron);
void Update(Patron patron);
void Checkout(int patronid, int bookid);
void BookReturn(int patronid, int bookid);
}
}
| d82f21e2c38a46a2111791117d35322950ee2902 | [
"C#"
] | 3 | C# | ck4957/.NET-Projects | 5b34cf22bbd1e61048c11bc303cc184a1f88d24f | c40872e6587a7f1741500245b064acdad89eaa92 | |
refs/heads/master | <file_sep>package com.example.webpagescannerapp.other;
import com.example.webpagescannerapp.service.RequestService;
public class MyRunnable implements Runnable {
RequestService requestService;
public MyRunnable(RequestService requestService){
this.requestService = requestService;
}
@Override
public void run() {
requestService.launch();
}
}
<file_sep># WebpageScannerApp
## Описание
Мобильное приложение воспроизводит поиск на web-страницах. В зависимости от количества<br/>
страниц, введенных пользователем, осуществляется построение дерева(графа) страниц по принципу "в ширину"<br/>
Далее запускается поиск текста на страницах, при чем используя параматрезированный набор потоков.<br/>
Из входных данных от пользователя необходимо запросить стартовый url, текст для поиска, количество страниц и потоков.<br/>
### Пользовательский интерфейс
Интерфейс взаимодействия с пользователем осуществлен на двух Activity: MainActivity, SearchActivity<br/>
В MainActivity пользователь вводит необходимые входные данные, валидация полей также реализована<br/>
В SearchActivity пользователь может увидить "терминал" с информацией о сканируемых адресах, статусе и тд.<br/>
Также есть панель управления, которая состоит из кнопок PauseButton, StartButton, StopButton<br/>
Над панелью управления расположен ProgressBar, который динамически прогрессирует во время просмотра страниц.<br/>
### Предположения (ответ на вопрос в ТЗ)
1. В задании указано, что надо осуществлять поиск текста и показывать статус "Найдено/Не найдено/Ошибка". Соответственно задача-минимум
это проверить наличие хотя бы одного совпадения текста на сканируемой странице. В приложении реализована чуть более сложная задача:
это поиск количества совпадений. В терминале на каждом url будет отметка Matches: N, где N - кол-во совпадений.<br/>
2. Предполагаем, что количество потоков сканирования точно больше 0. (В NumberPicker view нельзя выбрать 0 потоков). UI thread<br/>
не считаем.<br/>
3. Не указана необходимость адаптировать приложение под различный версии ОС и экраны, предположим, что достаточно концептуальной
реализации без адаптаций.<br/>
### Кратко об архитектуре
Алгоритм реализации основной задачи (поиска информации) разделен в несколько этапов.<br/>
1. Сбор входных данных делается на MainActivity.<br/>
2. ScannerService рекурсивно сканирует ссылки начиная с базовой и строит граф ссылок и их уровня в условном дереве.<br/>
Структура данных используется - LinkedHashMap для удовлетворения последовательности нод и уникальности.<br/>
3. RequestService проходит по созданной мапе и делает GET-запросы получая информацию со страницы в обьект RequestInfo.<br/>
Всю полученную информацию параллельно отображает на терминале (RecyclerView), который виден пользователю.<br/>
## Технологии
* Java core, collections, Executor API (for multithreading)
* OkHttp3 (http client)
* Retrofit2 (rest client)
* Jsoup (html parsing library)
* Android Studio
## Тестирование
Правильный подход к тестированию заключается в изначальном составлении Testing strategy/Testing plan/Requirement specification<br/>
Для базовой бизнес логики можно составить юнит-тесты используя к примеру фреймворк Mockito<br/>
Для тестирования внутри потоков можно использовать например Thread Weaver<br/>
## Screenshots


<file_sep>include ':app'
rootProject.name = "WebpageScannerApp"<file_sep>package com.example.webpagescannerapp.service;
import android.app.Activity;
import android.os.Build;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;
import okhttp3.OkHttpClient;
import okhttp3.Request;
public class ScannerService {
// This service collects HashMap of pages that we should pass (number entered by user)
// Recursive method that collects url's by Breadth-Search-Tree method
private OkHttpClient client; // http client
private LinkedHashMap<String, Integer> map; // Our main map with data
private String baseUrl, currentUrl;
private int maxLinkNumber, currentLinkNumber;
private int currentLevel;
public ScannerService(OkHttpClient client, String myBaseUrl, int myMaxLinksNumber){
this.client = client;
this.baseUrl = myBaseUrl;
this.maxLinkNumber = myMaxLinksNumber;
currentUrl = myBaseUrl;
this.currentLinkNumber = 0;
map = new LinkedHashMap<>(myMaxLinksNumber);
}
// Map Getter
public LinkedHashMap<String, Integer> getMap() {
return map;
}
// Document Getter
private Document getDocument() throws IOException {
Request request = new Request.Builder()
.url(currentUrl)
.get().build();
return Jsoup.parse(client.newCall(request).execute().body().string());
}
// Recursive function for collecting data into map
public void fillMap(Activity activity) throws IOException, InterruptedException {
//Assume that maxLinkNumber >= 1
// Lvl 0 processing
if (currentLevel == 0){
map.put(baseUrl, 0);
currentLinkNumber++;
currentLevel++;
// If links processed number < max links then go next
if (currentLinkNumber < maxLinkNumber){
// Recursive call
fillMap(activity);
}
else {
return;
}
} // Lvl 1 processing
else if (currentLevel == 1){
final Elements[] links = new Elements[1];
final int[] fullSize = new int[1];
Runnable r = () -> {
try {
links[0] = getDocument().select("a[href^=http]"); // start with http
fullSize[0] = links[0].size();
activity.runOnUiThread(() -> Toast.makeText(activity, "fullSize :" + fullSize[0], Toast.LENGTH_SHORT)
.show());
} catch (IOException e) {
e.printStackTrace();
}
};
Thread t = new Thread(r);
t.start();
t.join();
for (Element link : links[0]){
if (currentLinkNumber < maxLinkNumber){
// Avoid repeated urls
if (!map.containsKey(link.attr("href"))){
map.put(link.attr("href"), currentLevel);
currentLinkNumber++;
}
}
else {
return;
}
}
currentLevel++;
// If links processed number < max links then go next
if (currentLinkNumber < maxLinkNumber){
// Recursive call
fillMap(activity);
}
else {
return;
}
}
else { // Process level 2+
for (int j = 0; j < map.entrySet().stream().filter(node ->
node.getValue() == currentLevel-1).count(); j++){
LinkedHashMap<String, Integer> mapOfCurrentLevel = map.entrySet().stream()
.filter(node -> node.getValue() == currentLevel-1)
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
for (Map.Entry<String, Integer> node : mapOfCurrentLevel.entrySet()){
// Current url assign to entry with value of first match with url of current lvl
currentUrl = node.getKey();
final Elements[] linksOfNode = new Elements[1];
Runnable r = () -> {
try {
linksOfNode[0] = getDocument().select("a[href^=http]"); // start with http
} catch (IOException e) {
Toast.makeText(activity, e.getMessage(), Toast.LENGTH_SHORT).show();
}
};
Thread t = new Thread(r);
t.start();
t.join();
for (Element link : linksOfNode[0]){
if (currentLinkNumber < maxLinkNumber){
// Avoid repeated urls
if (!map.containsKey(link.attr("href"))){
map.put(link.attr("href"), currentLevel);
currentLinkNumber++;
}
}
else {
return;
}
}
}
currentLevel++;
// If links processed number < max links then go next
if (currentLinkNumber < maxLinkNumber){
// Recursive call
fillMap(activity);
}
else {
return;
}
}
}
}
}
<file_sep>package com.example.webpagescannerapp.activity;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
import com.example.webpagescannerapp.databinding.ActivityMainBinding;
import com.example.webpagescannerapp.other.NumericKeyBoardTransformationMethod;
import com.example.webpagescannerapp.R;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
// View binding class
ActivityMainBinding binding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getSupportActionBar().hide();
binding = ActivityMainBinding.inflate(getLayoutInflater());
//setContentView(R.layout.activity_main);
setContentView(binding.getRoot());
setUpMaxPageNumberEditText();
setUpNumberPicker();
}
// public void initViews(){
// urlEditText = findViewById(R.id.urlEditText);
// textEditText = findViewById(R.id.textEditText);
// maxPageNumberEditText = findViewById(R.id.maxPageNumberEditText);
// threadsNumberPicker = findViewById(R.id.threadsNumberPicker);
// }
public void setUpMaxPageNumberEditText(){
binding.maxPageNumberEditText.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
binding.maxPageNumberEditText.setTransformationMethod(new NumericKeyBoardTransformationMethod());
}
public void setUpNumberPicker(){
binding.threadsNumberPicker.setMinValue(1);
binding.threadsNumberPicker.setMaxValue(64);
binding.threadsNumberPicker.setValue(1);
binding.threadsNumberPicker.setWrapSelectorWheel(false);
binding.threadsNumberPicker.setTextColor(getResources().getColor(R.color.colorWhite));
}
public void searchButtonClicked(View view) {
if (isAllFieldsValid()){
Intent intent = new Intent(MainActivity.this, SearchActivity.class);
intent.putExtra("url", binding.urlEditText.getText().toString());
intent.putExtra("text", binding.textEditText.getText().toString());
intent.putExtra("max_pages_number", binding.maxPageNumberEditText.getText().toString());
intent.putExtra("threads_number", binding.threadsNumberPicker.getValue());
startActivity(intent);
}
}
// Validation for Url field
public boolean isUrlValid(){
Pattern pattern = Pattern.compile("^(https?)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]");
Matcher match = pattern.matcher(binding.urlEditText.getText().toString());
if (match.matches()){
binding.urlEditText.setBackgroundResource(R.drawable.drawable_edit_text_valid);
return true;
}
else {
binding.urlEditText.setBackgroundResource(R.drawable.drawable_edit_text_invalid);
Toast.makeText(this, "Enter correct url please", Toast.LENGTH_SHORT).show();
return false;
}
}
// Validation for Text field
public boolean isTextForSearchValid(){
if (binding.textEditText.getText().toString().length() > 0){
binding.textEditText.setBackgroundResource(R.drawable.drawable_edit_text_valid);
return true;
}
else {
binding.textEditText.setBackgroundResource(R.drawable.drawable_edit_text_invalid);
Toast.makeText(this, "Enter correct text please", Toast.LENGTH_SHORT).show();
return false;
}
}
// Validation for Max pages field
public boolean isMaxPagesNumberValid(){
if (binding.maxPageNumberEditText.getText().toString().length() > 0 &&
Integer.parseInt(binding.maxPageNumberEditText.getText().toString()) > 0){
binding.maxPageNumberEditText.setBackgroundResource(R.drawable.drawable_edit_text_valid);
return true;
}
else {
binding.maxPageNumberEditText.setBackgroundResource(R.drawable.drawable_edit_text_invalid);
Toast.makeText(this, "Enter correct pages-number please", Toast.LENGTH_SHORT).show();
return false;
}
}
// General validation
private boolean isAllFieldsValid(){
return isUrlValid() && isTextForSearchValid() && isMaxPagesNumberValid();
}
}<file_sep>package com.example.webpagescannerapp.activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.ProgressBar;
import android.widget.Toast;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.webpagescannerapp.databinding.ActivitySearchBinding;
import com.example.webpagescannerapp.other.MyRunnable;
import com.example.webpagescannerapp.R;
import com.example.webpagescannerapp.service.RequestService;
import com.example.webpagescannerapp.service.ScannerService;
import com.example.webpagescannerapp.adapter.RequestAdapter;
import com.example.webpagescannerapp.model.RequestInfo;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;
import okhttp3.OkHttpClient;
public class SearchActivity extends AppCompatActivity {
ActivitySearchBinding binding;
LinkedHashMap<String, Integer> nMap; // Map from ScannerService
// Values for current iteration
String text;
int threadsNumber;
ExecutorService executorService; // Executor service for several threads execution
List<Runnable> terminatedWorkersList; // When process paused (For executor.shutDownNow())
RequestAdapter requestAdapter; // Adapter for RecyclerView
ArrayList<RequestInfo> requestList; // List for RecyclerView
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getSupportActionBar().hide();
binding = ActivitySearchBinding.inflate(getLayoutInflater());
// setContentView(R.layout.activity_search);
setContentView(binding.getRoot());
//initViews();
initControlPanel();
Intent intent = getIntent();
// Getting data from intent
String url = intent.getStringExtra("url");
text = intent.getStringExtra("text");
int maxPagesNumber = Integer.parseInt(intent.getStringExtra("max_pages_number"));
threadsNumber = intent.getIntExtra("threads_number", 1);
// Setting http client
OkHttpClient okHttpClient = new OkHttpClient();
// Setting recycler view
setUpRecyclerView();
// Building tree of url's
ScannerService scanner1 = new ScannerService(okHttpClient, url, maxPagesNumber);
try{
scanner1.fillMap(SearchActivity.this);
} catch (IOException | InterruptedException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
// Setting progress bar (horizontal)
setUpProgressBar(scanner1);
// Getting map from ScannerService
nMap = scanner1.getMap();
// Creating and launching ExecutorService
executorService = Executors.newFixedThreadPool(threadsNumber);
launchExecutor();
}
// public void initViews(){
// progressBar = findViewById(R.id.progressBar);
// pauseButton = findViewById(R.id.pauseButton);
// playButton = findViewById(R.id.playButton);
// stopButton = findViewById(R.id.stopButton);
// recyclerView = findViewById(R.id.recyclerView);
// }
public void initControlPanel(){
binding.playButton.setEnabled(false);
binding.playButton.setAlpha(0.5f);
binding.pauseButton.setEnabled(true);
binding.pauseButton.setAlpha(1.0f);
binding.stopButton.setEnabled(true);
binding.stopButton.setAlpha(1.0f);
}
public void setUpRecyclerView(){
requestList = new ArrayList<>();
requestAdapter = new RequestAdapter(this, requestList);
binding.recyclerView.setAdapter(requestAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
binding.recyclerView.setLayoutManager(linearLayoutManager);
}
public void setUpProgressBar(ScannerService scanner){
binding.progressBar.setMin(0);
binding.progressBar.setMax(scanner.getMap().size());
binding.progressBar.setProgress(0);
}
private void switchPlayPauseButtons(boolean isPlaying){
if (isPlaying){
binding.playButton.setEnabled(false);
binding.playButton.setAlpha(0.5f);
binding.pauseButton.setEnabled(true);
binding.pauseButton.setAlpha(1.0f);
}
else {
binding.playButton.setEnabled(true);
binding.playButton.setAlpha(1.0f);
binding.pauseButton.setEnabled(false);
binding.pauseButton.setAlpha(0.5f);
}
}
public void playButtonClicked(View view) {
switchPlayPauseButtons(true);
resumeExecutor();
}
public void pauseButtonClicked(View view) {
switchPlayPauseButtons(false);
pauseExecutor();
}
public void stopButtonClicked(View view){
executorService.shutdownNow();
Toast.makeText(this, "FULL STOP", Toast.LENGTH_SHORT).show();
binding.stopButton.setAlpha(0.5f);
binding.stopButton.setEnabled(false);
binding.pauseButton.setAlpha(0.5f);
binding.pauseButton.setEnabled(false);
}
private void pauseExecutor(){
terminatedWorkersList = executorService.shutdownNow();
}
private void resumeExecutor(){
launchExecutor();
}
private void launchExecutor(){
// Start from paused_state (if conditions are unsatisfied then start_state)
if (terminatedWorkersList != null && terminatedWorkersList.size() > 0){
executorService = Executors.newFixedThreadPool(threadsNumber);
for (Runnable r : terminatedWorkersList){
executorService.execute(r);
}
}
//Start or continue executing tasks
for (Map.Entry<String, Integer> node : nMap.entrySet()){
String currentUrl = node.getKey();
// Runnable worker = new MyRunnable(currentUrl, SearchActivity.this, requestAdapter,
// recyclerView, text, requestList, progressBar);
RequestService requestService = new RequestService(currentUrl, SearchActivity.this,
requestAdapter, binding.recyclerView, text, requestList, binding.progressBar);
MyRunnable worker = new MyRunnable(requestService);
executorService.execute(worker);
// Remove this node via stream() -> (to maintain resume_state)
LinkedHashMap<String, Integer> newMap = nMap.entrySet()
.stream()
.filter(e -> !e.getKey().equals(currentUrl))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
nMap = newMap;
}
executorService.shutdown();
}
}
<file_sep>package com.example.webpagescannerapp.model;
public enum Status {
STATUS_FOUND, STATUS_NOT_FOUND, STATUS_ERROR
}
| 101e4bcd21dce9147158a34d048968af9b095725 | [
"Markdown",
"Java",
"Gradle"
] | 7 | Java | Sandora1933/WebpageScannerApp | 5f20e0bdadfb84253d57a7b35fe07c06b1db279d | 06bdd45c04391a8b3769cff0db48fe772869939f | |
refs/heads/master | <repo_name>esleytel22/safeMatrix<file_sep>/SA.cpp
#include<iostream>
#include <cstdlib>
#include <cassert>
#include<fstream>
#include<sstream>
using namespace std;
/*Generic Safe Array Class*/
template <class T> class SA;
template <class T> class SM;
template <class T> ostream& operator<<(ostream& os, SA<T> s);
template <class T> ostream& operator<< (ostream& os, SM<T> s);
template < class T > class SA {
private:
int low, high;
T *p;
public:
SA() {
low = 0;
high = -1;
p = NULL;
}
SA(int l, int h) {
if ((h - l + 1) <= 0) {
cout << "constructor bounds error" << endl;
exit(1);
}
low = l;
high = h;
p = new T[h - l + 1];
}
SA(int i) {
low = 0;
high = i - 1;
p = new T[i];
}
SA(const SA & s) {
int size = s.high - s.low + 1;
p = new T[size];
for (int i = 0; i < size; i++)
p[i] = s.p[i];
low = s.low;
high = s.high;
}
~SA() {
delete[]p;
}
T & operator[](int i) {
if (i < low || i > high) {
cout << "index " << i << " out of range" << endl;
exit(1);
}
return p[i - low];
}
SA & operator=(const SA & s) {
if (this == &s)
return *this;
delete[]p;
int size = s.high - s.low + 1;
p = new T[size];
for (int i = 0; i < size; i++)
p[i] = s.p[i];
low = s.low;
high = s.high;
return *this;
}
int* operator+(int i) {
return &p[low + i];
}
friend ostream& operator<< <T> (ostream& os, SA<T> s);
};
template <class T> ostream & operator<<(ostream & os, SA < T > s) {
int size = s.high - s.low + 1;
for (int i = 0; i < size; i++)
os << s.p[i] << endl;
return os;
}
| 009b2d03ebacbe49d824a38a9857e51a60fa8c10 | [
"C++"
] | 1 | C++ | esleytel22/safeMatrix | 4f6d9572bb44cb55829ddb2b8502bcff68338061 | 6ceca3aeb219ed8c86b64e3583e7e7223b3c4ca6 | |
refs/heads/master | <file_sep>// pages/home/home.js
Page({
/**
* 页面的初始数据
*/
data: {
imgUrls: [
'/assets/banner/banner1.png',
'/assets/banner/banner2.png',
'/assets/banner/banner3.png',
'/assets/banner/banner4.png',
],
indicatorDots: true, // 是否显示面板指示点
autoplay: true, // 是否自动切换
circular: true, // 是否采用衔接滑动
interval: 3000, // 自动切换时间间隔
duration: 1000, // 滑动动画时长
Height: "" ,
active1: [0],
active2: 0,
active3: [],
title1: '美的总部大楼医务室',
title2: '美的创新中心医务室',
title3: '美的体检中心',
title4:'就医流程指南',
content1: '美的总部大楼D区105室',
content2: '工作时间:9:20-12:00 14:00-17:30',
content3: '美的创新中心靠近西门',
content4:'工作时间:9:00-12:00 14:00-17:30',
content5: '顺德区展业路与新业四路交叉口东北100米'
},
getLocation: function () {
wx.getLocation({
type: 'wgs84',
success: function (res) {
wx.openLocation({//使用微信内置地图查看位置。
latitude: 22.913055,//要去的纬度-地址
longitude: 113.22998,//要去的经度-地址
name: "美的第二医务室",
address: '美的第二医务室'
})
}
})
},
onChange(event) {
const { key } = event.currentTarget.dataset;
this.setData({
[key]: event.detail
});
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
imgHeight: function (e) {
var winWid = wx.getSystemInfoSync().windowWidth; //获取当前屏幕的宽度
var imgh = e.detail.height;//图片高度
var imgw = e.detail.width;//图片宽度
var swiperH = winWid * imgh / imgw + "px"
this.setData({
Height: swiperH//设置高度
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
}) | 11b72cb64ba9b6efacf2d4c45ec43aaa5a8bee82 | [
"JavaScript"
] | 1 | JavaScript | konangolden/mideatest | 12f1e4ce5889b6586e42a50a657d4774245b2786 | 774c23d007aa9a1d4bcd481133ba926bdb1fcf60 | |
refs/heads/master | <file_sep>package sudokuGUI;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.util.Scanner;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.border.Border;
import sudokuGUI.ClickHandler;
public class SudokuGUI extends JFrame {
Button[][] buttons;
static int[][] NUMS;
static boolean[][] ISDISPLAYED;
static int ROWS = 3;
static int COLS = 3;
// Stores current number selected from the numpad
private int curNum;
public SudokuGUI() {
super("Sudoku"); // Window title
// Set x button to close when clicked
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
// Make frame visible
this.setVisible(true);
// Make outer JFrame to hold smaller JFrames
JPanel bigGrid = new JPanel();
// Outer JFrame is 3x3 grid to hold 9 more 3x3 grids
bigGrid.setLayout(new GridLayout(ROWS, COLS));
// Make padding
Border padding1 = BorderFactory.createEmptyBorder(20, 20, 20, 20);
bigGrid.setBorder(padding1);
// Set correct button values
NUMS = new int[][] {
{1,2,3,6,7,8,9,4,5},
{5,8,4,2,3,9,7,6,1},
{9,6,7,1,4,5,3,2,8},
{3,7,2,4,6,1,5,8,9},
{6,9,1,5,8,3,2,7,4},
{4,5,8,7,9,2,6,1,3},
{8,3,6,9,2,4,1,5,7},
{2,1,9,8,5,7,4,3,6},
{7,4,5,3,1,6,8,9,2} };
// Set boolean values
// False values are what users have to input/are not displayed
ISDISPLAYED = new boolean[][] {
{false, true, false, true, false, true, false, false, false},
{true, true, false, false, false, true, true, false, false},
{false, false, false, false, true, false, false, false, false},
{true, true, false, false, false, false, true, false, false},
{true, false, false, false, false, false, false, false, true},
{false, false, true, false, false, false, false, true, true},
{false, false, false, false, true, false, false, false, false},
{false, false, true, true, false, false, false, true, true},
{false, false, false, true, false, true, false, true, false}};
// Boolean values for testing win methods
/*
* ISDISPLAYED = new boolean[][] { {true, false, true, true, true, true, true,
* true, true}, {true, true, true, true, true, true, true, true, true}, {true,
* true, true, true, true, true, true, true, true}, {true, true, true, true,
* true, true, true, true, true}, {true, true, true, true, true, true, true,
* true, true}, {true, true, true, true, true, true, true, true, true}, {true,
* true, true, true, true, true, true, true, true}, {true, true, true, true,
* true, true, true, true, true}, {true, true, true, true, true, true, false,
* false, false}};
*/
// Initialize buttons list to hold buttons
buttons = new Button[9][9];
// Make 9 more smaller panels to hold a 3x3 grid of buttons each
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
JPanel smallGrid = new JPanel();
smallGrid.setLayout(new GridLayout(ROWS,COLS));
smallGrid.setBorder(BorderFactory.createLineBorder(Color.black));
for (int k = 0; k < ROWS; k++) {
for (int m = 0; m < COLS; m++) {
// Send integer values and boolean values to Button constructor
Button b = new Button(NUMS[i*3 + k][j*3 + m], ISDISPLAYED[i*3 + k][j*3 + m]);
// Add button to list of buttons
buttons[i*3 + k][j*3 + m] = b;
smallGrid.add(b);
// Add actionListener to track mouse clicks
b.addActionListener(new ClickHandler(this));
}
}
bigGrid.add(smallGrid);
}
}
// Make number pad panel
JPanel numPad = new JPanel();
// Num panel is 3x3
numPad.setLayout(new GridLayout(ROWS, COLS));
// Make padding
numPad.setBorder(BorderFactory.createLineBorder(Color.black));
Border padding2 = BorderFactory.createEmptyBorder(280, 10, 280, 10);
numPad.setBorder(padding2);
// Add numbers 1-9 to the number pad
int num = 1;
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
// Make new numpad button to add to frame
NumPadButton n = new NumPadButton(num);
numPad.add(n);
// Add actionListener to track mouse clicks.
n.addActionListener(new ClickHandler(this)); // "this" is the current game
num++;
}
}
this.add(bigGrid);
// Add numPad to frame, put on the right
this.add(numPad, BorderLayout.EAST);
// Have window match layout of JPanels
this.pack();
}
// Checks if game has been won
// Called by ClickHandler class after each click
public boolean checkWin() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!buttons[i][j].isCurBool()) { // Only checks values that user can change
if (buttons[i][j].getCurButtonValue() != NUMS[i][j]) {
// Return false and stops check if at least one value is incorrect
return false;
}
}
}
}
// If method makes it here, all values are correct
return true;
}
// Displays new frame to tell player they've won
// Called by ClickHandler class if checkWin() returns true
public void displayWon() {
JFrame winFrame = new JFrame("Sudoku");
winFrame.setSize(900,60);
winFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel winPanel = new JPanel();
JLabel winLabel = new JLabel("Winnah winnah <NAME>! Congratulations on beating this epic game of Sudoku!");
winPanel.add(winLabel);
winFrame.add(winPanel);
winFrame.setVisible(true);
this.pack();
}
// Gets the current number selected on the grid
public int getCurNum() {
return curNum;
}
// Set the current number selected on the grid
public void setCurNum(int num) {
curNum = num;
}
// Make new instance of the game
public static void main(String[] args) {
SudokuGUI game = new SudokuGUI();
}
}
<file_sep>package sudokuGUI;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import javax.swing.BorderFactory;
import javax.swing.JButton;
public class Button extends JButton {
private int realNum; // original, correct value displayed
private boolean isDisplayed = false;
private int curDisplayed; // current value displayed by user
// (may not be correct)
public Button(int num, boolean display) {
realNum = num;
isDisplayed = display;
// Only displays numbers on buttons that are set to true
if (isDisplayed) {
this.setText(Integer.toString(realNum));
this.setFont(new Font(Font.SERIF, Font.BOLD, 50));
this.setBackground(Color.LIGHT_GRAY);
} else {
this.setPreferredSize(new Dimension(90,90));
this.setBackground(Color.white);
this.setBorder(BorderFactory.createLineBorder(Color.black));
}
}
// Change the number displayed on the button
public void setCurDisplayed(int num, Button b) {
curDisplayed = num;
// Do not change button if boolean value is true.
// A true value means the button is part of the
// original grid and should not be changeable.
if (!isDisplayed) {
b.setText(Integer.toString(curDisplayed));
b.setFont(new Font(Font.SERIF, Font.BOLD, 50));
}
}
// Gets the current value stored showed on the button
public int getCurButtonValue() {
return curDisplayed;
}
// Returns the current boolean value of the button
// (If it was originally displayed or not
public boolean isCurBool() {
return isDisplayed;
}
}
| 5d61cbee6279e46c158bfd50c8bd4e78adf429f3 | [
"Java"
] | 2 | Java | cinadia/SudokuGUI | bd1b9d2b5cce0750e72b3fddc621f51761c9fe96 | 4ac28f64343db01acaa61c82063dcccacaa669cc | |
refs/heads/main | <file_sep># Hemingway
A reverse engineered version of Hemingway editor for VSCode.
Inspired from https://www.freecodecamp.org/news/https-medium-com-samwcoding-deconstructing-the-hemingway-app-8098e22d878d/
- Uses https://www.npmjs.com/package/retext-english + Unified
- Naive perf, parses the full doc at all times.
## Structure
```
.
├── client // Language Client
│ ├── src
│ │ ├── test // End to End tests for Language Client / Server
│ │ └── extension.ts // Language Client entry point
├── package.json // The extension manifest.
└── server // Language Server
└── src
└── server.ts // Language Server entry point
```
<file_sep>import type {Processor} from "unified";
export type {Processor};
export function importUnified(): Promise<Processor>;
<file_sep>let instance = null;
async function importUnified() {
if (!instance) {
// Father forgive me for I have sinned
// It's debatable whether this server can be distributed
// as an ESM module. Needs more time.
// This is a hack to import a Pure ESM module into a CommonJS package.
const { processor } = await import('processor');
return (instance = processor);
}
return instance;
}
exports.importUnified = importUnified;
<file_sep>import type {Plugin} from 'unified';
import type {Root} from 'nlcst';
export default function longSentences(): Plugin<void[], Root, string> {
return (tree: any, file: any) => {
console.log(tree);
return;
};
}
<file_sep>import retextEnglish from 'retext-english';
import retextPassive from 'retext-passive';
import retextStringify from 'retext-stringify';
import longSentences from './long-sentences.js';
import { unified } from 'unified';
export const processor = unified()
.use(retextEnglish)
.use(retextPassive)
.use(longSentences)
.use(retextStringify);
| 34bf3290008b26794320fd4e927134abb7a309a3 | [
"Markdown",
"TypeScript",
"JavaScript"
] | 5 | Markdown | iddl/hemingway-vscode | d996a7f8c3c36d579f62383febe9457b5c1c6262 | fcce76b5bb360a9a4bd48c3b1375f05f11f5c890 | |
refs/heads/master | <repo_name>terngkub/Frozen<file_sep>/simple_server.go
package main
import (
"errors"
"fmt"
"log"
"net"
"os"
"regexp"
"strings"
)
const (
CONN_HOST = "localhost"
CONN_PORT = "3333"
CONN_TYPE = "tcp"
)
type Account struct {
Password string
User string
Nickname string
}
type Channel struct {
Name string
Topic string
Key string
AdminList []*Account
UserList []*Account
BanList []*Account
UserMap map[string]*Account
}
type Env struct {
ChannelList []*Channel
AccountList []*Account
UserMap map[string]*Account
NicknameMap map[string]*Account
ConnMap map[string]net.Conn
ChannelMap map[string]*Channel
}
type Session struct {
Env *Env
Conn net.Conn
Account *Account
}
func main() {
ln, err := net.Listen(CONN_TYPE, CONN_HOST+":"+CONN_PORT)
if err != nil {
fmt.Println("Error listening :", err.Error())
os.Exit(1)
}
defer ln.Close()
env := Env{AccountList: []*Account{},
ChannelList: []*Channel{},
UserMap: make(map[string]*Account),
NicknameMap: make(map[string]*Account),
ConnMap: make(map[string]net.Conn),
ChannelMap: make(map[string]*Channel)}
fmt.Println("Listening on ", CONN_HOST+":"+CONN_PORT)
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error accepting ", err.Error())
continue
}
log.Println("accept connection", conn)
go runSession(&env, conn)
}
}
func runSession(env *Env, conn net.Conn) {
session := Session{Env: env, Conn: conn, Account: nil}
defer session.closeConnection()
if !session.authorize() {
return
}
defer session.disconnect()
log.Println("ConnMap", session.Env.ConnMap)
for {
request, err := session.getRequest()
if err != nil {
break
}
session.handleRequest(request)
}
}
func (session *Session) closeConnection() {
log.Println("close session", session.Conn)
session.Conn.Close()
}
func (session *Session) disconnect() {
log.Println("disconnect", session.Account.Nickname)
delete(session.Env.ConnMap, session.Account.Nickname)
}
func (session *Session) handleRequest(request string) {
switch {
case regexp.MustCompile(`^(:(.+) +)?NICK`).MatchString(request):
session.changeNickname(request)
case strings.HasPrefix(request, "PRIVMSG "):
session.privateMSG(request)
case strings.Contains(request, "JOIN"):
session.joinChan(request)
case strings.Contains(request, "PART"):
session.leaveChan(request)
case request == "NAMES":
session.cmdNAMES()
case request == "LIST":
session.cmdLIST()
}
}
func (session *Session) getRequest() (string, error) {
request := make([]byte, 1024)
len, err := session.Conn.Read(request)
if err != nil {
log.Println("Error reading: ", err)
return "", err
}
if request[len-2] != '\r' || request[len-1] != '\n' {
return "", errors.New("no CRLF")
}
requestStr := string(request[:len-2])
fmt.Println("<" + requestStr + ">")
return requestStr, nil
}
func (session *Session) cmdNAMES() {
list := make([]string, len(session.Env.ConnMap))
for key := range session.Env.ConnMap {
list = append(list, key)
}
message := fmt.Sprintf("%s\r\n", list)
session.Conn.Write([]byte(message))
}
func (session *Session) cmdLIST() {
list := make([]string, len(session.Env.ChannelMap))
for key := range session.Env.ChannelMap {
list = append(list, key)
}
message := fmt.Sprintf("%s\r\n", list)
session.Conn.Write([]byte(message))
}
<file_sep>/go.mod
module frozen
go 1.12
<file_sep>/validation.go
package main
import "regexp"
func isValidNickname(nick string) bool {
r := regexp.MustCompile(`^[a-zA-Z0-9\-\[\]\\\x60\^\{\}]{1,8}$`)
match := r.MatchString(nick)
if match {
return true
}
return false
}
func isValidUser(user string) bool {
r := regexp.MustCompile(`[^\x20\x0\xd\xa]+`)
match := r.MatchString(user)
if match {
return true
}
return false
}
<file_sep>/validation_test.go
package main
import "testing"
func TestNickname(t *testing.T) {
t.Run("valid_00", nicknameAlpha)
t.Run("valid_01", nicknameNumber)
t.Run("valid_02", nicknameSymbol)
t.Run("valid_03", nicknameCombine)
t.Run("fail_00", nicknameTooLong)
t.Run("fail_01", nicknameForbidden)
}
func nicknameAlpha(t *testing.T) {
nick := "Nick"
if !isValidNickname(nick) {
t.Errorf("'%s' should be valid", nick)
}
}
func nicknameNumber(t *testing.T) {
nick := "0123"
if !isValidNickname(nick) {
t.Errorf("'%s' should be valid", nick)
}
}
func nicknameSymbol(t *testing.T) {
nick := "-[]\\`^{}"
if !isValidNickname(nick) {
t.Errorf("'%s' should be valid", nick)
}
}
func nicknameCombine(t *testing.T) {
nick := "[N0]{n\\}"
if !isValidNickname(nick) {
t.Errorf("'%s' should be valid", nick)
}
}
func nicknameTooLong(t *testing.T) {
nick := "ThisIsMyNickName"
if isValidNickname(nick) {
t.Errorf("'%s' shouldn't be valid", nick)
}
}
func nicknameForbidden(t *testing.T) {
nick := "OMG!!!"
if isValidNickname(nick) {
t.Errorf("'%s' shouldn't be valid", nick)
}
}
<file_sep>/authorize.go
package main
import (
"log"
"strings"
)
func (session *Session) getRequests() ([]string, bool) {
request := make([]byte, 512)
len, err := session.Conn.Read(request)
if err != nil {
log.Println("error reading:", err)
return []string{}, false
}
log.Printf("receive: '%s'", request)
str := string(request[:len])
if str[len-2] != '\r' || str[len-1] != '\n' {
log.Println("error: request doesn't end with \\r\\n")
return []string{}, true
}
trimmed := strings.Trim(str, "\r\n")
splitted := strings.Split(trimmed, "\r\n")
return splitted, true
}
func (session *Session) authorize() bool {
account, ok := session.getAccountData()
if !ok {
return false
}
if oldAccount, ok := session.Env.UserMap[account.User]; ok {
return session.login(account, oldAccount)
}
return session.register(account)
}
func (session *Session) getAccountData() (*Account, bool) {
account := Account{}
for !account.isComplete() {
requests, ok := session.getRequests()
if !ok {
return nil, false
}
for _, request := range requests {
switch {
case strings.HasPrefix(request, "PASS"):
if newPass := session.cmdPASS(request); newPass != "" {
account.Password = newPass
}
case strings.HasPrefix(request, "NICK"):
if newNick := session.cmdNICK(request); newNick != "" {
account.Nickname = newNick
}
case strings.HasPrefix(request, "USER"):
if newUser := session.cmdUSER(request); newUser != "" {
account.User = newUser
if account.Password != "" {
if _, ok := session.Env.UserMap[account.User]; ok {
return &account, true
}
}
}
default:
session.error451()
continue
}
if account.isComplete() {
break
}
}
}
return &account, true
}
func (account *Account) isComplete() bool {
if account.Password != "" && account.Nickname != "" && account.User != "" {
return true
}
return false
}
func (session *Session) cmdPASS(request string) string {
if session.Account != nil {
session.error462()
return ""
}
matches := doRegexpSubmatch("^PASS +(.+)$", request)
if len(matches) != 2 {
session.error461("PASS")
return ""
}
log.Println("parse PASS:", matches[1])
return matches[1]
}
func (session *Session) cmdNICK(request string) string {
matches := doRegexpSubmatch("^NICK +(.+?)(?: +(?:.+)){0,1}$", request)
if len(matches) != 2 {
session.error431()
return ""
}
if !isValidNickname(matches[1]) {
session.error432(matches[1])
return ""
}
log.Println("parse NICK:", matches[1])
return matches[1]
}
func (session *Session) cmdUSER(request string) string {
if session.Account != nil {
session.error462()
return ""
}
matches := doRegexpSubmatch("^USER +(.+) +.+ +.+ +:.+$", request)
if len(matches) != 2 {
session.error461("USER")
return ""
}
log.Println("parse USER:", matches[1])
return matches[1]
}
func (session *Session) login(newAccount *Account, oldAccount *Account) bool {
log.Println("attemp to login", session.Conn)
if newAccount.Password != oldAccount.Password {
session.error464()
return false
}
session.Account = oldAccount
session.Env.ConnMap[oldAccount.Nickname] = session.Conn
log.Println("login success", session.Conn)
session.welcome()
return true
}
func (session *Session) register(account *Account) bool {
log.Println("attemp to register", session.Conn)
if _, isDuplicated := session.Env.NicknameMap[account.Nickname]; isDuplicated {
session.error434(account.Nickname)
return false
}
session.Env.AccountList = append(session.Env.AccountList, account)
length := len(session.Env.AccountList)
last := &session.Env.AccountList[length-1]
session.Account = *last
session.Env.UserMap[account.User] = *last
session.Env.NicknameMap[account.Nickname] = *last
session.Env.ConnMap[account.Nickname] = session.Conn
log.Println("register success", session.Conn)
session.welcome()
return true
}
func (session *Session) changeNickname(request string) {
matches := doRegexpSubmatch("^(?::(?:.+) +)?NICK +(.+)$", request)
if len(matches) != 2 {
session.error431()
return
}
if !isValidNickname(matches[1]) {
session.error432(matches[1])
return
}
if _, isDuplicated := session.Env.NicknameMap[matches[1]]; isDuplicated {
session.error433(matches[1])
return
}
session.Env.NicknameMap[matches[1]] = session.Account
session.Env.ConnMap[matches[1]] = session.Conn
delete(session.Env.NicknameMap, session.Account.Nickname)
delete(session.Env.ConnMap, session.Account.Nickname)
oldNickname := session.Account.Nickname
session.Account.Nickname = matches[1]
log.Printf("change nickname from %s to %s\n", oldNickname, session.Account.Nickname)
}
<file_sep>/utils.go
package main
import "regexp"
func doRegexpSubmatch(format, str string) []string {
r := regexp.MustCompile(format)
matches := r.FindStringSubmatch(str)
return matches
}
func remove_user(s []*Account, i int) []*Account {
if len(s) <= 1 {
return nil
}
s[len(s)-1], s[i] = s[i], s[len(s)-1]
return s[:len(s)-1]
}
func remove_chan(s []*Channel, i int) []*Channel {
if len(s) <= 1 {
return nil
}
s[len(s)-1], s[i] = s[i], s[len(s)-1]
return s[:len(s)-1]
}
<file_sep>/messaging.go
package main
import (
"fmt"
"strings"
)
func (session *Session) privateMSG(request string) {
matches := doRegexpSubmatch("^PRIVMSG +(.+?) +:(.+)$", request)
if len(matches) != 3 {
session.error461("PRIVMSG")
return
}
msg := fmt.Sprintf(":%s!%s@%s PRIVMSG %s :%s\r\n",
session.Account.Nickname,
session.Account.User,
CONN_HOST,
matches[1],
matches[2])
if matches[1][0] == '#' || matches[1][0] == '&' {
if channel, ok := session.Env.ChannelMap[matches[1]]; ok {
for _, account := range channel.UserList {
if account.Nickname != session.Account.Nickname {
dstConn := session.Env.ConnMap[account.Nickname]
dstConn.Write([]byte(msg))
}
}
} else {
session.error401(matches[1])
}
} else {
if account, ok := session.Env.NicknameMap[matches[1]]; ok {
dstConn := session.Env.ConnMap[account.Nickname]
dstConn.Write([]byte(msg))
} else {
session.error401(matches[1])
}
}
}
func (session *Session) joinChan(request string) {
src_user := session.Account
var req_keys []string
sp_matches := strings.Split(request, " ")
// grab channels and keys from request
if len(sp_matches) >= 2 {
req_chans := strings.Split(sp_matches[1], ",")
if len(sp_matches) >= 3 {
req_keys = strings.Split(sp_matches[2], ",")
}
for i, req_chan := range req_chans {
channel, ok := session.Env.ChannelMap[req_chan]
if ok == true {
if is_banned(src_user, *channel) == false {
// check key
session.checkChan(channel, req_keys, i)
}
} else if len(req_keys) > i && len(req_keys[i]) > 0 {
session.createChannel(req_chans[i], "", req_keys[i])
} else {
session.createChannel(req_chans[i], "", "")
}
}
} else {
session.error461(request)
}
}
func (session *Session) checkChan(channel *Channel, req_keys []string, idx int) {
if channel.Key != "" {
if len(req_keys) > idx && len(req_keys[idx]) > 0 {
if req_keys[idx] == channel.Key {
session.append_user(channel)
}
}
} else {
session.append_user(channel)
}
//TODO message if banned
}
func is_banned(user *Account, channel Channel) bool {
for _, banned := range channel.BanList {
if user.Nickname == banned.Nickname {
return true
}
}
return false
}
func (session *Session) createChannel(name string, topic string, key string) {
new_chan := Channel{
Name: name,
Topic: topic,
Key: key,
AdminList: []*Account{session.Account},
UserList: []*Account{},
BanList: []*Account{},
UserMap: make(map[string]*Account)}
session.Env.ChannelList = append(session.Env.ChannelList, &new_chan)
session.Env.ChannelMap[name] = &new_chan
session.append_user(&new_chan)
}
func (session *Session) append_user(channel *Channel) {
// add user to channel
src_user := session.Account
channel.UserList = append(channel.UserList, src_user)
channel.UserMap[src_user.Nickname] = src_user
// alert other users
for _, user := range channel.UserList {
alert_message := fmt.Sprintf("%s!%s@%s %s %s\r\n",
src_user.Nickname,
src_user.User,
CONN_HOST,
"JOIN",
channel.Name)
session.Env.ConnMap[user.Nickname].Write([]byte(alert_message))
}
//send responses
topic_message := fmt.Sprintf(":%s!%s@%s %s %s %s :%s\r\n",
src_user.Nickname,
src_user.User,
CONN_HOST,
"332",
src_user.Nickname,
channel.Name,
channel.Topic)
session.Conn.Write([]byte(topic_message))
var users_list string
for _, user := range channel.UserList {
users_list += user.Nickname + " "
}
names_message := fmt.Sprintf(":%s!%s@%s %s %s = %s :%s\r\n",
src_user.Nickname,
src_user.User,
CONN_HOST,
"353",
src_user.Nickname,
channel.Name,
users_list)
session.Conn.Write([]byte(names_message))
end_names_message := fmt.Sprintf(":%s!%s@%s %s %s %s :%s\r\n",
src_user.Nickname,
src_user.User,
CONN_HOST,
"366",
src_user.Nickname,
channel.Name,
"End of NAMES list")
session.Conn.Write([]byte(end_names_message))
}
func (session *Session) leaveChan(request string) {
if len(request) > 5 {
src := session.Account
matches := doRegexpSubmatch("PART (.*) :(.*)", request)
if len(matches) > 0 {
// if channel/user exists
channel, ok1 := session.Env.ChannelMap[matches[1]]
if ok1 == true {
_, ok2 := channel.UserMap[src.Nickname]
if ok2 == true {
session.sendPart(request, src, channel)
}
}
}
}
}
func (session *Session) sendPart(request string, src *Account, channel *Channel) {
// send PART messages
i := strings.Index(request[1:], ":")
msg := fmt.Sprintf(":%s!%s@%s PART %s :%s\r\n",
src.Nickname,
src.User,
CONN_HOST,
channel.Name,
request[i+2:])
for _, user := range channel.UserList {
if user.Nickname != src.Nickname {
dst_conn := session.Env.ConnMap[user.Nickname]
dst_conn.Write([]byte(msg))
}
}
// leave chann
for i, user := range channel.UserList {
if user.Nickname == src.Nickname {
channel.UserList = remove_user(channel.UserList, i)
delete(channel.UserMap, user.Nickname)
}
}
// remove empty channel
if channel.UserList == nil {
for i, channel := range session.Env.ChannelList {
if channel.Name == channel.Name {
session.Env.ChannelList = remove_chan(session.Env.ChannelList, i)
delete(session.Env.ChannelMap, channel.Name)
}
}
}
}
<file_sep>/reply.go
package main
import (
"fmt"
"log"
)
func (session *Session) reply(message string) {
session.Conn.Write([]byte(message))
log.Printf("reply: '%s'", message)
}
func (session *Session) welcome() {
message := fmt.Sprintf(":%s 001 %s :Welcome to the Internet Relay Network\r\n", CONN_HOST, session.Account.Nickname)
session.reply(message)
}
func (session *Session) error401(name string) {
message := fmt.Sprintf(":%s 401 %s :No such nick/channel\r\n", CONN_HOST, name)
session.reply(message)
}
func (session *Session) error431() {
message := fmt.Sprintf(":%s 431 :No nickname is given\r\n", CONN_HOST)
session.reply(message)
}
func (session *Session) error432(nick string) {
message := fmt.Sprintf(":%s 432 %s :Erroneus nickname\r\n", CONN_HOST, nick)
session.reply(message)
}
func (session *Session) error433(nick string) {
message := fmt.Sprintf(":%s 433 * %s :Nickname collision KILL\r\n", CONN_HOST, nick)
session.reply(message)
}
func (session *Session) error434(nick string) {
message := fmt.Sprintf(":%s 434 * %s :Nickname is already in use\r\n", CONN_HOST, nick)
session.reply(message)
}
// Authorization
func (session *Session) error451() {
message := fmt.Sprintf(":%s 451 :You have not registered\r\n", CONN_HOST)
session.reply(message)
}
func (session *Session) error461(command string) {
message := fmt.Sprintf(":%s 461 %s :Not enough parameters\r\n", CONN_HOST, command)
session.reply(message)
}
func (session *Session) error462() {
message := fmt.Sprintf(":%s 462 :You may not reregister\r\n", CONN_HOST)
session.reply(message)
}
func (session *Session) error464() {
message := fmt.Sprintf(":%s 464 :Password incorrect\r\n", CONN_HOST)
session.reply(message)
}
| 6b51aa93793a305d1b52ed7898d99504957af6f2 | [
"Go Module",
"Go"
] | 8 | Go | terngkub/Frozen | 831749803a34e1dbd5d59b45bc623608ec5812c5 | c56c7594977721d32a434057440107544664f7d8 | |
refs/heads/master | <file_sep>#!/bin/bash
### https://github.com/adnanjee/hyperledger-fabric.git ###
### Download golang ###
echo "Downloading golang"
curl -O https://dl.google.com/go/go1.14.2.linux-amd64.tar.gz
tar xvf go1.14.2.linux-amd64.tar.gz
### Moving go to /usr/local ###
sudo mv go /usr/local
rm go1.14.2.linux-amd64.tar.gz
# If GOROOT already set then DO Not set it again
if [ -z $GOROOT ]
then
echo "export GOROOT=/usr/local/go" >> ~/.profile
echo "export PATH=$PATH:/usr/local/go/bin" >> ~/.profile
echo "export GOPATH=/home/$USER/gopath" >> ~/.profile
echo "### Updated .profile with GOROOT/GOPATH/PATH ###"
echo "export GOROOT=/usr/local/go" >> ~/.bashrc
echo "export GOPATH=/home/$USER/gopath" >> ~/.bashrc
echo "### Updated .profile with GOROOT/GOPATH/PATH ###"
else
echo "### No Change made to .profile ###"
fi
. ~/.profile
. ~/.bashrc
echo "### Done ###"
<file_sep>#!/bin/bash
### https://github.com/adnanjee/hyperledger-fabric.git ###
export PATH=$PATH:$GOROOT/bin
. ~/.profile
. ~/.bashrc
echo "GOPATH=$GOPATH"
echo "GOROOT=$GOROOT"
echo "### Starting to Download Fabric ###"
curl -sSL https://bit.ly/2ysbOFE | bash -s -- 2.0.1 1.4.6 0.4.18
echo "### Copy the binaries from fabric-samples/bin to /usr/local/bin ###"
sudo cp fabric-samples/bin/* /usr/local/bin
echo "### Copy the binaries from fabric-samples/bin to bin folder for future use ###"
mkdir -p ${PWD}/../bin
cp fabric-samples/bin/* ${PWD}/../bin
# The sample chaincode is under the subfolder go and need to come under gopath/src subfolder
echo "### Setting up the src folder under $GOPATH /gopath/src ###"
mkdir -p $GOPATH/src
echo "### copying chaincodes from fabric-samples folder in gopath/src folder ###"
cp -r fabric-samples/chaincode/chaincode_example02/* $GOPATH/src
# Move fabric-samples to hyperledger-1.3.0 directory
mv fabric-samples ${PWD}/../
# This downloads the shim code
echo "### Setting up the HLF Shim ###"
mkdir -p $GOPATH/src/github.com/hyperledger
go get -u --tags nopkcs11 github.com/hyperledger/fabric/core/chaincode/shim
. ~/.profile
. ~/.bashrc
echo "### Installaion is completed ###"
<file_sep>### https://github.com/adnanjee/hyperledger-fabric-1.4.git ###
### Installing Development Environment ###
echo "Installing Composer Cli Tools"
npm install -g [email protected]
echo "Installing Composer REST Server"
npm install -g [email protected]
echo "Installing Utility for Generating Application Assets"
npm install -g [email protected]
echo "Installing Yeoman"
npm install -g yo
echo "Installing Composer Playground"
npm install -g [email protected]
. ~/.profile
. ~/.bashrc
echo "Installaions Done"
<file_sep>#!/bin/bash
### https://github.com/adnanjee/hyperledger-fabric-1.4.git ###
# Installs the JQ Utility
sudo apt-get install -y jq
| c302be77b1dc884b7c115cbcbd40206d0c5abe5e | [
"Shell"
] | 4 | Shell | adnanjee/hyperledger-fabric-1.4 | 4ecd4a4e67c03138125077018209c34c1a62675a | 6ac1f10e6cad6b672f64c582386ba0f3f5e8c9ff | |
refs/heads/master | <file_sep>import Cocoa
class AppDelegate: NSObject, NSApplicationDelegate {
private var context: Context!
private var statusBarHandler: StatusBarHandler!
func applicationDidFinishLaunching(_ aNotification: Notification) {
self.context = Context()
self.statusBarHandler = StatusBarHandler(context: context)
}
}
<file_sep>import Cocoa
final class StatusBarHandler {
private static let updateInterval: TimeInterval = 60
private let statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
private let popover = NSPopover()
private let context: Context
private var temperatureTimer: Timer!
init(context: Context) {
self.context = context
setupStatusBarButton()
setupPopover()
scheduleUpdate()
}
}
// MARK: - Setup
private extension StatusBarHandler {
func setupStatusBarButton() {
if let button = statusItem.button {
button.target = self
button.action = #selector(togglePopover(sender:))
}
}
func setupPopover() {
popover.contentViewController = WeatherViewController.create()
popover.behavior = .transient
}
func scheduleUpdate() {
temperatureTimer = Timer.scheduledTimer(
withTimeInterval: StatusBarHandler.updateInterval, repeats: true
) { [weak self] _ in
self?.context.weatherService.getTemperature { result in
DispatchQueue.main.async {
switch result {
case .success(let temperature):
self?.statusItem.button?.title = temperature
case .failure(let error):
self?.statusItem.button?.title = "-"
print(error.localizedDescription)
}
}
}
}
temperatureTimer.fire()
}
}
// MARK: - Popover actions
private extension StatusBarHandler {
@objc func togglePopover(sender: Any?) {
if popover.isShown {
closePopover(sender: sender)
} else {
showPopover()
}
}
func showPopover() {
if let button = statusItem.button {
popover.show(relativeTo: button.bounds, of: button, preferredEdge: .minY)
}
}
func closePopover(sender: Any?) {
popover.performClose(sender)
}
}
<file_sep>import Foundation
enum WeatherServiceError: Error {
case emptyResponse
case incorrectResponse
}
// MARK: - LocalizedError implementation
extension WeatherServiceError: LocalizedError {
var errorDescription: String? {
switch self {
case .emptyResponse:
return "Server returned empty response"
case .incorrectResponse:
return "Response couldn't be parsed"
}
}
}
<file_sep>import Cocoa
import WebKit
final class WeatherViewController: NSViewController {
@IBOutlet private var webView: WKWebView!
private lazy var pageTransformer = WeatherViewController.loadTransformationCode()
}
// MARK: - Lifecycle
extension WeatherViewController {
override func viewWillAppear() {
super.viewWillAppear()
loadPage()
}
}
// MARK: - Fabric method
extension WeatherViewController {
class func create() -> WeatherViewController {
let storyboard = NSStoryboard(name: "WeatherViewController", bundle: nil)
let identifier = "WeatherViewController"
guard let weatherVC = storyboard.instantiateController(withIdentifier: identifier) as? WeatherViewController else {
fatalError()
}
NSLayoutConstraint.activate([
weatherVC.view.heightAnchor.constraint(equalToConstant: 550),
weatherVC.view.widthAnchor.constraint(equalToConstant: 550)
])
return weatherVC
}
}
// MARK: - WKNavigationDelegate implementation
extension WeatherViewController: WKNavigationDelegate {
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
transformPage()
}
}
// MARK: - Javascript helpers
private extension WeatherViewController {
func loadPage() {
let url = URL(string: "http://weather.nsu.ru")!
webView.load(URLRequest(url: url))
}
func transformPage() {
webView.evaluateJavaScript(pageTransformer) { (_, error) in
error.flatMap { print($0) }
}
}
}
// MARK: - Load transforming code
private extension WeatherViewController {
class func loadTransformationCode() -> String {
guard let path = Bundle.main.url(forResource: "WeatherTransform", withExtension: "js") else {
fatalError("Couldn't find WeatherTransform.js")
}
guard let jsCode = try? String(contentsOf: path) else {
fatalError("Couldn't read WeatherTransform.js")
}
return jsCode
}
}
<file_sep>import Foundation
final class WeatherService {
private static let url = URL(string: "http://weather.nsu.ru/loadata.php")!
private let urlSession = URLSession.shared
}
// MARK: - getTemperature method
extension WeatherService {
func getTemperature(completion: @escaping (Result<String, Error>) -> ()) {
let task = urlSession.dataTask(with: WeatherService.url) { data, response, error in
if let error = error {
completion(.failure(error))
}
guard let data = data, let string = String(data: data, encoding: .utf8) else {
completion(.failure(WeatherServiceError.emptyResponse))
return
}
guard let jsRange = string.range(of: "cnv.innerHTML = '") else {
completion(.failure(WeatherServiceError.incorrectResponse))
return
}
let beginTemperature = jsRange.upperBound
guard let endTemperature = string.nextOccurance(of: "'", afterIndex: beginTemperature) else {
completion(.failure(WeatherServiceError.incorrectResponse))
return
}
let result = string[beginTemperature..<endTemperature]
completion(.success(String(result).withReplacedDegreeSymbol))
}
task.resume()
}
}
// MARK: - String helpers
private extension String {
func nextOccurance(of character: Character, afterIndex: String.Index) -> String.Index? {
return suffix(from: afterIndex).firstIndex(of: character)
}
var withReplacedDegreeSymbol: String {
return replacingOccurrences(of: "°", with: "°")
}
}
<file_sep>import Foundation
final class Context {
let weatherService: WeatherService
init() {
self.weatherService = WeatherService()
}
}
<file_sep>document.getElementsByTagName("small")[0].innerHTML = ""
document.getElementsByTagName("p")[0].innerHTML = ""
document.getElementsByTagName("h1")[0].setAttribute("style", "margin-top: -25px;")
document.getElementsByTagName("body")[0].setAttribute("style", "transform: scale(0.9, 0.9);")
| 15bcd5bb8252e4bef6b68588ccc19f8053d340e4 | [
"Swift",
"JavaScript"
] | 7 | Swift | vmistyurin/NSUWeather | b9f7adf0db410630b5a977deffac6f2271bd6e3b | 3402d4cd1a5775871298e790b2f3f89c753c791c | |
refs/heads/main | <repo_name>rkrishn7/couchsync-website<file_sep>/src/assets/images.ts
class Images {
private get base() {
return '';
}
get logo() {
return this.base + '/couchsync-128.png';
}
get appScreenshot() {
return this.base + '/app-screenshot.png';
}
get favicon() {
return this.base + '/favicon.ico';
}
};
export default new Images();
| d8d78df5fccfe592c1dacda5ea9e8255341af8e8 | [
"TypeScript"
] | 1 | TypeScript | rkrishn7/couchsync-website | abb6dd46e4458bf4d56d95d8e682647066ea68cf | 58c3ef1fea5e0034274461925532a9138638132c | |
refs/heads/master | <repo_name>Kazuki-AK/IKS_SHOP<file_sep>/UserLogin/forms.py
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import ( AuthenticationForm, UserCreationForm, PasswordChangeForm, PasswordResetForm, SetPasswordForm )
from .models import Shop
User = get_user_model()
class LoginForm(AuthenticationForm):
"""ログインフォーム"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
field.widget.attrs['placeholder'] = field.label # placeholderにフィールドのラベルを入れる
class UserUpdateForm(forms.ModelForm):
"""ユーザー情報更新フォーム"""
class Meta:
model = User
fields = ('email',
'last_name_representative', 'first_name_representative', 'last_name_representative_kana', 'first_name_representative_kana',
'last_name_manager', 'first_name_manager', 'last_name_manager_kana', 'first_name_manager_kana',
'tel', 'remarks',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
class ShopUpdateForm(forms.ModelForm):
"""ショップ情報更新フォーム"""
class Meta:
model = Shop
fields = ( 'shop_name', 'manager_name', 'email','tel_shop', 'website',
'zip_code', 'address1', 'address2', 'address3', 'address4', 'address5',
'station1', 'station1_time', 'station2', 'station2_time', 'station3', 'station3_time',
'price_basic', 'wheelchair', 'visually', 'hearing',
'remarks_shop', )
widgets = {
'zip_code':
forms.TextInput(
#attrsでp-postal-codeを指定
attrs={'class': 'p-postal-code','placeholder': '記入例:8900053',},
),
'address1': forms.TextInput(
#attrsでp-region/p-region-idを指定
#attrs={'class': 'p-region','placeholder': '記入例:鹿児島県'},
attrs={'class': 'p-region-id','placeholder': '記入例:鹿児島県'},
),
'address2': forms.TextInput(
#attrsでp-locality p-street-address p-extended-addressを指定
attrs={'class': 'p-locality', 'placeholder': '記入例:鹿児島市'},
),
'address3': forms.TextInput(
#attrsでp-locality p-street-address p-extended-addressを指定
attrs={'class': 'p-street-address', 'placeholder': '記入例:中央町10丁目'},
),
'address4': forms.TextInput(
#attrsでp-locality p-street-address p-extended-addressを指定
attrs={'class': 'p-extended-address', 'placeholder': '記入例:33-4'},
),
'address5': forms.TextInput(
attrs={'class': '','placeholder': '記入例:トリマビル'},
),
}
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
self.fields['zip_code'].widget.attrs['class'] = 'form-control p-postal-code'
self.fields['address1'].widget.attrs['class'] = 'form-control p-region'
self.fields['address2'].widget.attrs['class'] = 'form-control p-locality'
self.fields['address3'].widget.attrs['class'] = 'form-control p-street-address'
self.fields['address4'].widget.attrs['class'] = 'form-control p-extended-address'
class TimeUpdateForm(forms.ModelForm):
"""ユーザー情報更新フォーム"""
class Meta:
model = Shop
fields = ('is_holiday_sunday', 'is_holiday_monday', 'is_holiday_tuesday', 'is_holiday_wednesday', 'is_holiday_thursday', 'is_holiday_friday', 'is_holiday_saturday',
'time_open_sunday1', 'time_close_sunday1', 'time_open_sunday2', 'time_close_sunday2',
'time_open_monday1', 'time_close_monday1', 'time_open_monday2', 'time_close_monday2',
'time_open_tuesday1', 'time_close_tuesday1', 'time_open_tuesday2', 'time_close_tuesday2',
'time_open_wednesday1', 'time_close_wednesday1', 'time_open_wednesday2', 'time_close_wednesday2',
'time_open_thursday1', 'time_close_thursday1', 'time_open_thursday2', 'time_close_thursday2',
'time_open_friday1', 'time_close_friday1', 'time_open_friday2', 'time_close_friday2',
'time_open_saturday1', 'time_close_saturday1', 'time_open_saturday2', 'time_close_saturday2', )
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
self.fields['time_open_sunday1'].widget.attrs['class'] = 'form-control sunday'
self.fields['time_close_sunday1'].widget.attrs['class'] = 'form-control sunday'
self.fields['time_open_sunday2'].widget.attrs['class'] = 'form-control sunday'
self.fields['time_close_sunday2'].widget.attrs['class'] = 'form-control sunday'
self.fields['time_open_monday1'].widget.attrs['class'] = 'form-control monday'
self.fields['time_close_monday1'].widget.attrs['class'] = 'form-control monday'
self.fields['time_open_monday2'].widget.attrs['class'] = 'form-control monday'
self.fields['time_close_monday2'].widget.attrs['class'] = 'form-control monday'
self.fields['time_open_tuesday1'].widget.attrs['class'] = 'form-control tuesday'
self.fields['time_close_tuesday1'].widget.attrs['class'] = 'form-control tuesday'
self.fields['time_open_tuesday2'].widget.attrs['class'] = 'form-control tuesday'
self.fields['time_close_tuesday2'].widget.attrs['class'] = 'form-control tuesday'
self.fields['time_open_wednesday1'].widget.attrs['class'] = 'form-control wednesday'
self.fields['time_close_wednesday1'].widget.attrs['class'] = 'form-control wednesday'
self.fields['time_open_wednesday2'].widget.attrs['class'] = 'form-control wednesday'
self.fields['time_close_wednesday2'].widget.attrs['class'] = 'form-control wednesday'
self.fields['time_open_thursday1'].widget.attrs['class'] = 'form-control thursday'
self.fields['time_close_thursday1'].widget.attrs['class'] = 'form-control thursday'
self.fields['time_open_thursday2'].widget.attrs['class'] = 'form-control thursday'
self.fields['time_close_thursday2'].widget.attrs['class'] = 'form-control thursday'
self.fields['time_open_friday1'].widget.attrs['class'] = 'form-control friday'
self.fields['time_close_friday1'].widget.attrs['class'] = 'form-control friday'
self.fields['time_open_friday2'].widget.attrs['class'] = 'form-control friday'
self.fields['time_close_friday2'].widget.attrs['class'] = 'form-control friday'
self.fields['time_open_saturday1'].widget.attrs['class'] = 'form-control saturday'
self.fields['time_close_saturday1'].widget.attrs['class'] = 'form-control saturday'
self.fields['time_open_saturday2'].widget.attrs['class'] = 'form-control saturday'
self.fields['time_close_saturday2'].widget.attrs['class'] = 'form-control saturday'
class UserCreateForm(UserCreationForm):
"""ユーザー登録用フォーム"""
class Meta:
model = User
fields = ('email',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
def clean_email(self):
email = self.cleaned_data['email']
User.objects.filter(email=email, is_active=False).delete()
return email
class MyPasswordChangeForm(PasswordChangeForm):
"""パスワード変更フォーム"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
class MyPasswordResetForm(PasswordResetForm):
"""パスワード忘れたときのフォーム"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
class MySetPasswordForm(SetPasswordForm):
"""パスワード再設定用フォーム(パスワード忘れて再設定)"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
class EmailChangeForm(forms.ModelForm):
"""メールアドレス変更フォーム"""
class Meta:
model = User
fields = ('email',)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields.values():
field.widget.attrs['class'] = 'form-control'
def clean_email(self):
email = self.cleaned_data['email']
User.objects.filter(email=email, is_active=False).delete()
return email<file_sep>/UserLogin/urls.py
from django.urls import path
from django.conf.urls import include, url
from django.contrib.auth import views as auth_views
from . import views
app_name = 'UserLogin'
urlpatterns = [
path('', views.Top.as_view(), name='top'),
path('login/', views.Login.as_view(), name='login'),
path('logout/', views.Logout.as_view(), name='logout'),
path('user_detail/<int:pk>/', views.UserDetail.as_view(), name='user_detail'),
path('user_update/<int:pk>/', views.UserUpdate.as_view(), name='user_update'),
path('shop_detail/<int:pk>/', views.ShopDetail.as_view(), name='shop_detail'),
path('shop_update/<int:pk>/', views.ShopUpdate.as_view(), name='shop_update'),
path('time_detail/<int:pk>/', views.TimeDetail.as_view(), name='time_detail'),
path('time_update/<int:pk>/', views.TimeUpdate.as_view(), name='time_update'),
path('user_create/', views.UserCreate.as_view(), name='user_create'),
path('user_create/done', views.UserCreateDone.as_view(), name='user_create_done'),
path('user_create/complete/<token>/', views.UserCreateComplete.as_view(), name='user_create_complete'),
path('password_change/', views.PasswordChange.as_view(), name='password_change'),
path('password_change/done/', views.PasswordChangeDone.as_view(), name='password_change_done'),
path('password_reset/', views.PasswordReset.as_view(), name='password_reset'),
path('password_reset/done/', views.PasswordResetDone.as_view(), name='password_reset_done'),
path('password_reset/confirm/<uidb64>/<token>/', views.PasswordResetConfirm.as_view(), name='password_reset_confirm'),
path('password_reset/complete/', views.PasswordResetComplete.as_view(), name='password_reset_complete'),
path('email/change/', views.EmailChange.as_view(), name='email_change'),
path('email/change/done/', views.EmailChangeDone.as_view(), name='email_change_done'),
path('email/change/complete/<str:token>/', views.EmailChangeComplete.as_view(), name='email_change_complete'),
path('<int:pk>/', views.ShopPreView.as_view(), name='shop_preview'),
]<file_sep>/Shop/views.py
from django.shortcuts import render
from django.views.generic import TemplateView
from UserLogin.models import *
# Create your views here.
class ShopView(TemplateView):
template_name = 'shop/infomation.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
shop_id = self.request.user.shop_number
if Shop.objects.filter( pk = shop_id ).exists():
context['shop'] = Shop.objects.get( pk = shop_id )
else:
pass
else:
pass
return context<file_sep>/UserLogin/migrations/0001_initial.py
# Generated by Django 2.2.24 on 2021-07-16 15:59
import UserLogin.models
from django.conf import settings
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('shop_number', models.PositiveSmallIntegerField(default=0, verbose_name='店舗ID')),
('email', models.EmailField(max_length=255, unique=True, verbose_name='メールアドレス')),
('first_name_representative', models.CharField(blank=True, help_text='代表者の方の「名」', max_length=30, verbose_name='代表者「名」')),
('last_name_representative', models.CharField(blank=True, help_text='代表者の方の「姓」', max_length=30, verbose_name='代表者「姓」')),
('first_name_representative_kana', models.CharField(blank=True, help_text='代表者の方の「メイ」(フリガナ)', max_length=30, verbose_name='代表者「メイ」')),
('last_name_representative_kana', models.CharField(blank=True, help_text='代表者の方の「セイ」(フリガナ)', max_length=30, verbose_name='代表者「セイ」')),
('first_name_manager', models.CharField(blank=True, help_text='管理者の方の「名」', max_length=30, verbose_name='管理者「名」')),
('last_name_manager', models.CharField(blank=True, help_text='管理者の方の「姓」', max_length=30, verbose_name='管理者「姓」')),
('first_name_manager_kana', models.CharField(blank=True, help_text='管理者の方の「メイ」(フリガナ)', max_length=30, verbose_name='管理者「メイ」')),
('last_name_manager_kana', models.CharField(blank=True, help_text='管理者の方の「セイ」(フリガナ)', max_length=30, verbose_name='管理者「セイ」')),
('tel', models.CharField(blank=True, max_length=15, verbose_name='電話番号')),
('remarks', models.TextField(blank=True, max_length=150, verbose_name='備考')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.Group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.Permission', verbose_name='user permissions')),
],
options={
'verbose_name': '会員',
'verbose_name_plural': '会員',
},
managers=[
('objects', UserLogin.models.CustomUserManager()),
],
),
migrations.CreateModel(
name='Shop',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('shop_name', models.CharField(default='SHOP', max_length=20, verbose_name='店名')),
('shop_name_kana', models.CharField(default='ショップ', max_length=30, verbose_name='テンメイ')),
('manager_name', models.CharField(default='CHIEF', max_length=15, verbose_name='管理者')),
('email', models.EmailField(max_length=255, verbose_name='お客様用メールアドレス')),
('tel_shop', models.CharField(blank=True, max_length=15, verbose_name='電話番号')),
('website', models.CharField(default='http://www.', max_length=100, verbose_name='サイトURL')),
('zip_code', models.CharField(blank=True, max_length=8, verbose_name='郵便番号')),
('address1', models.CharField(blank=True, max_length=40, verbose_name='都道府県')),
('address2', models.CharField(blank=True, max_length=40, verbose_name='市区町村')),
('address3', models.CharField(blank=True, max_length=40, verbose_name='丁目')),
('address4', models.CharField(blank=True, max_length=40, verbose_name='番地以降')),
('address5', models.CharField(blank=True, max_length=40, verbose_name='建物名・部屋番号等')),
('station1', models.CharField(blank=True, max_length=15, verbose_name='付近の駅・バス停1')),
('station1_time', models.PositiveSmallIntegerField(default=0, verbose_name='駅・バス停1からの所要時間')),
('station2', models.CharField(blank=True, max_length=15, verbose_name='付近の駅・バス停2')),
('station2_time', models.PositiveSmallIntegerField(default=0, verbose_name='駅・バス停2からの所要時間')),
('station3', models.CharField(blank=True, max_length=15, verbose_name='付近の駅・バス停3')),
('station3_time', models.PositiveSmallIntegerField(default=0, verbose_name='駅・バス停3からの所要時間')),
('is_holiday_sunday', models.BooleanField(default='False', verbose_name='日曜日')),
('is_holiday_monday', models.BooleanField(default='False', verbose_name='月曜日')),
('is_holiday_tuesday', models.BooleanField(default='False', verbose_name='火曜日')),
('is_holiday_wednesday', models.BooleanField(default='False', verbose_name='水曜日')),
('is_holiday_thursday', models.BooleanField(default='False', verbose_name='木曜日')),
('is_holiday_friday', models.BooleanField(default='False', verbose_name='金曜日')),
('is_holiday_saturday', models.BooleanField(default='False', verbose_name='土曜日')),
('point', models.IntegerField(default=0, verbose_name='店舗ID')),
('remarks_shop', models.TextField(blank=True, max_length=150, verbose_name='備考')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('manager_account', models.ForeignKey(null=True, on_delete='models.DO_NOTHING', related_name='ManagerAccount', to=settings.AUTH_USER_MODEL, to_field='email', verbose_name='管理者アカウント')),
],
options={
'verbose_name': '店舗情報',
'verbose_name_plural': '店舗情報',
},
),
]
<file_sep>/templates/registration/shop_detail.html
{% extends "base.html" %}
{% block title %}
登録情報確認ページ
{% endblock %}
{% block content %}
<table class="table">
<tbody>
<tr>
<th>店名</th>
<td>{{ shop.shop_name }}</td>
</tr>
<tr>
<th>管理者</th>
<td>{{ shop.manager_name }}</td>
</tr>
<tr>
<th>お客様用メールアドレス</th>
<td>{{ shop.email }}</td>
</tr>
<tr>
<th>電話番号</th>
<td>{{ shop.tel_shop }}</td>
</tr>
<tr>
<th>サイトURL</th>
<td>{{ shop.website }}</td>
</tr>
<tr>
<th>郵便番号</th>
<td>{{ shop.zip_code }}</td>
</tr>
<tr>
<th>都道府県</th>
<td>{{ shop.address1 }}</td>
</tr>
<tr>
<th>市区町村</th>
<td>{{ shop.address2 }}</td>
</tr>
<tr>
<th>丁目</th>
<td>{{ shop.address3 }}</td>
</tr>
<tr>
<th>番地以降</th>
<td>{{ shop.address4 }}</td>
</tr>
<tr>
<th>建物名・部屋番号等</th>
<td>{{ shop.address5 }}</td>
</tr>
<tr>
<th>付近の駅・バス停1</th>
<td>{{ shop.station1 }}</td>
</tr>
<tr>
<th>駅・バス停1からの所要時間</th>
<td>{{ shop.station1_time }}</td>
</tr>
<tr>
<th>付近の駅・バス停2</th>
<td>{{ shop.station2 }}</td>
</tr>
<tr>
<th>駅・バス停2からの所要時間</th>
<td>{{ shop.station2_time }}</td>
</tr>
<tr>
<th>付近の駅・バス停3</th>
<td>{{ shop.station3 }}</td>
</tr>
<tr>
<th>駅・バス停3からの所要時間</th>
<td>{{ shop.station3_time }}</td>
</tr>
<tr>
<th>基本料金</th>
<td>{{ shop.price_basic }}</td>
</tr>
<tr>
<th>車イス対応</th>
<td>{{ shop.wheelchair }}</td>
</tr>
<tr>
<th>視覚障碍対応</th>
<td>{{ shop.visually }}</td>
</tr>
<tr>
<th>聴覚障碍対応</th>
<td>{{ shop.hearing }}</td>
</tr>
<tr>
<th>備考</th>
<td>{{ shop.remarks_shop }}</td>
</tr>
</tbody>
<tbody>
{% for field in form %}
<tr>
<th><label for="{{ field.id_for_label }}">{{ field.label }}</label></th>
<td>{{ field }} {{ field.errors }}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}<file_sep>/Shop/urls.py
from django.urls import path
from Shop.views import ShopView
app_name = 'Shop'
urlpatterns = [
path('<int:pk>/', ShopView.as_view(), name='shop_info'),
]<file_sep>/UserLogin/migrations/0007_auto_20210718_2353.py
# Generated by Django 2.2.24 on 2021-07-18 14:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UserLogin', '0006_auto_20210718_1346'),
]
operations = [
migrations.AddField(
model_name='shop',
name='hearing',
field=models.IntegerField(choices=[(0, ''), (1, '可'), (2, '応相談')], default=0, verbose_name='聴覚障碍対応'),
),
migrations.AddField(
model_name='shop',
name='price_basic',
field=models.PositiveSmallIntegerField(default=0, verbose_name='基本料金'),
),
migrations.AddField(
model_name='shop',
name='visually',
field=models.IntegerField(choices=[(0, ''), (1, '可'), (2, '応相談')], default=0, verbose_name='視覚障碍対応'),
),
migrations.AddField(
model_name='shop',
name='wheelchair',
field=models.IntegerField(choices=[(0, ''), (1, '可'), (2, '応相談')], default=0, verbose_name='車イス対応'),
),
]
<file_sep>/IKS_Beauty_Shop/__init__.py
"""
Package for IKS_Beauty_Shop.
"""
<file_sep>/UserLogin/migrations/0008_auto_20210719_2320.py
# Generated by Django 2.2.24 on 2021-07-19 14:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('UserLogin', '0007_auto_20210718_2353'),
]
operations = [
migrations.AlterField(
model_name='shop',
name='is_holiday_sunday',
field=models.BooleanField(default='False', help_text='sunday', verbose_name='日曜日'),
),
]
<file_sep>/Top/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import TemplateView
# Create your views here.
def top(request):
template_name = "top.html"
return render(request,template_name)<file_sep>/UserLogin/views.py
from django.conf import settings
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.contrib.auth.views import ( LoginView, LogoutView, PasswordChangeView, PasswordChangeDoneView, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView )
from django.contrib.sites.shortcuts import get_current_site
from django.core.signing import BadSignature, SignatureExpired, loads, dumps
from django.http import HttpResponse, HttpResponseBadRequest, Http404
from django.shortcuts import render, redirect, resolve_url
from django.template.loader import render_to_string
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic import TemplateView
from .forms import ( LoginForm, UserCreateForm, UserUpdateForm, ShopUpdateForm, TimeUpdateForm, MyPasswordChangeForm, MyPasswordResetForm, MySetPasswordForm, EmailChangeForm )
from .models import ( User, Shop )
# Create your views here.
User = get_user_model()
class Top(generic.TemplateView):
template_name = 'top.html'
def get_context_data(self, **kwargs):
# 継承元のメソッド呼び出し
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
shop_id = self.request.user.shop_number
if Shop.objects.filter( pk = shop_id ).exists():
context['shop'] = Shop.objects.get( pk = shop_id ).shop_name
else:
context['shop'] = '未登録'
else:
pass
return context
class Login(LoginView):
"""ログインページ"""
form_class = LoginForm
template_name = 'registration/login.html'
class Logout(LogoutView):
"""ログアウトページ"""
template_name = 'registration/logout.html'
class OnlyYouMixin(UserPassesTestMixin):
raise_exception = True
def test_func(self):
# 「ログイン中のユーザーのpkと、そのユーザー情報ページのpkが同じ」or「ログイン中のユーザーがスーパーユーザー」なら許可
user = self.request.user
return user.pk == self.kwargs['pk'] or user.is_superuser
class UserDetail(OnlyYouMixin, generic.DetailView):
model = User
template_name = 'registration/user_detail.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
shop_id = self.request.user.shop_number
if Shop.objects.filter( pk = shop_id ).exists():
context['shop'] = Shop.objects.get( pk = shop_id ).shop_name
else:
context['shop'] = '未登録'
else:
pass
return context
class UserUpdate(OnlyYouMixin, generic.UpdateView):
model = User
form_class = UserUpdateForm
template_name = 'registration/user_form.html'
def get_success_url(self):
return resolve_url('UserLogin:user_detail', pk=self.kwargs['pk'])
class ShopDetail(OnlyYouMixin, generic.DetailView):
model = Shop
template_name = 'registration/shop_detail.html'
class ShopUpdate(OnlyYouMixin, generic.UpdateView):
model = Shop
form_class = ShopUpdateForm
template_name = 'registration/shop_form.html'
def get_success_url(self):
return resolve_url('UserLogin:shop_detail', pk=self.kwargs['pk'])
class TimeDetail(OnlyYouMixin, generic.DetailView):
model = Shop
template_name = 'registration/time_detail.html'
class TimeUpdate(OnlyYouMixin, generic.UpdateView):
model = Shop
form_class = TimeUpdateForm
template_name = 'registration/time_form.html'
def get_success_url(self):
return resolve_url('UserLogin:time_detail', pk=self.kwargs['pk'])
class UserCreate(generic.CreateView):
"""ユーザー仮登録"""
template_name = 'registration/user_create.html'
form_class = UserCreateForm
def form_valid(self, form):
"""仮登録と本登録用メールの発行."""
# 仮登録と本登録の切り替えは、is_active属性を使うと簡単です。
# 退会処理も、is_activeをFalseにするだけにしておくと捗ります。
user = form.save(commit=False)
user.is_active = False
user.save()
# アクティベーションURLの送付
current_site = get_current_site(self.request)
domain = current_site.domain
context = {
'protocol': self.request.scheme,
'domain': domain,
'token': dumps(user.pk),
'user': user,
}
subject = render_to_string('registration/mail_template/create/subject.txt', context)
message = render_to_string('registration/mail_template/create/message.txt', context)
user.email_user(subject, message)
return redirect('UserLogin:user_create_done')
class UserCreateDone(generic.TemplateView):
"""ユーザー仮登録したよ"""
template_name = 'registration/user_create_done.html'
class UserCreateComplete(generic.TemplateView):
"""メール内URLアクセス後のユーザー本登録"""
template_name = 'registration/user_create_complete.html'
timeout_seconds = getattr(settings, 'ACTIVATION_TIMEOUT_SECONDS', 60*60*24) # デフォルトでは1日以内
def get(self, request, **kwargs):
"""tokenが正しければ本登録."""
token = kwargs.get('token')
try:
user_pk = loads(token, max_age=self.timeout_seconds)
# 期限切れ
except SignatureExpired:
return HttpResponseBadRequest()
# tokenが間違っている
except BadSignature:
return HttpResponseBadRequest()
# tokenは問題なし
else:
try:
user = User.objects.get(pk=user_pk)
except User.DoesNotExist:
return HttpResponseBadRequest()
else:
if not user.is_active:
# 問題なければ本登録とする
user.is_active = True
user.save()
login(request, user, backend='django.contrib.auth.backends.ModelBackend') #登録後にそのままログインする場合の処理
return super().get(request, **kwargs)
return HttpResponseBadRequest()
class PasswordChange(PasswordChangeView):
"""パスワード変更ビュー"""
form_class = MyPasswordChangeForm
success_url = reverse_lazy('UserLogin:password_change_done')
template_name = 'registration/password_change.html'
class PasswordChangeDone(PasswordChangeDoneView):
"""パスワード変更しました"""
template_name = 'registration/password_change_done.html'
class PasswordReset(PasswordResetView):
"""パスワード変更用URLの送付ページ"""
subject_template_name = 'registration/mail_template/password_reset/subject.txt'
email_template_name = 'registration/mail_template/password_reset/message.txt'
template_name = 'registration/password_reset_form.html'
form_class = MyPasswordResetForm
success_url = reverse_lazy('UserLogin:password_reset_done')
class PasswordResetDone(PasswordResetDoneView):
"""パスワード変更用URLを送りましたページ"""
template_name = 'registration/password_reset_done.html'
class PasswordResetConfirm(PasswordResetConfirmView):
"""新パスワード入力ページ"""
form_class = MySetPasswordForm
success_url = reverse_lazy('UserLogin:password_reset_complete')
template_name = 'registration/password_reset_confirm.html'
class PasswordResetComplete(PasswordResetCompleteView):
"""新パスワード設定しましたページ"""
template_name = 'registration/password_reset_complete.html'
class EmailChange(LoginRequiredMixin, generic.FormView):
"""メールアドレスの変更"""
template_name = 'registration/email_change_form.html'
form_class = EmailChangeForm
def form_valid(self, form):
user = self.request.user
new_email = form.cleaned_data['email']
# URLの送付
current_site = get_current_site(self.request)
domain = current_site.domain
context = {
'protocol': 'https' if self.request.is_secure() else 'http',
'domain': domain,
'token': dumps(new_email),
'user': user,
}
subject = render_to_string('registration/mail_template/email_change/subject.txt', context)
message = render_to_string('registration/mail_template/email_change/message.txt', context)
send_mail(subject, message, None, [new_email])
return redirect('registration:email_change_done')
class EmailChangeDone(LoginRequiredMixin, generic.TemplateView):
"""メールアドレスの変更メールを送ったよ"""
template_name = 'registration/email_change_done.html'
class EmailChangeComplete(LoginRequiredMixin, generic.TemplateView):
"""リンクを踏んだ後に呼ばれるメアド変更ビュー"""
template_name = 'registration/email_change_complete.html'
timeout_seconds = getattr(settings, 'ACTIVATION_TIMEOUT_SECONDS', 60*60*24) # デフォルトでは1日以内
def get(self, request, **kwargs):
token = kwargs.get('token')
try:
new_email = loads(token, max_age=self.timeout_seconds)
# 期限切れ
except SignatureExpired:
return HttpResponseBadRequest()
# tokenが間違っている
except BadSignature:
return HttpResponseBadRequest()
# tokenは問題なし
else:
User.objects.filter(email=new_email, is_active=False).delete()
request.user.email = new_email
request.user.save()
return super().get(request, **kwargs)
class ShopPreView(TemplateView):
template_name = 'shop/infomation.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
shop_id = self.request.user.shop_number
if Shop.objects.filter( pk = shop_id ).exists():
context['shop'] = Shop.objects.get( pk = shop_id )
else:
pass
else:
pass
return context<file_sep>/UserLogin/models.py
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.base_user import ( AbstractBaseUser, BaseUserManager )
from django.contrib.auth.models import ( PermissionsMixin, UserManager )
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class CustomUserManager(UserManager):
"""ユーザーマネージャー"""
use_in_migrations = True
def _create_user(self, email, password, **extra_fields):
if not email:
raise ValueError('The given email must be set')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
extra_fields.setdefault('is_superuser', False)
return self._create_user(email, password, **extra_fields)
def create_superuser(self, email, password, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)
if extra_fields.get('is_staff') is not True:
raise ValueError('Superuser must have is_staff=True.')
if extra_fields.get('is_superuser') is not True:
raise ValueError('Smf jki8h09;mkuperuser must have is_superuser=True.')
return self._create_user(email, password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
"""カスタムユーザーモデル."""
shop_number = models.PositiveSmallIntegerField( verbose_name='店舗ID', default=0, )
email = models.EmailField( verbose_name='メールアドレス', max_length=255, unique=True, )
first_name_representative = models.CharField( verbose_name='代表者「名」', max_length=30, blank=True, help_text='代表者の方の「名」' , )
last_name_representative = models.CharField( verbose_name='代表者「姓」', max_length=30, blank=True, help_text='代表者の方の「姓」' , )
first_name_representative_kana = models.CharField( verbose_name='代表者「メイ」', max_length=30, blank=True, help_text='代表者の方の「メイ」(フリガナ)' , )
last_name_representative_kana = models.CharField( verbose_name='代表者「セイ」', max_length=30, blank=True, help_text='代表者の方の「セイ」(フリガナ)' , )
first_name_manager = models.CharField( verbose_name='管理者「名」', max_length=30, blank=True, help_text='管理者の方の「名」' , )
last_name_manager = models.CharField( verbose_name='管理者「姓」', max_length=30, blank=True, help_text='管理者の方の「姓」' )
first_name_manager_kana = models.CharField( verbose_name='管理者「メイ」', max_length=30, blank=True, help_text='管理者の方の「メイ」(フリガナ)' , )
last_name_manager_kana = models.CharField( verbose_name='管理者「セイ」', max_length=30, blank=True, help_text='管理者の方の「セイ」(フリガナ)' , )
tel = models.CharField( verbose_name='電話番号', max_length=15, blank=True, )
remarks = models.TextField( verbose_name='備考', max_length=150, blank=True, )
is_staff = models.BooleanField(
_('staff status'),
default=False,
help_text=_(
'Designates whether the user can log into this admin site.'),
)
is_active = models.BooleanField(
_('active'),
default=True,
help_text=_(
'Designates whether this user should be treated as active. '
'Unselect this instead of deleting accounts.'
),
)
date_joined = models.DateTimeField(_('date joined'), default=timezone.now)
objects = CustomUserManager()
EMAIL_FIELD = 'email'
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
class Meta:
verbose_name = _('会員')
verbose_name_plural = _('会員')
def get_full_name(self):
"""Return the first_name plus the last_name, with a space in
between."""
full_name = '%s %s' % (self.first_name_manager, self.last_name_manager)
return full_name.strip()
def get_short_name(self):
"""Return the short name for the user."""
def email_user(self, subject, message, from_email=None, **kwargs):
"""Send an email to this user."""
send_mail(subject, message, from_email, [self.email], **kwargs)
@property
def username(self):
"""username属性のゲッター
他アプリケーションが、username属性にアクセスした場合に備えて定義
メールアドレスを返す
"""
return self.email
class Shop(models.Model):
shop_name = models.CharField( verbose_name='店名', default='SHOP', max_length=20, )
shop_name_kana = models.CharField( verbose_name='テンメイ', default='ショップ', max_length=30, )
manager_name = models.CharField( verbose_name='管理者', default='CHIEF', max_length=15, )
manager_account = models.ForeignKey('User', verbose_name='管理者アカウント', to_field='email', related_name='ManagerAccount', on_delete='models.DO_NOTHING', null=True, )
#連絡用
email = models.EmailField( verbose_name='お客様用メールアドレス', max_length=255, blank = True, null = True )
tel_shop = models.CharField( verbose_name='電話番号', max_length=15, blank=True, )
website = models.CharField( verbose_name='サイトURL', default='http://www.', max_length=100, )
#アクセス情報
zip_code = models.CharField(
verbose_name='郵便番号',max_length=8,blank=True,
)
address1 = models.CharField(
verbose_name='都道府県',max_length=40,blank=True,
)
address2 = models.CharField(
verbose_name='市区町村',max_length=40,blank=True,
)
address3 = models.CharField(
verbose_name='丁目',max_length=40,blank=True,
)
address4 = models.CharField(
verbose_name='番地以降',max_length=40,blank=True,
)
address5 = models.CharField(
verbose_name='建物名・部屋番号等',max_length=40,blank=True,
)
station1 = models.CharField( verbose_name='付近の駅・バス停1', max_length=15, blank=True, )
station1_time = models.PositiveSmallIntegerField( verbose_name='駅・バス停1からの所要時間', default=0, )
station2 = models.CharField( verbose_name='付近の駅・バス停2', max_length=15, blank=True, )
station2_time = models.PositiveSmallIntegerField( verbose_name='駅・バス停2からの所要時間', default=0, )
station3 = models.CharField( verbose_name='付近の駅・バス停3', max_length=15, blank=True, )
station3_time = models.PositiveSmallIntegerField( verbose_name='駅・バス停3からの所要時間', default=0, )
#サービス内容
price_basic = models.PositiveSmallIntegerField( verbose_name='基本料金', default=0, )
support_list = ( (0,''), (1,'可'), (2,'応相談'), )
wheelchair = models.IntegerField( verbose_name='車イス対応',choices=support_list, default=0, )
visually = models.IntegerField( verbose_name='視覚障碍対応',choices=support_list, default=0, )
hearing = models.IntegerField( verbose_name='聴覚障碍対応',choices=support_list, default=0, )
#営業時間
is_holiday_sunday = models.BooleanField( verbose_name='日曜日', default='False', )
is_holiday_monday = models.BooleanField( verbose_name='月曜日', default='False')
is_holiday_tuesday = models.BooleanField( verbose_name='火曜日', default='False')
is_holiday_wednesday = models.BooleanField( verbose_name='水曜日', default='False')
is_holiday_thursday = models.BooleanField( verbose_name='木曜日', default='False')
is_holiday_friday = models.BooleanField( verbose_name='金曜日', default='False')
is_holiday_saturday = models.BooleanField( verbose_name='土曜日', default='False')
time_list = ( (00,'00:00'), (1,'00:30'), (2,'01:00'), (3,'01:30'), (4,'02:00'), (5,'02:30'), (6,'03:00'), (7,'03:30'), (8,'04:00'), (9,'04:30'), (10,'05:00'), (11,'05:30'),
(12,'06:00'), (13,'06:30'),(14,'07:00'), (15,'07:30'),(16,'08:00'), (17,'08:30'),(18,'09:00'), (19,'09:30'),(20,'10:00'), (21,'10:30'), (22,'11:00'), (23,'11:30'),
(24,'12:00'), (25,'12:30'),(26,'13:00'), (27,'13:30'),(28,'14:00'), (29,'14:30'),(30,'15:00'), (31,'15:30'),(32,'16:00'), (33,'16:30'), (34,'17:00'), (35,'17:30'),
(36,'18:00'), (37,'18:30'),(38,'19:00'), (39,'19:30'),(40,'20:00'), (41,'20:30'),(42,'21:00'), (43,'21:30'),(44,'22:00'), (45,'22:30'), (46,'23:00'), (47,'23:30'), (48,'24:00'), )
time_open_sunday1 = models.IntegerField( verbose_name='【日曜日】開店時刻1',choices=time_list, default=0, help_text='sunday', )
time_close_sunday1 = models.IntegerField( verbose_name='【日曜日】閉店時刻1',choices=time_list, default=0, help_text='sunday', )
time_open_sunday2 = models.IntegerField( verbose_name='【日曜日】開店時刻2',choices=time_list, default=0, help_text='sunday', )
time_close_sunday2 = models.IntegerField( verbose_name='【日曜日】閉店時刻2',choices=time_list, default=0, help_text='sunday', )
time_open_monday1 = models.IntegerField( verbose_name='【月曜日】開店時刻1',choices=time_list, default=0, help_text='monday', )
time_close_monday1 = models.IntegerField( verbose_name='【月曜日】閉店時刻1',choices=time_list, default=0, help_text='monday', )
time_open_monday2 = models.IntegerField( verbose_name='【月曜日】開店時刻2',choices=time_list, default=0, help_text='monday', )
time_close_monday2 = models.IntegerField( verbose_name='【月曜日】閉店時刻2',choices=time_list, default=0, help_text='monday', )
time_open_tuesday1 = models.IntegerField( verbose_name='【火曜日】開店時刻1',choices=time_list, default=0, help_text='tuesday', )
time_close_tuesday1 = models.IntegerField( verbose_name='【火曜日】閉店時刻1',choices=time_list, default=0, help_text='tuesday', )
time_open_tuesday2 = models.IntegerField( verbose_name='【火曜日】開店時刻2',choices=time_list, default=0, help_text='tuesday', )
time_close_tuesday2 = models.IntegerField( verbose_name='【火曜日】閉店時刻2',choices=time_list, default=0, help_text='tuesday', )
time_open_wednesday1 = models.IntegerField( verbose_name='【水曜日】開店時刻1',choices=time_list, default=0, help_text='wednesday', )
time_close_wednesday1 = models.IntegerField( verbose_name='【水曜日】閉店時刻1',choices=time_list, default=0, help_text='wednesday', )
time_open_wednesday2 = models.IntegerField( verbose_name='【水曜日】開店時刻2',choices=time_list, default=0, help_text='wednesday', )
time_close_wednesday2 = models.IntegerField( verbose_name='【水曜日】閉店時刻2',choices=time_list, default=0, help_text='wednesday', )
time_open_thursday1 = models.IntegerField( verbose_name='【木曜日】開店時刻1',choices=time_list, default=0, help_text='thursday', )
time_close_thursday1 = models.IntegerField( verbose_name='【木曜日】閉店時刻1',choices=time_list, default=0, help_text='thursday', )
time_open_thursday2 = models.IntegerField( verbose_name='【木曜日】開店時刻2',choices=time_list, default=0, help_text='thursday', )
time_close_thursday2 = models.IntegerField( verbose_name='【木曜日】閉店時刻2',choices=time_list, default=0, help_text='thursday', )
time_open_friday1 = models.IntegerField( verbose_name='【金曜日】開店時刻1',choices=time_list, default=0, help_text='friday', )
time_close_friday1 = models.IntegerField( verbose_name='【金曜日】閉店時刻1',choices=time_list, default=0, help_text='friday', )
time_open_friday2 = models.IntegerField( verbose_name='【金曜日】開店時刻2',choices=time_list, default=0, help_text='friday', )
time_close_friday2 = models.IntegerField( verbose_name='【金曜日】閉店時刻2',choices=time_list, default=0, help_text='friday', )
time_open_saturday1 = models.IntegerField( verbose_name='【土曜日】開店時刻1',choices=time_list, default=0, help_text='saturday', )
time_close_saturday1 = models.IntegerField( verbose_name='【土曜日】閉店時刻1',choices=time_list, default=0, help_text='saturday', )
time_open_saturday2 = models.IntegerField( verbose_name='【土曜日】開店時刻2',choices=time_list, default=0, help_text='saturday', )
time_close_saturday2 = models.IntegerField( verbose_name='【土曜日】閉店時刻2',choices=time_list, default=0, help_text='saturday', )
#評価用
point = models.IntegerField( verbose_name='店舗ID', default=0, )
remarks_shop = models.TextField( verbose_name='備考', max_length=150, blank=True, )
created_at = models.DateTimeField( auto_now_add=True, )
updated_at = models.DateTimeField( auto_now=True, )
class Meta:
verbose_name = _('店舗情報')
verbose_name_plural = _('店舗情報')
def __str__(self):
return self.shop_name<file_sep>/UserLogin/migrations/0004_auto_20210717_1520.py
# Generated by Django 2.2.24 on 2021-07-17 06:20
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('UserLogin', '0003_shop_time_cloae_sunday1'),
]
operations = [
migrations.RenameField(
model_name='shop',
old_name='time_cloae_sunday1',
new_name='time_close_sunday1',
),
]
| 4e8b63f71d77992e4c6263bdceb23a99fba9397b | [
"Python",
"HTML"
] | 13 | Python | Kazuki-AK/IKS_SHOP | b665230e99ab9f4fc6cb71e4ab8a149c13712f73 | 45e74d71485083d1e0b5fd4f82aef17f2f8dd8a9 | |
refs/heads/master | <file_sep>-- Ejercicio 14 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists medicamentos;
-- 2
create table medicamentos(
codigo integer auto_increment,
nombre varchar(20) not null,
laboratorio varchar(20),
precio float,
cantidad integer not null,
primary key (codigo)
);
-- 3
describe medicamentos;
-- 4
insert into medicamentos (nombre,laboratorio,precio,cantidad)
values('Sertal gotas','Roche',5.2,100);
insert into medicamentos (nombre,laboratorio,precio,cantidad)
values('Sertal compuesto','Roche',7.1,150);
insert into medicamentos (nombre,laboratorio,precio,cantidad)
values('Buscapina','Roche',null,200);
insert into medicamentos (nombre,laboratorio,precio,cantidad)
values('Amoxidal 500','Bayer',15.60,0);
insert into medicamentos (nombre,laboratorio,precio,cantidad)
values('Amoxidal jarabe','Bayer',25,120);
insert into medicamentos (nombre,laboratorio,precio,cantidad)
values('Amoxinil',null,25,120);
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Bayaspirina','',0,150);
-- 5
select * from medicamentos;
-- 6
select * from medicamentos where laboratorio is null;
select * from medicamentos where laboratorio='';
-- 7
select * from medicamentos where precio is null;
select * from medicamentos where precio=0;
-- 8
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values(null,'Bayer',10.20,100);
-- ERROR 1048 (23000): Column 'nombre' cannot be null
-- 8
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('<NAME>','Bayer',10.20,null);
-- ERROR 1048 (23000): Column 'cantidad' cannot be null
-- 9
insert into medicamentos (codigo,nombre, laboratorio,precio,cantidad)
values(null,'<NAME>','Bayer',10.20,null);
-- ERROR 1048 (23000): Column 'cantidad' cannot be null
-- 10
select * from medicamentos where precio<>0;
select * from medicamentos where precio is not null;
-- 11
select * from medicamentos where laboratorio<>'';
select * from medicamentos where laboratorio is not null;<file_sep>-- Ejercicio 18 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists pedido;
-- 2
create table pedido(
numero_pedido tinyint unsigned auto_increment,
nombre char(8),
tipo varchar (15),
precio decimal(2.2) unsigned,
cantidad tinyint unsigned,
domicilio varchar(20),
primary key (numero_pedido)
);<file_sep>-- Ejercicio 4 Obs: Los numeros indican los pasos del problema
-- Problema
use Base_Datos_I;
-- 1
drop table if exists agenda;
-- 2
Create table agenda(
nombre varchar(20),
domicilio varchar(30),
telefono varchar(11)
)engine=InnoDB;
-- 3
show tables;
-- 4
describe agenda;
-- 5
insert into agenda(nombre,domicilio,telefono)
values('<NAME>','Colon 123', '4234567');
insert into agenda(nombre,domicilio,telefono)
values('<NAME>','Avellanada 135', '4458787');
-- 6
select * from agenda;
-- 7
drop table if exists agenda;
-- 8
drop table agenda;
-- ERROR 1051 (42S02): Unknown table 'datos_amigos.agenda'
<file_sep>-- Ejercicio 6 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists peliculas;
-- 2
create table peliculas(
titulo varchar(20),
actor varchar(20),
duracion integer,
cantidad integer
);
-- 3
describe peliculas;
-- 4
insert into peliculas (titulo, actor, duracion, cantidad)
values ('Mision imposible','<NAME>',120,3);
insert into peliculas (titulo, actor, duracion, cantidad)
values ('Mision imposible 2','<NAME>',180,2);
insert into peliculas (titulo, actor, duracion, cantidad)
values ('<NAME>','<NAME>.',90,3);
insert into peliculas (titulo, actor, duracion, cantidad)
values ('<NAME>','China Zorrilla',90,2);
-- 5
select titulo,actor from peliculas;
-- 6
select titulo,duracion from peliculas;
-- 7
select titulo,cantidad from peliculas;
<file_sep>-- Ejercicio 9 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists agenda;
-- 2
create table agenda(
apellido varchar(30),
nombre varchar(20),
domicilio varchar(30),
telefono varchar(11)
);
-- 3
describe agenda;
-- 4
insert into agenda(apellido,nombre,domicilio,telefono)
values( 'Mores','Alberto','Colon 123','4234567');
insert into agenda(apellido,nombre,domicilio,telefono)
values('Torres','Juan','Avellaneda 135','4458787');
insert into agenda(apellido,nombre,domicilio,telefono)
values( 'Lopez','Mariana','Urquiza 333','4545454');
insert into agenda(apellido,nombre,domicilio,telefono)
values('Lopez','Jose','Urquiza 333','4545454');
insert into agenda(apellido,nombre,domicilio,telefono)
values('Peralta','Susana','Gral. Paz 1234','4123456');
-- 5
set SQL_SAFE_UPDATES=0;
delete from agenda
where nombre = 'Juan';
-- 6
delete from agenda
where telefono = '4545454';
set SQL_SAFE_UPDATES=1;<file_sep>-- Ejercicio 15 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists peliculas;
-- 2
/*Tenga en cuenta el rango de valores que almacenará cada campo:
-codigo: entero a partir de 1, autoincrementable,
-titulo: caracteres de 40 de longitud, no nulo,
-actor: cadena de 20,
-duracion: entero positivo,
-clave primaria: codigo.*/
-- 3
create table peliculas(
codigo integer unsigned auto_increment,
titulo varchar(40) not null,
actor varchar(20),
duracion integer unsigned,
primary key(codigo)
)engine = InnoDB;
-- 4
describe peliculas;<file_sep>-- Ejercicio 7 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists agenda;
-- 2
create table agenda(
nombre varchar(20),
domicilio varchar(30),
telefono varchar(11)
);
-- 3
describe agenda;
-- 4
insert into agenda(nombre, domicilio,telefono)
values( '<NAME>','Colon 123','4234567');
insert into agenda(nombre, domicilio,telefono)
values( '<NAME>','Avellaneda 135','4458787');
insert into agenda(nombre, domicilio,telefono)
values( '<NAME>','Urquiza 333','4545454');
insert into agenda(nombre, domicilio,telefono)
values( '<NAME>','Urquiza 333','4545454');
-- 5
select * from agenda;
-- 6
select * from agenda
where nombre='<NAME>';
-- 7
select * from agenda
where domicilio='Colon 123';
-- 8
select * from agenda
where telefono='4545454';
-- 9
drop table agenda;
<file_sep>-- Ejercicio 12 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists medicamentos;
-- 2
create table medicamentos(
codigo integer auto_increment,
nombre varchar(20),
laboratorio varchar(20),
precio float,
cantidad integer,
primary key (codigo)
);
-- 3
describe medicamentos;
-- 4
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Sertal','Roche',5.2,100);
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Buscapina','Roche',4.10,200);
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Amoxidal 500','Bayer',15.60,100);
-- 5
select codigo,nombre,laboratorio,precio,cantidad
from medicamentos;
-- 6
insert into medicamentos (codigo,nombre, laboratorio,precio,cantidad)
values(3,'Paracetamol 500','S.O.S',2.8,22);
-- ERROR 1062 (23000): Duplicate entry '3' for key 'PRIMARY'
-- 7
insert into medicamentos (codigo,nombre, laboratorio,precio,cantidad)
values(12,'Paracetamol 500','Bago',1.90,200);
-- 8
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Bayaspirina','Bayer',2.10,150); <file_sep>-- Ejercicio 5 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists peliculas;
-- 2
create table peliculas(
nombre varchar(20),
actor varchar(20),
duracion integer,
cantidad integer
);
-- 3
describe peliculas;
-- 4
insert into peliculas (nombre, actor, duracion, cantidad)
values ('Mision imposible','<NAME>',120,3);
insert into peliculas (nombre, actor, duracion, cantidad)
values ('Mision imposible 2','<NAME>',180,2);
insert into peliculas (nombre, actor, duracion, cantidad)
values ('<NAME>','<NAME>.',90,3);
insert into peliculas (nombre, actor, duracion, cantidad)
values ('<NAME>','China Zorrilla',90,2);
-- 5
select * from peliculas;
<file_sep>-- Ejercicio 13 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists medicamentos;
-- 2
create table medicamentos(
codigo integer auto_increment,
nombre varchar(20),
laboratorio varchar(20),
precio float,
cantidad integer,
primary key (codigo)
);
-- 3
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Sertal','Roche',5.2,100);
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Buscapina','Roche',4.10,200);
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Amoxidal 500','Bayer',15.60,100);
-- 4
delete from medicamentos;
-- 5
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Sertal','Roche',5.2,100);
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Amoxidal 500','Bayer',15.60,100);
-- 6
select * from medicamentos;
-- 7
truncate table medicamentos;
-- 8
insert into medicamentos (nombre, laboratorio,precio,cantidad)
values('Buscapina','Roche',4.10,200);
-- 9
select * from medicamentos;<file_sep>/*Ejercicio 3 Obs: Los numeros indican los pasos del problema
--Problema*/
create database Base_Datos_I;
show databases;
use Base_Datos_I;
-- 1
drop table if exists agenda;
-- 2
create table Base_Datos_I.agenda(
nombre varchar(20),
domicilio varchar(30),
telefono varchar(11)
) engine=InnoDB;
-- 3
create table Base_Datos_I.agenda(
nombre varchar(20),
domicilio varchar(30),
telefono varchar(11)
) engine=InnoDB;
-- ERROR 1050 (42S01): Table 'agenda' already exists
-- 4
show tables;
-- 5
describe agenda;
-- 6
drop table if exists agenda;
-- 7
drop table agenda;
-- ERROR 1051 (42S02): Unknown table 'datos_amigos.agenda'
<file_sep>-- Ejercicio 8 Obs: Los numeros indican los pasos del problema
-- Problema Oficial
use Base_Datos_I;
-- 1
drop table if exists articulos;
-- 2
create table articulos(
codigo integer,
nombre varchar(20),
descripcion varchar(30),
precio float,
cantidad integer
);
-- 3
describe articulos;
-- 4
insert into articulos (codigo, nombre, descripcion, precio,cantidad)
values (1,'impresora','Epson Stylus C45',400.80,20);
insert into articulos (codigo, nombre, descripcion, precio,cantidad)
values (2,'impresora','Epson Stylus C85',500,30);
insert into articulos (codigo, nombre, descripcion, precio,cantidad)
values (3,'monitor','Samsung 14',800,10);
insert into articulos (codigo, nombre, descripcion, precio,cantidad)
values (4,'teclado','ingles Biswal',100,50);
insert into articulos (codigo, nombre, descripcion, precio,cantidad)
values (5,'teclado','español Biswal',90,50);
-- 5
select * from articulos;
-- 6
select *from articulos
where nombre = 'impresora';
-- 7
select * from articulos
where precio>=500;
-- 8
select nombre,descripcion, precio,cantidad from articulos
where cantidad<30;
-- 9
select nombre, descripcion from articulos
where precio<>100;
| 4cb5605704a5a795d00f61bb9fb06eb774c34469 | [
"SQL"
] | 12 | SQL | SaidaPereira/BASE_DE_DATOS_I | 712fd5791c87f040c7d58827ee56fdddd94fce70 | 11b60e192b3618d98a0e56ff2c0c0788b7a05f8b | |
refs/heads/master | <file_sep>#include "../head/LinkStack.h"
#include<stdio.h>
#include<stdlib.h>
Status initLStack(LinkStack *s) {
s->top = (LinkStackPtr)malloc(sizeof(StackNode));
if(!(s->top))
return ERROR;
s->top = NULL;
s->count = 0;
return SUCCESS;
}
Status isEmptyLStack(LinkStack *s) {
if(!(s->top)) {
printf("栈为空!\n");
return ERROR;
}
else {
printf("栈不为空!\n");
return SUCCESS;
}
}
Status getTopLStack(LinkStack *s,ElemType *e) {
if(!(s->top)) {
printf("栈为空!\n");
return ERROR;
}
else {
*e = s->top->data;
printf("获取栈顶元素成功!\n");
printf("栈顶元素为%d\n",*e);
return SUCCESS;
}
}
Status clearLStack(LinkStack *s) {
s->top = NULL;
return SUCCESS;
}
Status destroyLStack(LinkStack *s) {
StackNode *p;
p = s->top;
while(s->top) {
s->top = p->next;
free(p);
p = s->top;
}
return SUCCESS;
}
Status LStackLength(LinkStack *s,int *length) {
StackNode *p;
p = s->top;
*length = 0;
while(p) {
(*length)++;
p=p->next;
}
return SUCCESS;
}
Status pushLStack(LinkStack *s,ElemType data) {
StackNode *p;
p = (StackNode *)malloc(sizeof(StackNode));
if(!p)
return ERROR;
p->data = data;
p->next = s->top;
s->top = p;
s->count++;
printf("入栈成功!\n");
return SUCCESS;
}
Status popLStack(LinkStack *s,ElemType *data) {
StackNode *p;
p = s->top;
if(!p)
return ERROR;
if(!(s->top)) {
printf("栈为空!\n");
return ERROR;
}
*data = p->data;
s->top = p->next;
s->count--;
free(p);
printf("出栈成功!\n");
return SUCCESS;
}
Status TraverseStack(LinkStack *s) {
int i;
StackNode *p = s->top;
if (!(s->top))
return ERROR;
for(i=s->count;i>0;i--) {
printf("%d ",p->data);
p=p->next;
}
return SUCCESS;
}
int chnum(char *str) {
int i,n,num=0;
for(i=0;str[i]!='\0';i++){
if(str[i]>='0'&&str[i]<='9') {
num=num*10+str[i]-'0';
}
}
return num;
}
<file_sep>driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql:///day01
username=root
password=<PASSWORD>
initialSize=5
maxActive=10
maxWait=3000<file_sep>#QG训练营后台组第四周周记:
2020年4月27日
## 生活随记
还有两天就最终考核了,完成了最后一次训练营的作业,也总算兑现了自己的承诺“坚持下来”,最终考核的结果怎么样谁也不知道,但是我觉得在这一个月内自己成长了很多,在训练营的日子也算痛并快乐着,期间踩了无数的坑,查各个网站的资料,不停的尝试,把一个个困扰着自己的问题解决掉,也是因为这样,在这种高压状态下学到了很多很多知识,独自解决问题的能力和抗压能力都在不断地提升,我也会时刻警醒自己少犯错,少走弯路,这样效率才会高,才会进步。
##一周总结
(1)在改进自己的登录注册页面,理解前后端的数据共享,同时也在学习Filter和Jquery相关的知识点。
(2)完成了这周的大组作业,掌握了数据结构二叉树的遍历,创建表达树,以及中缀表达式转前缀表达式等知识。
##存在问题
(1)最近时间分配的不太好,临近考核要学的东西很多,课内的作业有点跟不上。
(2)平时熬夜多,早上起来迟,作息不规律。
##下周规划
准备好奋斗最终考核的大项目。
<file_sep>#include "../head/SqStack.h"
#include<stdio.h>
#include<stdlib.h>
void main()
{
SqStack *s;
ElemType data,e;
char a[100],b[100];int num,length;
s=(SqStack *)malloc(sizeof(SqStack));
s->size=100;
initStack(s,s->size);
while(1) {
printf("****************************************************************\n");
printf("* *\n");
printf("*******************数据结构之数组栈程序设计********************\n");
printf("* *\n");
printf("***************作者:梁德钊(3119005103)软工三班******************\n");
printf("* 1.判断栈链是否为空 *\n");
printf("* 2.得到栈顶元素 *\n");
printf("* 3.清空栈 *\n");
printf("* 4.销毁栈 *\n");
printf("* 5.检测栈长度 *\n");
printf("* 6.入栈 *\n");
printf("* 7.出栈 *\n");
printf("* 8.遍历栈 *\n");
printf("* 0.退出程序 *\n");
printf("****************************************************************\n");
printf("请输入要执行的操作前的选项:");
while(1) {
gets(a);
num=a[0]-'0';
if(a[0]>='0'&&a[0]<='8')break;
printf("输入错误,请再次输入:");
}
switch(num){
case 1:
system("cls");
printf("*********************\n");
isEmptyStack(s);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
system("cls");
printf("*********************\n");
getTopStack(s,&e);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
system("cls");
clearStack(s);
printf("*********************\n");
printf("清空成功!\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
system("cls");
destroyStack(s);
printf("*********************\n");
printf("销毁成功!\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
system("cls");
stackLength(s,&length);
printf("*********************\n");
printf("栈长度为:%d\n",length);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
system("cls");
printf("*********************\n");
printf("请输入入栈的数据(data):");
gets(a);
pushStack(s,chnum(a));
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 7:
system("cls");
printf("*********************\n");
popStack(s,&data);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 8:
system("cls");
printf("*********************\n");
printf("栈数据为:");
TraverseStack(s);
printf("\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);break;
}
}
}
<file_sep>#QG训练营后台组第二周周记:
2020年4月12日
## 生活随记
最近的生活还是一如既往的紧凑哎,除了网课布置的作业,还得去跟上训练营的进度,不过有一点值得说的是心态好像平缓的好多,不像之前那样急躁。收到消息好像快要开学了,得好好把握这个月了,现在都这么忙估计回学校更加忙。
##一周总结
(1)最近这周在学JDBC和MYSQL,在不停的刷视频,但是还是有很多搞不懂的地方。
(2)在写大组作业的时候学会怎样巧用void*和void *memcpy(void *destin, void *source, unsigned n);
实现c语言的泛型。
##存在问题
1.在写队列的时候指针方面出错很多,然后花了很多时间去改。
2.小组作业写Java项目的时候的格式不太规范。
3.完成效率很慢了,基本上完成作业都要花上一天多。
##下周规划
1.呜呜呜这周的高数测验要来了,要好好备考高数第一次测验。
2.继续刷视频学servlet,学完的话再继续学下去。
<file_sep>#ifndef STACK_H_INCLUDED
#define STACK_H_INCLUDED
typedef enum Status
{
ERROR = 0, SUCCESS = 1
} Status;
typedef char ElemType;
typedef struct SqStack
{
ElemType *elem;
int top;
int size;
} SqStack;
typedef struct SqStack1
{
float *elem1;
int top;
int size;
} SqStack1;
Status destroyStack(SqStack *s);
Status initStack(SqStack *s,int sizes);
Status initStack1(SqStack1 *s,int sizes);
Status isEmptyStack(SqStack *s);
Status pushStack(SqStack *s,ElemType data);
Status pushStack1(SqStack1 *s,float data);
Status popStack(SqStack *s,ElemType *data);
Status popStack1(SqStack1 *s,float *data);
int chnum(char a);
void Calculate();
#endif
<file_sep>#include"../AQueue/AQueue.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void InitAQueue(AQueue *Q){
int i;
Q->length=MAXQUEUE;
for(i=0;i<MAXQUEUE;i++) {
Q->data[i] = (void *)malloc(20);
}
Q->front = 0;
Q->rear = 0;
datatype[Q->rear]='i';
printf("队列初始化成功!\n");
}
void DestoryAQueue(AQueue *Q) {
int i;
if(Q->data[0]==NULL) {
printf("队列未初始化!\n");
return;
}
for(i=0;i<MAXQUEUE;i++) {
free(Q->data[i]);
}
printf("销毁队列成功!\n");
Q->data[0]=NULL;
}
Status IsFullAQueue(const AQueue *Q) {
if(Q->data[0]==NULL) {
printf("队列未初始化!\n");
return -1;
}
return Q->front==(Q->rear+1)%MAXQUEUE ? TRUE:FALSE;
}
Status IsEmptyAQueue(const AQueue *Q) {
int i;
if(Q->data[0]==NULL) {
printf("队列未初始化!\n");
return -1;
}
return Q->rear==Q->front ? TRUE:FALSE;
}
Status GetHeadAQueue(AQueue *Q,void *e) {
int flag;
flag=IsEmptyAQueue(Q);
if(flag==-1) return FALSE;
memcpy(e,Q->data[Q->front],20);
printf("获取头元素成功!\n");
return TRUE;
}
int LengthAQueue(AQueue *Q) {
int len;
if(IsEmptyAQueue(Q)==-1)
return FALSE;
len=(Q->rear+1-Q->front+Q->length)%Q->length;
return len;
}
Status EnAQueue(AQueue *Q, void *data) {
int flag;
flag=IsFullAQueue(Q);
if(flag==-1) return FALSE;
if(flag==TRUE) {
printf("队列已满!\n");
return FALSE;
}
Q->rear=(Q->rear+1)%MAXQUEUE;
memcpy(Q->data[Q->rear],data,20);
return TRUE;
}
Status DeAQueue(AQueue *Q) {
int flag;
flag=IsEmptyAQueue(Q);
if(flag==-1) return FALSE;
if(flag==TRUE) {
printf("队列为空!\n");
return FALSE;
}
Q->front=(Q->front+1)%MAXQUEUE;
printf("出队成功!\n");
return TRUE;
}
void ClearAQueue(AQueue *Q) {
if(Q->data[0]==NULL) {
printf("队列未初始化!\n");
return;
}
Q->front=0;
Q->rear=0;
printf("清空成功!\n");
}
Status TraverseAQueue(const AQueue *Q, void (*foo)(void *q,char type)) {
int i,j,flag;
j=0;i=Q->front;
flag=IsEmptyAQueue(Q);
if(flag==-1) return FALSE;
while(j<=(Q->rear-Q->front+MAXQUEUE)%MAXQUEUE) {
foo(Q->data[i],datatype[i]);
i=(i+1)%MAXQUEUE;
j++;
}
printf("\n");
return TRUE;
}
void APrint(void *q,char type) {
if(type=='d')
printf("-->%lf",*(double *)q);
else if(type=='c')
printf("-->%c",*(char *)q);
else if(type=='i')
printf("-->%d",*(int *)q);
else if(type=='s')
printf("-->%s",(char *)q);
}
<file_sep>#include "../head/duLinkedList.h"
#include<stdlib.h>
#include<stdio.h>
/**
* @name : Status InitList_DuL(DuLinkedList *L)
* @description : initialize an empty linked list with only the head node
* @param : L(the head node)
* @return : Status
* @notice : None
*/
Status InitList_DuL(DuLinkedList *L) {
*L=(DuLinkedList)malloc(sizeof(DuLNode));
if(!(*L))
return ERROR;
(*L)->next=NULL;
(*L)->prior=NULL;
return SUCCESS;
}
/**
* @name : Status CreateList_DuL(DuLinkedList *L)
* @description : Create a new linked list with data
* @param : L(the head node)
* @return : Status
* @notice : None
*/
Status CreateList_DuL(DuLinkedList *L) {
int n=0;
char str[100],str1[100],end[3]="end";
DuLNode *p1,*p2;
p1=p2=(DuLinkedList)malloc(sizeof(DuLNode));
printf("请输入节点的数据,输入end结束\n->");
gets(str1);
gets(str);
p1->data=chnum(str);
while(strcmp(str,end)) {
n++;
if(n==1) {
(*L)->next=p1;
p1->prior=(*L);
}
else {
p2->next=p1;
p1->prior=p2;
}
p2=p1;
printf("->");
p1=(DuLinkedList)malloc(sizeof(DuLNode));
gets(str);
p1->data=chnum(str);
}
p2->next=NULL;
return SUCCESS;
}
/**
* @name : void DestroyList_DuL(DuLinkedList *L)
* @description : destroy a linked list
* @param : L(the head node)
* @return : status
* @notice : None
*/
void DestroyList_DuL(DuLinkedList *L) {
DuLNode *p;
while(*L) {
p=(*L);
(*L)=(*L)->next;
free(p);
if(*L)
(*L)->prior=NULL;
}
}
/**
* @name : Status InsertBeforeList_DuL(DuLNode *p, LNode *q)
* @description : insert node q before node p
* @param : p, q
* @return : status
* @notice : None
*/
Status InsertBeforeList_DuL(DuLNode *p, DuLNode *q) {
if(!p)
return ERROR;
p->prior->next = q;
q->prior = p->prior;
q->next = p;
p->prior = q;
return SUCCESS;
}
/**
* @name : Status InsertAfterList_DuL(DuLNode *p, DuLNode *q)
* @description : insert node q after node p
* @param : p, q
* @return : status
* @notice : None
*/
Status InsertAfterList_DuL(DuLNode *p, DuLNode *q) {
if(!p)
return ERROR;
if(p->next){
p->next->prior = q;
q->next = p->next;
}
else {
q->next=NULL;
}
q->prior = p;
p->next = q;
return SUCCESS;
}
/**
* @name : Status DeleteList_DuL(DuLNode *p, ElemType *e)
* @description : delete the first node after the node p and assign its value to e
* @param : p, e
* @return : status
* @notice : None
*/
Status DeleteList_DuL(DuLNode *p, ElemType *e) {
DuLNode *q;
if(!(p->next))
return ERROR;
q = p->next;
*e = q->data;
if(q->next)
q->next->prior = p;
p->next = q->next;
free(q);
return SUCCESS;
}
/**
* @name : void TraverseList_DuL(DuLinkedList L, void (*visit)(ElemType e))
* @description : traverse the linked list and call the funtion visit
* @param : L(the head node), visit
* @return : Status
* @notice : None
*/
void TraverseList_DuL(DuLinkedList L, void (*visit)(ElemType e)) {
DuLNode *p=L->next;
while(p) {
if(p->next==NULL)
(*visit)(p->data);
else {
(*visit)(p->data);
printf("->");
}
p=p->next;
}
}
/**
* @name : void visit(ElemType e)
* @description : print e
* @param : e
* @return : None
* @notice : None
*/
void visit(ElemType e) {
printf("%d",e);
}
/**
* @name : long int chnum(char *str)
* @description : String to integer
* @param : str
* @return : num
* @notice : None
*/
int chnum(char *str) {
int i,n,num=0;
for(i=0;str[i]!='\0';i++){
if(str[i]>='0'&&str[i]<='9') {
num=num*10+str[i]-'0';
}
}
return num;
}
<file_sep>#第一周周记
##初来到训练营的感受
经历了两轮的面试,有幸能够加入到QG训练营中去锻炼自己的能力,其实也不管那么多了,无论能不能进到QG工作室,我还是很开心的,起码能在训练营这段时间给自己施加压力去学新的知识。上周五的时候听完大组的培训后,开始了第一次作业,一开始慌得一批,主要是不清楚作业的要求,而且时间也挺紧的,本来自己的进度就不够别人快,四天内学git,github,markdown,实现双链表和单链表的各个接口。没办法只能硬着头皮去完成,智商不够时间来凑。
##学到的新知识
1.懂得了git和github的结构,怎样去提交自己的代码到本地仓库和远程仓库,在git bash里面输入命令行去实现各种文件的管理操作。
2.在实现duLinkedList.c和LinkedList.c中实现了链表的各种操作,刚开始搞不清楚形参为什么是二级指针,这个点疑惑了很久,原来如果形参是一级指针,那么只会改变指针指向的内容,传进来的指针是不会改变的,而在进行链表的操作时头指针的值经常会发生改变,所以需要传该指针的地址,形参定义二级指针。
3.记录一下选做偶数反转实现的方法和自己的理解
首先,需要判断链表的结点数是奇或偶
###图为改变节点指向的思路

###偶数反转相关代码
LNode* ReverseEvenList(LinkedList *L) {
LNode *p1,*p2,*p3;
p1=(*L)->next;
(*L)->next=p1->next;
while(p1&&p1->next) {
p2=p1->next;
p3=p2->next;
if(p2->next&&p2->next->next) {
p1->next=p3->next;
}
else {
p1->next=p2->next;
}
p2->next=p1;
p1=p3;
}
return *L;
}
##总结一下
平时的进度要加快,以后的项目更这次肯定难得多,还是要不断去坚持,规划好自己的学习计划。<file_sep>#QG训练营后台组第四周周记:
2020年4月19日
## 生活随记
距离考核的时间越来短了,在高压的工作状态中不得不快速学习接收大量的东西,不知道为什么感觉自己信心不是很足够,可能是因为自己的进度慢吧,担心自己完成不了,但没办法既然自己已经做出了选择,就一定要坚持下去,我希望自己真正能做到这一点,临近最终考核,自己更加要一步一步踏实地做好自己的事情。
##一周总结
(1)最近这周在学servlet&jsp。
(2)掌握了排序的各种算法,印象最深刻的就是用递归实现快排和归并,通过写非递归版的快排也让我更深刻理解到递归这个过程,栈和递归的原理差不多,都是先进后出,后进先出,那么递归的算法也就可以利用堆栈来实现。
记录一下快排(非递归版)的代码
void QuickSort(int *a,long size) {
int *stack;
stack = (int *)malloc(sizeof(int)*size);
int top,begin,end,mid;
top=begin=0;end=size-1;
mid = QuickSort_Recursion(a,begin,end);
if(mid>begin+1) {
stack[top++] = begin;
stack[top++] = mid-1;
}
if(mid<end-1) {
stack[top++] = mid+1;
stack[top++] = end;
}
while(top>0) {
end = stack[--top];
begin = stack[--top];
mid = QuickSort_Recursion(a,begin,end);
if(mid>begin+1) {
stack[top++] = begin;
stack[top++] = mid-1;
}
if(mid<end-1) {
stack[top++] = mid+1;
stack[top++] = end;
}
}
}
##存在问题
1.学servlet&jsp的时候遇到很多配置上的问题。
2.自己代码的分包不规范。
##下周规划
1.继续刷视频学下去,完成这周的作业任务。
<file_sep>#include"D:/QG训练营第五次培训/inc/BinaryTree.h"
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
void main()
{
int i;
int enter;
char a[100];
char *definition;
BiTree T=NULL;
while(1) {
printf("*********************************************\n");
printf("***************二叉树相关操作****************\n");
printf("*** 1.初始化二叉树 ***\n");
printf("*** 2.销毁二叉树 ***\n");
printf("*** 3.前缀表达式构造树 ***\n");
printf("*** 4.表达树求值 ***\n");
printf("*** 5.非递归遍历树 ***\n");
printf("*** 6.先序遍历 ***\n");
printf("*** 7.中序遍历 ***\n");
printf("*** 8.后序遍历 ***\n");
printf("*** 9.层序遍历 ***\n");
printf("*** 0.结束程序 ***\n");
printf("*********************************************\n");
printf("*********************************************\n");
printf("请输入选项:");
while(1) {
gets(a);
if(a[0]>='0'&&a[0]<='9') {
enter=a[0]-'0';
break;
}
printf("输入错误,请再次输入:");
}
system("cls");
switch(enter) {
case 1:
InitBiTree(&T);
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
if(T==NULL){
printf("二叉树为空树!\n");
}else{
DestroyBiTree(&T);
printf("销毁成功!\n");
}
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
if(T!=NULL) {
printf("该二叉树已存在!如果要重新构造树请先销毁\n");
break;
}
printf("请输入中缀表达式\n");
definition=(char *)malloc(sizeof(int)*20);
scanf("%s",definition);
gets(a);
change(definition);
printf("转换得前缀表达式为:\n");
for(i=0;definition[i]!='\0';i++){
printf("%c ",definition[i]);
}
CreateBiTree(&T,definition);
memset(definition,0,sizeof(definition));
printf("\n");
printf("构造二叉树成功!\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
if(T==NULL){
printf("二叉树为空!\n");
}else{
printf("表达树为\n");
PreOrderTraverse(T,visit);
printf("\n");
printf("求得表达树的值为%d\n",value(T));
}
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
if(T==NULL) {
printf("二叉树为空树!\n");
}else{
printf("遍历二叉树的结果为:\n");
Traverse(T,visit);
}
printf("\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
if(T==NULL){
printf("二叉树为空!\n");
}else{
printf("遍历二叉树的结果为:\n");
PreOrderTraverse(T,visit);
}
printf("\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 7:
if(T==NULL){
printf("二叉树为空!\n");
}else{
printf("遍历二叉树的结果为:\n");
InOrderTraverse(T,visit);
}
printf("\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 8:
if(T==NULL){
printf("二叉树为空!\n");
}else{
printf("遍历二叉树的结果为:\n");
PostOrderTraverse(T,visit);
}
printf("\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 9:
if(T==NULL){
printf("二叉树为空!\n");
}else{
printf("遍历二叉树的结果为:\n");
LevelOrderTraverse(T,visit);
}
printf("\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);
}
}
}
<file_sep>#include"stdio.h"
#include"stdlib.h"
#include"string.h"
void main()
{
FILE *fp;
int i;
long num;
char fileName[100];
printf("请输入要创建的文件名");
gets(fileName);
printf("已保存到当前目录里了哦\n");
fp = fopen(fileName,"w");
printf("请输入需要生成的随机数据的数量:");
scanf("%ld",&num);
fprintf(fp,"%d ",40000);
for(i=1;i<num;i++)
fprintf(fp,"%d ",rand());
printf("数据已生成啦!");
fclose(fp);
}
<file_sep>#include"D:/QG训练营第五次培训/inc/BinaryTree.h"
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
Status visit(TElemType e){//打印结点元素
printf("%c ",e);
return SUCCESS;
}
Status InOrderTraverse(BiTree T, Status (*visit)(TElemType e)) {//中序遍历T
if(T){
InOrderTraverse(T->lchild,(*visit));
(*visit)(T->data);
InOrderTraverse(T->rchild,(*visit));
}else{
return ERROR;
}
}
Status PostOrderTraverse(BiTree T, Status (*visit)(TElemType e)) {//后序遍历T
if(T){
PostOrderTraverse(T->lchild,(*visit));
PostOrderTraverse(T->rchild,(*visit));
(*visit)(T->data);
}else{
return ERROR;
}
}
Status PreOrderTraverse(BiTree T, Status (*visit)(TElemType e)) {//先序遍历T
if(T){
(*visit)(T->data);
PreOrderTraverse(T->lchild,(*visit));
PreOrderTraverse(T->rchild,(*visit));
}else{
return ERROR;
}
}
Status InitBiTree(BiTree *T){//构造空二叉树T
*T=NULL;
printf("二叉树初始化成功!\n");
return SUCCESS;
}
Status DestroyBiTree(BiTree *T){//摧毁二叉树T
if((*T)==NULL){
return ERROR;
}
DestroyBiTree(&((*T)->lchild));
DestroyBiTree(&((*T)->rchild));
free(*T);
*T=NULL;
return SUCCESS;
}
/*按前序输入二叉树中结点的值(一个字符)*/
/*definition为'#'表示空树,构造二叉链表表示二叉树T*/
Status CreateBiTree(BiTree *T, char* definition) {
char data;
data=nextToken(definition);
(*T)=(BiTree)malloc(sizeof(BiTNode));
if(!(*T)) return ERROR;
(*T)->data=data;
(*T)->lchild=NULL;
(*T)->rchild=NULL;
if(!isOpNum(data)) {
CreateBiTree(&(*T)->lchild,definition);
CreateBiTree(&(*T)->rchild,definition);
}
return SUCCESS;
}
char nextToken(char *definition)//括号、操作数、操作符等都为一个字符
{
static int pos=0;
while((definition[pos]!='\0')&&(definition[pos]==' ')){pos++;}//跳过空格
return definition[pos++];
}
int isOpNum(char ch)//判断是否是操作数
{
if(ch=='('||ch==')'||ch=='+'||ch=='-'||ch=='*'||ch=='/') {
return 0;
}
return 1;
}
int value(BiTree T){
if(T==NULL) {
return ERROR;
}
if(!isOpNum(T->data)) {
switch(T->data) {
case '+': return value(T->lchild)+value(T->rchild);break;
case '-': return value(T->lchild)-value(T->rchild);break;
case '*': return value(T->lchild)*value(T->rchild);break;
case '/': return value(T->lchild)/value(T->rchild);break;
}
}
return T->data-'0';
}
void change(char *definition)
{
char stack[100];
int top=-1;
int i = 0,len = 0;
char str[200];char que[200];
char arr[200];char tem[200];
int rear=0,front=0;
len = strlen(definition);
for(i=0;i<len;i++){
str[i]=definition[len-1-i];
if(definition[len-1-i]=='(')str[i]=')';
if(definition[len-1-i]==')')str[i]='(';
}
i=0;
while(str[i] != '\0')
{
if(str[i] == '+' || str[i] == '-')//如果str[i]是加号或减号,则先弹出栈顶直到栈已空或栈顶元素为左括号,再将str[i]压入栈
{
if(top==-1)//若栈已空时,栈顶指针为空,找不到其元素,故须单独讨论
{
stack[++top]=str[i];
}
else
{
while(stack[top] == '+' || stack[top] == '-' || stack[top] == '*' || stack[top] == '/')
{
que[++rear]=stack[top--];
}
stack[++top]=str[i];
}
}
else if(str[i] == '*' || str[i] == '/')//如果str[i]是乘号或除号,则只有栈顶也是乘除号时才需要弹出
{
if(top==-1)//若栈已空时,栈顶指针为空,找不到其元素,故须单独讨论
{
stack[++top]=str[i];
}
else
{
while(stack[top] == '*' || stack[top] == '/')
{
que[++rear]=stack[top--];
}
stack[++top]=str[i];
}
}
else if(str[i] == '(')//如果str[i]是左括号则直接压入栈
{
stack[++top]=str[i];
}
else if(str[i] == ')')//如果str[i]是右括号,则打印并弹出栈中第一个左括号前的所有操作符,最后将此左括号直接弹出
{
while(stack[top] != '(')
{
que[++rear]=stack[top--];
}
stack[top--];
}
else//如果str[i]不是操作符则直接打印
{
que[++rear]=str[i];
}
i++;
}
while(top!=-1)//遍历后如果栈不为空,则弹出所有操作符
{
que[++rear]=stack[top--];
}
for(i=0;i<=rear;i++){
definition[i]='\0';
}
for(i=0;i<rear;i++){
definition[i]=que[rear-i];
}
}
Status LevelOrderTraverse(BiTree T, Status (*visit)(TElemType e)) {//层序遍历
BiTree que[20];//创建储存树结点的队列
int front=0;
int rear=0;
int len=20;
que[0]=NULL;
if(T==NULL){
return ERROR;
}
que[++rear%len] = T;
while(front!=rear) {
if(que[front]!=NULL)
(*visit)(que[front]->data);
front=(front+1)%len;
if(que[front]->lchild!=NULL)//如果左子树不为空则入列
que[++rear%len] = que[front]->lchild;
if(que[front]->rchild!=NULL)//如果右子树不为空则入列
que[++rear%len] = que[front]->rchild;
}
(*visit)(que[rear]->data);
return SUCCESS;
}
Status Traverse(BiTree T, Status (*visit)(TElemType e)) {//非递归排序
BiTree data[20];//定义顺序栈
BiTree p;
int top=-1;//定义栈顶坐标
if(T==NULL){
printf("二叉树为空!\n");
return ERROR;
}
data[++top] = T;
while(top!=-1) {
p = data[top--];
(*visit)(p->data);
if(p->rchild) {
data[++top] = p->rchild;
}
if(p->lchild) {
data[++top] = p->lchild;
}
}
return SUCCESS;
}
void menu(){
printf("*********************************************\n");
printf("***************二叉树相关操作****************\n");
printf("*** 1.初始化二叉树 ***\n");
printf("*** 2.销毁二叉树 ***\n");
printf("*** 3.前缀表达式构造树 ***\n");
printf("*** 4.表达树求值 ***\n");
printf("*** 5.非递归遍历树 ***\n");
printf("*** 6.先序遍历 ***\n");
printf("*** 7.中序遍历 ***\n");
printf("*** 8.后序遍历 ***\n");
printf("*** 9.层序遍历 ***\n");
printf("*** 0.结束程序 ***\n");
printf("*********************************************\n");
printf("*********************************************\n");
printf("请输入选项:");
}
<file_sep>#include"../inc/qgsort.h"
#include"stdio.h"
#include"stdlib.h"
void insertSort(int *a,int n) {
int i,j,t;
for(i=1;i<n;i++) {
t = a[i];
for(j=i-1;j>=0;j--) {
if(a[j]>t)
a[j+1] = a[j];
else
break;
}
a[j+1] = t;
}
}
void MergeArray(int *a,int begin,int mid,int end,int *temp) {
int i,j,k;
i=k=begin,j=mid+1;
while(i<=mid&&j<=end) {
temp[k++] = a[i]<a[j] ? a[i++]:a[j++];
}
while(i<=mid) {
temp[k++] = a[i++];
}
while(j<=end) {
temp[k++] = a[j++];
}
for(i=begin;i<=end;i++) {
a[i]=temp[i];
}
}
void MergeSort(int *a,int begin,int end,int *temp) {
if(begin<end) {
int mid = (begin+end)/2;
MergeSort(a,begin,mid,temp);
MergeSort(a,mid+1,end,temp);
MergeArray(a,begin,mid,end,temp);
}
}
int QuickSort_Recursion(int *a, int begin, int end) {
int i,j,temp;
i=begin;j=end;temp=a[begin];
while(i<j) {
while(i<j&&a[j]>temp)
j--;
if(i<j)
a[i++] = a[j];
while(i<j&&a[i]<temp)
i++;
if(i<j)
a[j--] = a[i];
}
a[i] = temp;
return i;
}
void Partition(int *a, int begin, int end) {
if(begin<end) {
int mid=QuickSort_Recursion(a,begin,end);
Partition(a,begin,mid-1);
Partition(a,mid+1,end);
}
}
void QuickSort(int *a,long size) {
int *stack;
stack = (int *)malloc(sizeof(int)*size);
int top,begin,end,mid;
top=begin=0;end=size-1;
mid = QuickSort_Recursion(a,begin,end);
if(mid>begin+1) {
stack[top++] = begin;
stack[top++] = mid-1;
}
if(mid<end-1) {
stack[top++] = mid+1;
stack[top++] = end;
}
while(top>0) {
end = stack[--top];
begin = stack[--top];
mid = QuickSort_Recursion(a,begin,end);
if(mid>begin+1) {
stack[top++] = begin;
stack[top++] = mid-1;
}
if(mid<end-1) {
stack[top++] = mid+1;
stack[top++] = end;
}
}
}
void CountSort(int *a, long size , int max) {
int *temp1,*temp2;
int i,j,k;
temp1 = (int *)malloc(sizeof(int)*(max+1));
temp2 = (int *)malloc(sizeof(int)*size);
for(i=0;i<=max;i++) temp1[i]=0;
for(i=0;i<size;i++) temp1[a[i]]++;
for(i=1;i<=max;i++) {
temp1[i]+=temp1[i-1];
}
i=size-1;
for(i;i>=0;i--) {
temp2[--temp1[a[i]]]=a[i];
}
for(i=0;i<size;i++)
a[i] = temp2[i];
}
void RadixCountSort(int *a,int size) {
int *temp1,*temp2;
int radix = 10;
int count = 1;
int i,j,k,n;
temp1 = (int *)malloc(sizeof(int)*(radix));//存放各个桶的元素个数,共10个桶
temp2 = (int *)malloc(sizeof(int)*size);//定义暂存元素数组temp2
n = 1;//记录基位
while(count<6) {
for(i=0;i<radix;i++) temp1[i]=0;
for(i=0;i<size;i++) {
k = (a[i]/n)%10;
temp1[k]++;
}
for(i=radix-1;i>=0;i--) {
if(i>0) {
for(j=i-1;j>=0;j--) {
temp1[i] = temp1[i] + temp1[j];//统计小于等于该元素的个数
}
}
}
i=size-1;
for(i;i>=0;i--) {
k = (a[i]/n)%10;
temp2[--temp1[k]]=a[i];
}
for(i=0;i<size;i++)
a[i] = temp2[i];
n*=10;
count++;
}
}
void ColorSort(int *a,int size) {
int front,post,i,t;
front = 0;
post = size-1;
for(i=0;i<=post;i++) {
if(a[i]==2) {
t = a[i];
a[i] = a[post];
a[post] = t;
post--;
}
if(a[i]==0) {
t = a[i];
a[i] = a[front];
a[front] = t;
front++;
if(a[i]==2) {
t = a[i];
a[i] = a[post];
a[post] = t;
post--;
}
}
}
}
int FindSort(int *a,int begin,int end,int k){
int index;
if(begin==end) return a[begin];
int par = QuickSort_Recursion(a,begin,end);
index = end-par+1;
if(index==k) {
return a[par];
}else if(index<k) {
return FindSort(a,begin,par-1,k-index);
}else{
return FindSort(a,par+1,end,k);
}
}
void CreateArray(int *a,int num1) {
int i;
a[0] = 40000;
for(i=1;i<num1;i++) {
a[i] = rand();
}
}
<file_sep>#include"../inc/qgsort.h"
#include"stdio.h"
#include"stdlib.h"
#include"time.h"
void main()
{
char n[100];
int **a;
int temp[100];
int i,j,max=40000;
long num1;
clock_t start,time[6];
while(1) {
time[3]=0;
printf("输入随机数组数量:");
scanf("%ld",&num1);
gets(n);
a = (int **)malloc(sizeof(int *)*num1);
for(i=0;i<num1;i++) {
a[i] = (int *)malloc(sizeof(int)*100);
}
CreateArray(a,num1);
start = clock();
for(i=0;i<num1;i++)
insertSort(a[i],100);
time[0] = clock() - start;
CreateArray(a,num1);
start = clock();
for(i=0;i<num1;i++)
MergeSort(a[i],0,99,temp);
time[1] = clock() - start;
CreateArray(a,num1);
start = clock();
for(i=0;i<num1;i++)
Partition(a[i],0,99);
time[2] = clock() - start;
CreateArray(a,num1);
for(i=0;i<num1;i++) {
start = clock();
CountSort(a[i],100,max);
time[3] = time[3]+(clock() - start);
}
CreateArray(a,num1);
start = clock();
for(i=0;i<num1;i++)
RadixCountSort(a[i],100);
time[4] = clock() - start;
CreateArray(a,num1);
start = clock();
for(i=0;i<num1;i++)
QuickSort(a[i],100);
time[5] = clock() - start;
printf("- - - - - - - - - - - - - - - - 排序时间(单位:ms)- - - - - - - - - - - - - - - - -\n");
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf("| + 插入 + | + 归并 + | + 快排 + | + 快排(非递归) + | + 计数 + | + 基数 + |\n");
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf("| + %d + | + %d + | + %d + | + %d + | + %d + | + %d + |\n",time[0],time[1],time[2],time[5],time[3],time[4]);
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf("输入0返回,输入1结束程序\n");
while(1) {
gets(n);
if(n[0]=='0') break;
if(n[0]=='1') exit(0);
printf("输入错误,请再次输入:");
}
system("cls");
}
}
<file_sep>#include "..\代码和头文件\calculator.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{ while(1) {
char enter[100],a[100],b[100][100],c;
SqStack *s;SqStack1 *t;
int i,j=0,k,h=0,flag=1,num;float k1=0,k2=0,temp=0,semp=0.1;
s=(SqStack *)malloc(sizeof(SqStack));
t=(SqStack1 *)malloc(sizeof(SqStack1));
t->size=s->size=100;
initStack(s,s->size);
initStack1(t,t->size);
printf("**********************************\n");
printf("* 四则运算计算器 *\n");
printf("**********************************\n");
printf("请输入前缀表达式:");
gets(a);
if(chnum(a[0])==0) {
system("cls");
printf("输入错误\n");
continue;
}
for(i=0;a[i]!='\0';i++) {
if(a[i]>='0'&&a[i]<='9') {
b[j][h++]=a[i];
}
if(a[i]=='.') {
b[j][h++]=a[i];
}
if((chnum(a[i])!=1)&&(chnum(a[i])!=0)) {
if(chnum(a[i-1])==1&&s->top==-1) j++;h=0;
if(!isEmptyStack(s)) {
pushStack(s,a[i]);
}
else {
if(a[i]=='(') {
pushStack(s,a[i]);
}
else if(a[i]==')') {
for(k=s->top;k>-1;k--) {
popStack(s,&c);
if(chnum(c)!=4) {
b[++j][0]=c;
}
if(c=='(') break;
}
}
else {
for(k=s->top;k>-1;k--) {
if(!isEmptyStack(s))
break;
if(chnum(a[i])<=chnum(s->elem[s->top])&&chnum(s->elem[s->top])!=4) {
popStack(s,&c);
b[++j][0]=c;
}
if(chnum(a[i])>chnum(s->elem[s->top])||chnum(s->elem[s->top]==4))
break;
}
pushStack(s,a[i]);j++;
}
}
}
}
for(i=s->top;i>-1;i--) {
popStack(s,&c);
b[++j][0]=c;
}
printf("后缀表达式为:");
for(i=0;i<=j;i++) {
printf("%s ",b[i]);
}
for(i=0;i<=j;i++) {
if(chnum(b[i][0])!=1) {
switch(b[i][0]) {
case '+':
k1=(t->elem1[t->top-1])+(t->elem1[t->top]);
popStack1(t,&k2);
popStack1(t,&k2);
pushStack1(t,k1);
break;
case '-':
k1=(t->elem1[t->top-1])-(t->elem1[t->top]);
popStack1(t,&k2);
popStack1(t,&k2);
pushStack1(t,k1);
break;
case '*':
k1=(t->elem1[t->top-1])*(t->elem1[t->top]);
popStack1(t,&k2);
popStack1(t,&k2);
pushStack1(t,k1);
break;
case '/':
k1=(t->elem1[t->top-1]/t->elem1[t->top]);
popStack1(t,&k2);
popStack1(t,&k2);
pushStack1(t,k1);
break;
}
}
else {
for(k=0;k<strlen(b[i]);k++) {
if(b[i][k-1]=='.') flag=0;
if(flag&&b[i][k]!='.')
temp=temp*10+b[i][k]-'0';
if(flag==0) {
temp=temp+semp*(b[i][k]-'0');
semp/=10;
}
}
pushStack1(t,temp);
temp=0,semp=0.1,flag=1;
}
}
popStack1(t,&k1);
printf("\n结果为=%f",k1);
printf("\n输入1重置,输入0结束程序:\n");
while(1) {
gets(enter);
num=enter[0]-'0';
if(enter[0]=='0')
exit(0);
if(enter[0]=='1') {
system("cls");
break;
}
printf("输入错误!请再次输入:");
}
}
}
<file_sep>#include"../inc/qgsort.h"
#include"stdio.h"
#include"stdlib.h"
#include"time.h"
void main()
{
FILE *fp;
int num;
int *a,*temp;
long i,n,enter;//n为数据的个数,也是存储数据的数组长度
char path[100],inp[100];
clock_t start,time[6];
while(1) {
while(1) {
printf("请输入生成测试数据的文件路径:");
gets(path);
fp = fopen(path,"r");
if(fp==NULL) {
system("cls");
printf("文件不存在!\n");
}
else break;
}
for(n=1;n<1000000;n++) {
fscanf(fp,"%d",&num);
if(num==0) {
n-=1;
break;
}
num = 0;
}
close(fp);
fp = fopen(path,"r");
a = (int *)malloc(sizeof(int)*n);
for(i=0;i<n;i++) {
fscanf(fp,"%d",&a[i]);
}
close(fp);
printf("文件的数据已读取成功哦\n");
printf("*********************************************\n");
printf("************请选择那种方法排序***************\n");
printf("*** 1.插入排序 ***\n");
printf("*** 2.归并排序 ***\n");
printf("*** 3.快速排序 ***\n");
printf("*** 4.快速排序(非递归) ***\n");
printf("*** 5.计数排序 ***\n");
printf("*** 6.基数排序 ***\n");
printf("*** 0.结束程序 ***\n");
printf("*********************************************\n");
printf("*********************************************\n");
printf("请输入选项:");
while(1) {
gets(inp);
if(inp[0]>='0'&&inp[0]<='6') {
enter=inp[0]-'0';
break;
}
printf("输入错误,请再次输入:");
}
system("cls");
switch(enter) {
case 1:
start = clock();
insertSort(a,n);
time[0] = clock() - start;
break;
case 2:
temp = (int *)malloc(sizeof(int)*n);
start = clock();
MergeSort(a,0,n-1,temp);
time[1] = clock() - start;
break;
case 3:
start = clock();
Partition(a,0,n-1);
time[2] = clock() - start;
break;
case 4:
start = clock();
QuickSort(a,n);
time[3] = clock()-start;
break;
case 5:
start = clock();
CountSort(a,n,40000);
time[4] = clock()-start;
break;
case 6:
start = clock();
RadixCountSort(a,n);
time[5] = clock()-start;
break;
case 0:
exit(0);
}
system("cls");
fp = fopen(path,"w");
for(i=0;i<n;i++) fprintf(fp,"%d ",a[i]);
close(fp);
printf("- - - - - - - 排序成功 - - - - - - -\n");
printf("| + 排序用时: %dms + |\n",time[enter-1]);
printf("- - - - - - - - - - - - - - - - - -\n");
printf("输入1读取新文件\n");
printf("输入0则结束程序\n");
while(1) {
gets(inp);
if(inp[0]=='1') break;
if(inp[0]=='0') exit(0);
printf("输入错误,请再次输入:");
}
system("cls");
}
}
<file_sep>#include"../head/SqStack.h"
#include<stdio.h>
#include<stdlib.h>
Status initStack(SqStack *s,int sizes) {
s->top = -1;
s->elem = (ElemType*)malloc(sizeof(ElemType)*sizes);
return SUCCESS;
}
Status isEmptyStack(SqStack *s) {
if(s->top==-1) {
printf("栈为空!\n");
return ERROR;
}
printf("栈不为空!\n");
return SUCCESS;
}
Status getTopStack(SqStack *s,ElemType *e) {
if(s->top==-1) {
printf("栈为空!\n");
return ERROR;
}
else {
*e = s->elem[s->top];
printf("获取栈顶元素成功!\n");
printf("栈顶元素为%d\n",*e);
return SUCCESS;
}
}
Status clearStack(SqStack *s) {
s->top = -1;
return SUCCESS;
}
Status destroyStack(SqStack *s) {
int i;
for(i=s->top;i>-1;i--) {
free(s->elem+i);
}
s->top=-1;
return SUCCESS;
}
Status stackLength(SqStack *s,int *length) {
*length = s->top+1;
return SUCCESS;
}
Status pushStack(SqStack *s,ElemType data) {
if((s->top+1)==s->size) {
printf("栈已满!\n");
}
s->elem[++s->top] = data;
printf("入栈成功!\n");
return SUCCESS;
}
Status popStack(SqStack *s,ElemType *data) {
if(s->top==-1) {
printf("栈为空!\n");
return ERROR;
}
*data = s->elem[s->top--];
printf("出栈成功!\n");
return SUCCESS;
}
Status TraverseStack(SqStack *s) {
int i;
if (s->top==-1)
return ERROR;
for(i=s->top;i>-1;i--) {
printf("%d ",s->elem[i]);
}
return SUCCESS;
}
int chnum(char *str) {
int i,n,num=0;
for(i=0;str[i]!='\0';i++){
if(str[i]>='0'&&str[i]<='9') {
num=num*10+str[i]-'0';
}
}
return num;
}
<file_sep>#include "../head/linkedList.h"
#include<stdio.h>
#include<stdlib.h>
void main()
{
int num,i,n,m;
char str[100],str1[100];ElemType e;
LinkedList L=NULL,q,p;
while(1) {
printf("-----------单向链表的基本操作-----------\n");
printf("| 1.创建链表 |\n");
printf("| 2.销毁链表 |\n");
printf("| 3.插入节点 |\n");
printf("| 4.删除节点 |\n");
printf("| 5.遍历链表 |\n");
printf("| 6.搜寻节点 |\n");
printf("| 7.反转链表 |\n");
printf("| 8.判断环形 |\n");
printf("| 9.偶数反转 |\n");
printf("| 10.寻找中点 |\n");
printf("| 0.退出程序 |\n");
printf("----------------------------------------\n");
printf("提醒:请输入0~9,否则自动退出程序!\n");
printf("请输入要执行的操作前的选项:");
while(1) {
scanf("%d",&num);
if(num>=0&&num<=10)break;
printf("输入错误,请再次输入:");
}
switch(num)
{
case 1:
InitList(&L);CreateList(&L);
system("cls");
printf("创建链表成功!\n");
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
system("cls");
if(!L) {
printf("链表为空!\n");
}
else {
DestroyList(&L);
printf("销毁链表成功!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
system("cls");
if(!L)
printf("链表为空!\n");
else {
q=(LNode *)malloc(sizeof(LNode));
printf("请输入插入节点的数据:");
gets(str1);
gets(str);
q->data=chnum(str);
printf("请输入插入到第几个节点后面:");
scanf("%d",&m);
p=L->next;i=0;
while(p) {
i++;
if(i==m){
if(InsertList(p,q)) {
printf("插入节点成功!\n");break;
}
}
p=p->next;
}
if(i<m||m<0)
printf("插入节点失败!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
system("cls");
if(!L)
printf("链表为空!\n");
else {
printf("删除第几个节点后的第一个节点:");
scanf("%d",&m);
p=L->next;i=0;
while(p) {
i++;
if(i==m){
if(DeleteList(p,&e)) {
printf("删除节点成功!\n");break;
}
else {
printf("删除节点失败!\n");break;
}
}
p=p->next;
}
if(m<0||m>i) printf("删除节点失败!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
if(!L)
printf("链表为空!\n");
else {
system("cls");
printf("链表数据为:\n");
TraverseList(L,visit);
}
printf("\n输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
system("cls");
if(!L)
printf("链表为空!\n");
else {
printf("请输入节点含有的数据:");
scanf("%d",&e);
if(SearchList(L,e))
printf("存在该节点!\n");
else
printf("不存在该节点!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 7:
system("cls");
if(!L)
printf("链表为空!\n");
else {
ReverseList(&L);
printf("链表反转成功!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 8:
system("cls");
if(!L)
printf("链表为空!\n");
else {
if(IsLoopList(L)) {
printf("该链表是循环链表\n");
}
else {
printf("该链表不是循环链表\n");
}
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 9:
system("cls");
if(!L)
printf("链表为空!\n");
else {
ReverseEvenList(&L);
printf("偶数反转成功!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 10:
system("cls");
if(!L)
printf("链表为空!\n");
else {
printf("中点节点数据为:%d\n",FindMidNode(&L)->data);
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);break;
}
}
}
<file_sep>#include"../AQueue/AQueue.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
void *e=NULL;
char a[100],b4[100],b2;
double b1;
int flag=1,data=0,num,Judge,len,b3;
AQueue *Q;
Q=(AQueue *)malloc(sizeof(AQueue));
Q->data[0]=NULL;
while(1) {
printf("****************************************************************\n");
printf("* *\n");
printf("*****************数据结构之循环队列程序设计*********************\n");
printf("* *\n");
printf("***************作者:梁德钊(3119005103)软工三班******************\n");
printf("* 1.初始化队列 *\n");
printf("* 2.销毁队列 *\n");
printf("* 3.检查队列是否已满 *\n");
printf("* 4.检查队列是否为空 *\n");
printf("* 5.查看队头元素 *\n");
printf("* 6.确定队列长度 *\n");
printf("* 7.入队操作 *\n");
printf("* 8.出队操作 *\n");
printf("* 9.清空队列 *\n");
printf("* 10.遍历队列 *\n");
printf("* 0.退出程序 *\n");
printf("****************************************************************\n");
printf("请输入要执行的操作前的选项:");
while(1) {
gets(a);
if(a[0]=='1'&&a[1]=='0') {
num=10;
break;
}
if(a[0]>='0'&&a[0]<='9') {
num=a[0]-'0';
break;
}
printf("输入错误,请再次输入:");
}
switch(num){
case 1:
system("cls");
printf("*********************\n");
InitAQueue(Q);
Q->data[0]=&data;
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
system("cls");
printf("*********************\n");
DestoryAQueue(Q);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
system("cls");
printf("*********************\n");
Judge=IsFullAQueue(Q);
if(Judge==TRUE)
printf("队列已满/n");
if(Judge==FALSE)
printf("队列未满\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
system("cls");
printf("*********************\n");
Judge=IsEmptyAQueue(Q);
if(Judge==TRUE)
printf("队列为空\n");
if(Judge==FALSE)
printf("队列非空\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
system("cls");
printf("*********************\n");
e=(void *)malloc(20);
if(GetHeadAQueue(Q,e))
APrint(e,datatype[Q->front]);
printf("\n*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
system("cls");
printf("*********************\n");
len=LengthAQueue(Q);
if(len!=-1)
printf("队列长度为%d\n",len);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 7:
system("cls");
printf("************************\n");
printf("请选择入队元素的数据类型\n");
printf("************************\n");
printf("* 1.double 2.char *\n");
printf("* 3.int 4.string *\n");
printf("************************\n");
printf("请输入选项:");
while(1) {
gets(a);
if(a[0]>='1'&&a[0]<='4') break;
printf("输入错误,请再次输入:");
}
num=a[0]-'0';
switch(num){
case 1:
printf("请输入元素:");
scanf("%lf",&b1);
if(!EnAQueue(Q,&b1))
break;
datatype[Q->rear]='d';
break;
case 2:
printf("请输入元素:");
scanf("%c",&b2);
if(!EnAQueue(Q,&b2))
break;
datatype[Q->rear]='c';
break;
case 3:
printf("请输入元素:");
scanf("%d",&b3);
if(!EnAQueue(Q,&b3))
break;
datatype[Q->rear]='i';
break;
case 4:
printf("请输入元素:");
scanf("%s",b4);
if(!EnAQueue(Q,b4))
break;
datatype[Q->rear]='s';
break;
}
gets(a);
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 8:
system("cls");
printf("*********************\n");
DeAQueue(Q);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 9:
system("cls");
printf("*********************\n");
ClearAQueue(Q);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 10:
system("cls");
printf("*********************\n");
TraverseAQueue(Q,APrint);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);break;
}
}
}
<file_sep># QG训练营后台组第二周周记:
2020年4月5日
## 生活随记
这周时间太紧凑了,有点忙活不过来,心好累,写的代码BUG又多,又不知道哪里错了,所以进度好慢,匆匆忙忙完成大组作业又要补课内的作业了,这周也没时间去打球,略感遗憾。最近天气转冷了,写作业和打代码都瑟瑟发抖。
## 一周总结
掌握了栈的应用和栈的基本操作,完成四则运算计算器的实现,最近也一直在学Java。
## 存在问题
1.在编写四则运算计算器的时候,虽然能够实现四则运算和小数的计算,但是自己写的代码杂糅,还需要深入理解逆波兰表达式,再看看别人是如何编写的,来完善自己写的代码。
2.学习进度慢,无论是完成作业或者学新知识,花的时间都有点长,需要改进自己的学习习惯。
3.注意力不够集中,代码的BUG很多,需要改很久。
## 下周规划
1.完成小组作业
2.跟上后台训练营的学习进度
<file_sep>#include "..\代码和头文件\calculator.h"
#include<stdio.h>
#include<stdlib.h>
Status initStack(SqStack *s,int sizes) {
s->top = -1;
s->elem = (ElemType *)malloc(sizeof(ElemType)*sizes);
return SUCCESS;
}
Status initStack1(SqStack1 *s,int sizes) {
s->top = -1;
s->elem1 = (float *)malloc(sizeof(float)*sizes);
return SUCCESS;
}
Status destroyStack(SqStack *s) {
int i;
for(i=s->top;i>-1;i--) {
free(s->elem+i);
}
s->top=-1;
return SUCCESS;
}
Status isEmptyStack(SqStack *s) {
if(s->top==-1) {
return ERROR;
}
return SUCCESS;
}
Status pushStack(SqStack *s,ElemType data) {
if((s->top+1)==s->size) {
printf("栈已满!\n");
}
s->elem[++s->top] = data;
return SUCCESS;
}
Status popStack(SqStack *s,ElemType *data) {
if(s->top==-1) {
return ERROR;
}
*data = s->elem[s->top--];
return SUCCESS;
}
Status pushStack1(SqStack1 *s,float data) {
if((s->top+1)==s->size) {
printf("栈已满!\n");
}
s->elem1[++s->top] = data;
return SUCCESS;
}
Status popStack1(SqStack1 *s,float *data) {
if(s->top==-1) {
return ERROR;
}
*data = s->elem1[s->top--];
return SUCCESS;
}
int chnum(char a) {
if(a=='('||a==')')
return 4;
if(a=='*'||a=='/')
return 3;
if(a=='+'||a=='-')
return 2;
if(a>='0'&&a<='9')
return 1;
return 0;
}
<file_sep>#ifndef TREE_H_INCLUDED
#define TREE_H_INCLUDED
typedef char TElemType; // 假设二叉树结点的元素类型为字符
typedef struct BiTNode {
TElemType data; // 数据域
struct BiTNode *lchild,*rchild; // 左、右孩子指针
} BiTNode,*BiTree; // 二叉链表
typedef struct LinkStack//链式栈
{
BiTree top;
}LinkStack;
typedef enum Status{
ERROR,
SUCCESS
}Status;
Status InitBiTree(BiTree *T);
//操作结果:构造空二叉树T
Status DestroyBiTree(BiTree *T);
//初始条件:二叉树T存在
//操作结果:摧毁二叉树T
Status CreateBiTree(BiTree *T, char* definition);
//初始条件: definition给出二叉树的定义
//操作结果:按definition构造二叉树T
//以下部分函数定义未指定参数类型
Status PreOrderTraverse(BiTree T, Status (*visit)(TElemType e));//先序遍历
//初始条件:二叉树T存在,visit为对结点的操作的应用函数
//操作结果:先序遍历T,对每个结点调用visit函数一次且仅一次,一旦visit失败,则操作失败
Status InOrderTraverse(BiTree T, Status (*visit)(TElemType e)); //中序遍历
Status PostOrderTraverse(BiTree T, Status (*visit)(TElemType e)); //后序遍历
Status LevelOrderTraverse(BiTree T, Status (*visit)(TElemType e)); //层序遍历
int Value(BiTree T); //构造出的二叉树求值
Status visit(TElemType e); //打印元素值
char nextToken(char *definition);//跳过空格
int isOpNum(char ch);//判断是否是操作数
void change(char *definition);//中缀表达式转前缀表达式
Status Traverse(BiTree T, Status (*visit)(TElemType e));//非递归遍历二叉树
void menu();
/*
提示:可在结点结构体中设置个Tag值标志数字与操作符来构造二叉树,
可根据需要自行增加操作.
*/
#endif
<file_sep>#include"../LQueue/LQueue.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void main()
{
void *e=NULL;
char a[100],b4[100],b2;
double b1;
int data=0,num,Judge,len,b3;
LQueue *Q;
Q=(LQueue *)malloc(sizeof(LQueue));
Q->front=NULL;
while(1) {
printf("****************************************************************\n");
printf("* *\n");
printf("*****************数据结构之链式队列程序设计*********************\n");
printf("* *\n");
printf("***************作者:梁德钊(3119005103)软工三班******************\n");
printf("* 1.初始化队列 *\n");
printf("* 2.销毁队列 *\n");
printf("* 3.检查队列是否为空 *\n");
printf("* 4.查看队头元素 *\n");
printf("* 5.确定队列长度 *\n");
printf("* 6.入队操作 *\n");
printf("* 7.出队操作 *\n");
printf("* 8.清空队列 *\n");
printf("* 9.遍历队列 *\n");
printf("* 0.退出程序 *\n");
printf("****************************************************************\n");
printf("请输入要执行的操作前的选项:");
while(1) {
gets(a);
if(a[0]>='0'&&a[0]<='9') {
num=a[0]-'0';
break;
}
printf("输入错误,请再次输入:");
}
switch(num){
case 1:
system("cls");
printf("*********************\n");
InitLQueue(Q);
Q->front->data=(void *)malloc(20);
Q->front->data=&data;
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
system("cls");
printf("*********************\n");
DestoryLQueue(Q);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
system("cls");
printf("*********************\n");
Judge=IsEmptyLQueue(Q);
if(Judge==TRUE)
printf("队列为空\n");
if(Judge==FALSE)
printf("队列非空\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
system("cls");
printf("*********************\n");
e=(void *)malloc(20);
if(GetHeadLQueue(Q,e))
printf("队头元素为:\n");
LPrint(e,Q->front->datatype);
free(e);
printf("\n*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
system("cls");
printf("*********************\n");
len=LengthLQueue(Q);
if(len!=FALSE)
printf("队列长度为%d\n",len);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
system("cls");
printf("************************\n");
printf("请选择入队元素的数据类型\n");
printf("************************\n");
printf("* 1.double 2.char *\n");
printf("* 3.int 4.string *\n");
printf("************************\n");
printf("请输入选项:");
while(1) {
gets(a);
if(a[0]>='1'&&a[0]<='4') break;
printf("输入错误,请再次输入:");
}
num=a[0]-'0';
switch(num){
case 1:
printf("请输入元素:");
scanf("%lf",&b1);
if(!EnLQueue(Q,&b1))
break;
Q->rear->datatype='d';
break;
case 2:
printf("请输入元素:");
scanf("%c",&b2);
if(!EnLQueue(Q,&b2))
break;
Q->rear->datatype='c';
break;
case 3:
printf("请输入元素:");
scanf("%d",&b3);
if(!EnLQueue(Q,&b3))
break;
Q->rear->datatype='i';
break;
case 4:
printf("请输入元素:");
scanf("%s",b4);
if(!EnLQueue(Q,b4))
break;
Q->rear->datatype='s';
break;
}
gets(a);
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 7:
system("cls");
printf("*********************\n");
DeLQueue(Q);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 8:
system("cls");
printf("*********************\n");
ClearLQueue(Q);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 9:
system("cls");
printf("*********************\n");
TraverseLQueue(Q,LPrint);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);break;
}
}
}
<file_sep>#include"../inc/qgsort.h"
#include"stdio.h"
#include"stdlib.h"
#include"time.h"
void main()
{
char n[100];
int a[10000],b[50000],c[200000];
int *temp1,*temp2,*temp3;
int i,max,num;
clock_t start,time[6];
while(1) {
printf("---------------------------------------------\n");
printf("-------------请选择测试数据个数--------------\n");
printf("*1.10000 2.50000 3.200000 0.结束程序*\n");
printf("---------------------------------------------\n");
printf("---------------------------------------------\n");
printf("请输入选项:");
while(1) {
gets(n);
if(n[0]>='0'&&n[0]<='3') {
num=n[0]-'0';
break;
}
printf("输入错误,请再次输入:");
}
system("cls");
CreateArray(a,10000);
CreateArray(b,50000);
CreateArray(c,200000);
switch(num) {
case 1:
max = a[0];
temp1 = (int *)malloc(sizeof(int)*10000);
printf("排序中,请耐心等待...............\n");
start=clock(); insertSort(a,10000); time[0]=clock()-start; CreateArray(a,10000);
start=clock(); MergeSort(a,0,9999,temp1); time[1]=clock()-start; CreateArray(a,10000);
start=clock(); Partition(a,0,9999); time[2]=clock()-start; CreateArray(a,10000);
start=clock(); QuickSort(a,10000); time[3]=clock()-start; CreateArray(a,10000);
start=clock(); CountSort(a,10000,max); time[4]=clock()-start; CreateArray(a,10000);
start=clock(); RadixCountSort(a,10000); time[5]=clock()-start;
free(temp1);
break;
case 2:
max = b[0];
temp2 = (int *)malloc(sizeof(int)*50000);
for(i=0;i<50000;i++) {
if(b[i]>max) max = b[i];
}
printf("排序中,请耐心等待...............\n");
start=clock(); insertSort(b,50000); time[0]=clock()-start; CreateArray(b,50000);
start=clock(); MergeSort(b,0,49999,temp2); time[1]=clock()-start; CreateArray(b,50000);
start=clock(); Partition(b,0,49999); time[2]=clock()-start; CreateArray(b,50000);
start=clock(); QuickSort(b,50000); time[3]=clock()-start; CreateArray(b,50000);
start=clock(); CountSort(b,50000,max); time[4]=clock()-start; CreateArray(b,50000);
start=clock(); RadixCountSort(b,50000); time[5]=clock()-start;
free(temp2);
break;
case 3:
max = c[0];
temp3 = (int *)malloc(sizeof(int)*200000);
printf("排序中,请耐心等待...............\n");
start=clock(); insertSort(c,200000); time[0]=clock()-start; CreateArray(c,200000);
start=clock(); MergeSort(c,0,199999,temp3);time[1]=clock()-start; CreateArray(c,200000);
start=clock(); Partition(c,0,19999); time[2]=clock()-start; CreateArray(c,200000);
start=clock(); QuickSort(c,200000); time[3]=clock()-start; CreateArray(c,200000);
start=clock(); CountSort(c,200000,max); time[4]=clock()-start; CreateArray(c,200000);
start=clock(); RadixCountSort(c,200000); time[5]=clock()-start;
free(temp3);
break;
case 0:
exit(0);
}
printf("- - - - - - - - - - - - - - - - 排序时间(单位:ms)- - - - - - - - - - - - - - - - -\n");
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf("| + 插入 + | + 归并 + | + 快排 + | + 快排(非递归) + | + 计数 + | + 基数 + |\n");
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf("| + %d + | + %d + | + %d + | + %d + | + %d + | + %d + |\n",time[0],time[1],time[2],time[3],time[4],time[5]);
printf("- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -\n");
printf("输入0返回上一层:");
while(1) {
gets(n);
if(n[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
}
}
<file_sep>#include"../LQueue/LQueue.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void InitLQueue(LQueue *Q) {
Node *p;
p = (Node *)malloc(sizeof(Node));
if (NULL == p)
return;
p->datatype='i';
p->next = NULL;
Q->front = p;
Q->rear = p;
printf("队列初始化成功!\n");
return;
}
void DestoryLQueue(LQueue *Q) {
Node *p;
if(Q->front==NULL) {
printf("队列未初始化!\n");
return;
}
ClearLQueue(Q);
p=Q->front;
Q->front=Q->rear=NULL;
free(p);
printf("队列销毁成功!\n");
}
Status IsEmptyLQueue(const LQueue *Q) {
if(Q->front==NULL) {
printf("队列未初始化!\n");
return -1;
}
return Q->rear==Q->front ? TRUE:FALSE;
}
Status GetHeadLQueue(LQueue *Q, void *e) {
int flag;
flag=IsEmptyLQueue(Q);
if(flag==-1) return FALSE;
memcpy(e,Q->front->data,20);
printf("获取头元素成功!\n");
return TRUE;
}
int LengthLQueue(LQueue *Q) {
Node *p;
int len=1;
if(IsEmptyLQueue(Q)==-1)
return FALSE;
p=Q->front;
while(p!=Q->rear) {
p=p->next;
len++;
}
return len;
}
Status EnLQueue(LQueue *Q, void *data) {
Node *p;
p=(Node *)malloc(sizeof(Node));
if(Q->front==NULL) {
printf("队列未初始化!\n");
return FALSE;
}
if(p==NULL)
return FALSE;
p->data=(void *)malloc(20);
memcpy(p->data,data,20);
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
return TRUE;
}
Status DeLQueue(LQueue *Q) {
int flag;
Node *p;
flag=IsEmptyLQueue(Q);
if(flag==-1) return FALSE;
if(flag==TRUE) {
printf("队列为空!\n");
return FALSE;
}
p=Q->front;
Q->front=Q->front->next;
p->next=NULL;
free(p);
printf("出队成功!\n");
return TRUE;
}
void ClearLQueue(LQueue *Q) {
Node *p,*q;
if(Q->front==NULL) {
printf("队列未初始化!\n");
return;
}
Q->rear=Q->front;
p=Q->front->next;
while(p!=NULL) {
q=p;
p=p->next;
free(q);
}
Q->front->next=NULL;
printf("队列已清空!\n");
return;
}
Status TraverseLQueue(const LQueue *Q, void (*foo)(void *q,char type)) {
int flag;
Node *p;
flag=IsEmptyLQueue(Q);
if(flag==-1) return FALSE;
p=Q->front;
while(p) {
foo(p->data,p->datatype);
p=p->next;
}
printf("\n");
return TRUE;
}
void LPrint(void *q,char type) {
if(type=='d')
printf("-->%lf",*(double *)q);
else if(type=='c')
printf("-->%c",*(char *)q);
else if(type=='i')
printf("-->%d",*(int *)q);
else if(type=='s')
printf("-->%s",(char *)q);
}
<file_sep>#include "../head/duLinkedList.h"
#include<stdio.h>
#include<stdlib.h>
void main()
{
int num,i,n,m;
char str[100],str1[100];ElemType e;
DuLinkedList L=NULL,q,p;
while(1) {
printf("-----------双向链表的基本操作-----------\n");
printf("| 1.创建链表 |\n");
printf("| 2.销毁链表 |\n");
printf("| 3.插前节点 |\n");
printf("| 4.插后节点 |\n");
printf("| 5.删除节点 |\n");
printf("| 6.遍历链表 |\n");
printf("| 0.退出程序 |\n");
printf("----------------------------------------\n");
printf("提醒:请输入0~9,否则自动退出程序!\n");
printf("请输入要执行的操作前的选项:");
while(1) {
scanf("%d",&num);
if(num>=0&&num<=10)break;
printf("输入错误,请再次输入:");
}
switch(num)
{
case 1:
InitList_DuL(&L);CreateList_DuL(&L);
system("cls");
printf("创建链表成功!\n");
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
system("cls");
if(!L) {
printf("链表为空!\n");
}
else {
DestroyList_DuL(&L);
printf("销毁链表成功!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
system("cls");
if(!L)
printf("链表为空!\n");
else {
q=(DuLNode *)malloc(sizeof(DuLNode));
printf("请输入插入节点的数据:");
gets(str1);
gets(str);
q->data=chnum(str);
printf("请输入插入到第几个节点的前面:");
scanf("%d",&m);
p=L->next;i=0;
while(p) {
i++;
if(i==m){
if(InsertBeforeList_DuL(p,q)) {
printf("插入节点成功!\n");break;
}
}
p=p->next;
}
if(i<m||m<0) printf("插入节点失败!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
system("cls");
if(!L)
printf("链表为空!\n");
else {
q=(DuLNode *)malloc(sizeof(DuLNode));
printf("请输入插入节点的数据:");
gets(str1);
gets(str);
q->data=chnum(str);
printf("请输入插入到第几个节点后面:");
scanf("%d",&m);
p=L->next;i=0;
while(p) {
i++;
if(i==m){
if(InsertAfterList_DuL(p,q)) {
printf("插入节点成功!\n");break;
}
}
p=p->next;
}
if(i<m||m<0) printf("插入节点失败!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
system("cls");
if(!L)
printf("链表为空!\n");
else {
printf("删除第几个节点后的第一个节点:");
scanf("%d",&m);
p=L->next;i=0;
while(p) {
i++;
if(i==m){
if(DeleteList_DuL(p,&e)) {
printf("删除节点成功!\n");break;
}
else {
printf("删除节点失败!\n");break;
}
}
p=p->next;
}
if(m<0||m>i) printf("删除节点失败!\n");
}
printf("输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
if(!L)
printf("链表为空!\n");
else {
system("cls");
printf("链表数据为:\n");
TraverseList_DuL(L,visit);
}
printf("\n输入0返回上一层:");
while(1) {
scanf("%d",&n);
if(n==0) break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);break;
}
}
}
<file_sep>#include "../head/linkedList.h"
#include<stdio.h>
#include<stdlib.h>
/**
* @name : Status InitList(LinkList *L);
* @description : initialize an empty linked list with only the head node without value
* @param : L(the head node)
* @return : Status
* @notice : None
*/
Status InitList(LinkedList *L) {
*L=(LinkedList)malloc(sizeof(LNode));
if(!(*L))
return ERROR;
(*L)->next=NULL;
return SUCCESS;
}
/**
* @name : Status CreateList(LinkList *L);
* @description : Create a linked list with data
* @param : L(the head node)
* @return : Status
* @notice : None
*/
Status CreateList(LinkedList *L) {
int n=0;
char str[100],str1[100],end[3]="end";
LNode *p1,*p2;
p1=p2=(LNode *)malloc(sizeof(LNode));
printf("请输入节点的数据,输入end结束\n->");
gets(str1);
gets(str);
p1->data=chnum(str);
while(strcmp(str,end)) {
n++;
if(n==1)(*L)->next=p1;
else
p2->next=p1;
p2=p1;
printf("->");
p1=(LNode *)malloc(sizeof(LNode));
gets(str);
p1->data=chnum(str);
}
p2->next=NULL;
return SUCCESS;
}
/**
* @name : void DestroyList(LinkedList *L)
* @description : destroy a linked list, free all the nodes
* @param : L(the head node)
* @return : None
* @notice : None
*/
void DestroyList(LinkedList *L) {
LNode *p;
while(*L) {
p=(*L);
(*L)=(*L)->next;
free(p);
}
*L=NULL;
}
/**
* @name : Status InsertList(LNode *p, LNode *q)
* @description : insert node q after node p
* @param : p, q
* @return : Status
* @notice : None
*/
Status InsertList(LNode *p, LNode *q) {
if(!p)
return ERROR;
if(!(p->next)) {
p->next=q;
q->next=NULL;
}
else {
q->next=p->next;
p->next=q;
}
return SUCCESS;
}
/**
* @name : Status DeleteList(LNode *p, ElemType *e)
* @description : delete the first node after the node p and assign its value to e
* @param : p, e
* @return : Status
* @notice : None
*/
Status DeleteList(LNode *p, ElemType *e) {
LNode *q;
if(!(p->next))
return ERROR;
q=p->next;
*e=q->data;
p->next=q->next;
free(q);
return SUCCESS;
}
/**
* @name : void TraverseList(LinkedList L, void (*visit)(ElemType e))
* @description : traverse the linked list and call the funtion visit
* @param : L(the head node), visit
* @return : None
* @notice : None
*/
void TraverseList(LinkedList L, void (*visit)(ElemType e)) {
LNode *p=L->next;
while(p) {
if(p->next==NULL)
(*visit)(p->data);
else {
(*visit)(p->data);
printf("->");
}
p=p->next;
}
}
/**
* @name : void visit(ElemType e)
* @description : achieve the funtion visit
* @param : e
* @return : None
* @notice : None
*/
void visit(ElemType e) {
printf("%d",e);
}
/**
* @name : Status SearchList(LinkedList L, ElemType e)
* @description : find the first node in the linked list according to e
* @param : L(the head node), e
* @return : Status
* @notice : None
*/
Status SearchList(LinkedList L, ElemType e) {
LNode *p=L->next;
if(!L)
return ERROR;
while(p) {
if(p->data==e)
return SUCCESS;
else
p=p->next;
}
return ERROR;
}
/**
* @name : Status ReverseList(LinkedList *L)
* @description : reverse the linked list
* @param : L(the head node)
* @return : Status
* @notice : None
*/
Status ReverseList(LinkedList *L) {
LNode *p1,*p2,*p3;
if(!(*L))
return ERROR;
p1=(*L)->next;
p2=p1->next;
p1->next=NULL;
p3=p2->next;
while(p1) {
p2->next=p1;
p1=p2;p2=p3;
if(p2==NULL)break;
p3=p2->next;
}
(*L)->next=p1;
return SUCCESS;
}
/**
* @name : Status IsLoopList(LinkedList L)
* @description : judge whether the linked list is looped
* @param : L(the head node)
* @return : Status
* @notice : None
*/
Status IsLoopList(LinkedList L) {
LNode *slow,*fast;
slow=fast=L;
while(fast&&fast->next) {
slow=slow->next;
fast=fast->next->next;
if(slow==fast)
return SUCCESS;
}
return ERROR;
}
/**
* @name : LNode* ReverseEvenList(LinkedList *L)
* @description : reverse the nodes which value is an even number in the linked list, input: 1 -> 2 -> 3 -> 4 output: 2 -> 1 -> 4 -> 3
* @param : L(the head node)
* @return : LNode(the new head node)
* @notice : choose to finish
*/
LNode* ReverseEvenList(LinkedList *L) {
LNode *p1,*p2,*p3;
p1=(*L)->next;
(*L)->next=p1->next;
while(p1&&p1->next) {
p2=p1->next;
p3=p2->next;
if(p2->next&&p2->next->next) {
p1->next=p3->next;
}
else {
p1->next=p2->next;
}
p2->next=p1;
p1=p3;
}
return *L;
}
/**
* @name : LNode* FindMidNode(LinkedList *L)
* @description : find the middle node in the linked list
* @param : L(the head node)
* @return : LNode
* @notice : choose to finish
*/
LNode* FindMidNode(LinkedList *L) {
LNode *Mid,*p;
Mid=p=*L;
while(p->next&&p->next->next) {
Mid=Mid->next;
p=p->next->next;
}
return Mid;
}
/**
* @name : long int chnum(char *str)
* @description : String to integer
* @param : str
* @return : num
* @notice : None
*/
int chnum(char *str) {
int i,n,num=0;
for(i=0;str[i]!='\0';i++){
if(str[i]>='0'&&str[i]<='9') {
num=num*10+str[i]-'0';
}
}
return num;
}
<file_sep>#include "../head/LinkStack.h"
#include<stdio.h>
#include<stdlib.h>
void main()
{
LinkStack *s;
ElemType data,e;
char a[100],b[100];int num,length;
s=(LinkStack *)malloc(sizeof(LinkStack));
initLStack(s);
while(1) {
printf("****************************************************************\n");
printf("* *\n");
printf("********************数据结构之链栈程序设计**********************\n");
printf("* *\n");
printf("***************作者:梁德钊(3119005103)软工三班******************\n");
printf("* 1.判断栈链是否为空 *\n");
printf("* 2.得到栈顶元素 *\n");
printf("* 3.清空栈 *\n");
printf("* 4.销毁栈 *\n");
printf("* 5.检测栈长度 *\n");
printf("* 6.入栈 *\n");
printf("* 7.出栈 *\n");
printf("* 8.遍历栈 *\n");
printf("* 0.退出程序 *\n");
printf("****************************************************************\n");
printf("请输入要执行的操作前的选项:");
while(1) {
gets(a);
num=a[0]-'0';
if(a[0]>='0'&&a[0]<='8')break;
printf("输入错误,请再次输入:");
}
switch(num){
case 1:
system("cls");
printf("*********************\n");
isEmptyLStack(s);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 2:
system("cls");
printf("*********************\n");
getTopLStack(s,&e);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 3:
system("cls");
clearLStack(s);
printf("*********************\n");
printf("清空成功!\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 4:
system("cls");
destroyLStack(s);
printf("*********************\n");
printf("销毁成功!\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 5:
system("cls");
LStackLength(s,&length);
printf("*********************\n");
printf("栈长度为:%d\n",length);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 6:
system("cls");
printf("*********************\n");
printf("请输入入栈结点的数据:");
gets(a);
pushLStack(s,chnum(a));
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 7:
system("cls");
printf("*********************\n");
popLStack(s,&data);
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 8:
system("cls");
printf("*********************\n");
printf("栈数据为:");
TraverseStack(s);
printf("\n");
printf("*********************\n");
printf("输入0返回上一层:");
while(1) {
gets(a);
if(a[0]=='0') break;
printf("输入错误,请再次输入:");
}
system("cls");
break;
case 0:
exit(0);break;
}
}
}
| 36d56ae16456322ea876492eca88dc7d97d9fa71 | [
"Markdown",
"C",
"INI"
] | 29 | C | XavierLeong/XL1 | 505ff79b6976a909730107ccd2b686f0f17e4519 | 5828d07b89c2992a44f41b23856c9ac6cf080271 | |
refs/heads/master | <repo_name>alaponin/TindomondoClient<file_sep>/src/app/main/main.html
<div ng-controller="MainController as controller">
<div>
<div class = "text">Tindomondo helps you find<p>new companions for your<p>sport activities.</div>
<div class = "citation">"If Tindomondo had been there in<p>my childhood, me and the whole<p>Estonian basketball community
<p>would definitely have<p>benefited from it!"</div>
<div class = "name"><b><NAME> (BC TU/Rock)</b></div>
<div class = "but"><button type="button" class="btn btn-default loginButton" data-ng-show="!controller.logged"
data-ng-disabled="!controller.facebookReady && controller.buttonDisabled"
data-ng-click="controller.IntentLogin()">Login with Facebook</button></div>
</div>
</div>
<file_sep>/src/app/main/main.controller.js
(function() {
'use strict';
angular
.module('client')
.controller('MainController', MainController);
/** @ngInject */
function MainController($scope, $rootScope, $route, $timeout, Facebook, $http, $location, userService, $cookieStore) {
var vm = this;
// Define user empty data :/
vm.user = {};
// Defining user logged status
vm.logged = false;
vm.buttonDisabled = false;
/**
* Watch for Facebook to be ready.
* There's also the event that could be used
*/
$scope.$watch(
function() {
return Facebook.isReady();
},
function(newVal) {
if (newVal)
vm.facebookReady = true;
}
);
var userIsConnected = false;
Facebook.getLoginStatus(function(response) {
if (response.status == 'connected') {
userIsConnected = true;
vm.logged = true;
vm.me();
$location.path('/eventList');
}
});
/**
* IntentLogin
*/
vm.IntentLogin = function() {
console.log("Before: ", vm.buttonDisabled);
vm.buttonDisabled = true;
console.log("After: ", vm.buttonDisabled);
console.log("Login started!");
if(!userIsConnected) {
vm.login();
}
};
/**
* Login
*/
vm.login = function() {
Facebook.login(function(response) {
if (response.status == 'connected') {
vm.logged = true;
vm.me();
} else {
vm.buttonDisabled = false;
}
}, {scope: 'email,public_profile'});
};
/**
* me
*/
vm.me = function() {
Facebook.api('/me', function(response) {
/**
* Using $scope.$apply since this happens outside angular framework.
*/
userService.createUser({name: response.name, fb_id: response.id});
userService.getUserByFbId(response.id).then(function(response){
$cookieStore.put('user_id',response.data.id);
});
$scope.$apply(function() {
vm.user = response;
$rootScope.$broadcast('fbLoginHappened', vm.user);
$location.path('/eventList');
});
});
};
/**
* Logout
*/
vm.logout = function() {
Facebook.logout(function() {
$scope.$apply(function() {
vm.user = {};
vm.logged = false;
userIsConnected = false;
$route.reload();
});
});
};
$rootScope.$on('logOutHappened', function() {
vm.user = {};
vm.logged = false;
userIsConnected = false;
vm.buttonDisabled = false;
$route.reload();
});
}
})();
<file_sep>/src/app/serverApi/registrationService.service.js
(function() {
'use strict';
angular
.module('client')
.service('registrationService', registrationService);
/** @ngInject */
function registrationService($http, $q, backendlink) {
return {
getRegistrations: function(data) {
var registration = $q.defer();
$http({
method: 'GET',
url: backendlink+'registrations.json',
data: data
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
getRegistrationByEvent: function(data) {
var registration = $q.defer();
$http({
method: 'GET',
url: backendlink+'registrations/'+data+'.json',
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
createRegistration: function(data) {
console.log(data);
var registration = $q.defer();
$http({
method: 'POST',
url: backendlink+'registrations.json',
data: data
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
unjoinEvent: function(data) {
console.log(data);
var registration = $q.defer();
$http({
method: 'POST',
url: backendlink+'registrations/unjoin',
data: data
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
getUserRegistrations: function(data) {
console.log(data);
var registration = $q.defer();
$http({
method: 'GET',
url: backendlink+'registrations/userevents?user_id='+data,
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
getUserEvents: function(data) {
console.log(data);
var registration = $q.defer();
$http({
method: 'GET',
url: backendlink+'registrations/usereventid?user_id='+data.user_id+'&event_id='+data.event_id,
data: data
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
getEventParticipants: function(data) {
console.log(data);
var registration = $q.defer();
$http({
method: 'GET',
url: backendlink+'registrations/eventparticipants?event_id='+data,
data: data
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
},
getParticipantsList: function(data) {
console.log(data);
var registration = $q.defer();
$http({
method: 'GET',
url: backendlink+'registrations/eventparticipantslist?event_id='+data,
data: data
}).then(function(data) {
registration.resolve(data);
});
return registration.promise;
}
}
}
})();<file_sep>/src/app/components/navbar/navbar.controller.js
(function() {
'use strict';
angular
.module('client')
.controller('NavbarController', NavbarController);
/** @ngInject */
function NavbarController($scope, $rootScope, $timeout, Facebook, $route) {
var vm = this;
vm.loggedIn = false;
vm.user = {};
vm.profilePicImage = "";
vm.facebookReady = true;
vm.me = function() {
Facebook.api('/me', function(response) {
Facebook.api("/me/picture?type=large",
function (response2) {
if (response2 && !response2.error) {
vm.profilePicImage = response2.data.url;
}
}
);
/**
* Using $scope.$apply since this happens outside angular framework.
*/
$scope.$apply(function() {
vm.user = response;
});
});
};
vm.logout = function() {
Facebook.logout(function() {
$scope.$apply(function() {
vm.user = {};
vm.loggedIn = false;
vm.profilePicImage = "";
$rootScope.$broadcast('logOutHappened');
$route.reload();
});
});
};
$rootScope.$on('fbLoginHappened', function(ev, user) {
vm.user = user;
vm.loggedIn = true;
vm.me();
});
}
angular
.module('client')
.controller('AppCtrl', function ($scope, $timeout, $mdSidenav, $log) {
$scope.toggleLeft = buildDelayedToggler('left');
$scope.toggleRight = buildToggler('right');
$scope.isOpenRight = function(){
return $mdSidenav('right').isOpen();
};
/**
* Supplies a function that will continue to operate until the
* time is up.
*/
function debounce(func, wait, context) {
var timer;
return function debounced() {
var context = $scope,
args = Array.prototype.slice.call(arguments);
$timeout.cancel(timer);
timer = $timeout(function() {
timer = undefined;
func.apply(context, args);
}, wait || 10);
};
}
/**
* Build handler to open/close a SideNav; when animation finishes
* report completion in console
*/
function buildDelayedToggler(navID) {
return debounce(function() {
$mdSidenav(navID)
.toggle()
.then(function () {
$log.debug("toggle " + navID + " is done");
});
}, 200);
}
function buildToggler(navID) {
return function() {
$mdSidenav(navID)
.toggle()
.then(function () {
$log.debug("toggle " + navID + " is done");
});
}
}
})
.controller('LeftCtrl', function ($scope, $timeout, $mdSidenav, $log) {
$scope.close = function () {
$mdSidenav('left').close()
.then(function () {
$log.debug("close LEFT is done");
});
};
})
.controller('RightCtrl', function ($scope, $timeout, $mdSidenav, $log) {
$scope.close = function () {
$mdSidenav('right').close()
.then(function () {
$log.debug("close RIGHT is done");
});
};
});
})();
<file_sep>/src/app/components/googleMaps/googleMaps.mock.js
window.google = {
maps: {
LatLng: function(lat, lng) {
return {
latitude: parseFloat(lat),
longitude: parseFloat(lng)
};
},
LatLngBounds: function(ne, sw) {
return {};
},
DirectionsService: function() {
return {
route: function (request, callback) {
return callback();
}
};
},
TravelMode: {
DRIVING: 'DRIVING'
}
}
};<file_sep>/gulpfile.js
/**
* Welcome to your gulpfile!
* The gulp tasks are splitted in several files in the gulp directory
* because putting all here was really too long
*/
'use strict';
var gulp = require('gulp');
var wrench = require('wrench');
var rsync = require('gulp-rsync');
var gutil = require('gulp-util');
var push = require('git-push');
var argv = require('minimist')(process.argv.slice(2));
/**
* This will load all js or coffee files in the gulp directory
* in order to load all gulp tasks
*/
wrench.readdirSyncRecursive('./gulp').filter(function(file) {
return (/\.(js|coffee)$/i).test(file);
}).map(function(file) {
require('./gulp/' + file);
});
/**
* Default task clean temporaries directories and launch the
* main optimization build task
*/
gulp.task('default', ['clean'], function () {
gulp.start('build');
});
gulp.task('deploy', function() {
gulp.src('dist/**')
.pipe(rsync({
root: 'dist',
hostname: 'tindomondo.com',
username: 'TindoAdmin',
destination: '~/production',
incremental: true
}));
});
gulp.task('rsync', function() {
return gulp.src('./dist/**')
.pipe(rsync({
destination: '~/production',
root: '~',
hostname: 'tindomondo.com',
username: 'TindoAdmin',
incremental: true,
progress: true,
relative: true,
emptyDirectories: true,
recursive: true,
clean: true,
exclude: ['.DS_Store'],
include: []
}));
});
gulp.task('moveToDist', function() {
push('./dist', 'https://github.com/alaponin/TindomondoClientDist', function() {
console.log('Done!');
});
});
<file_sep>/src/app/serverApi/sportService.service.js
(function() {
'use strict';
angular
.module('client')
.service('sportService', sportService);
/** @ngInject */
function sportService($http, $q, backendlink) {
return {
getSports: function(data) {
var sport = $q.defer();
$http({
method: 'GET',
url: backendlink+'/sports.json',
data: data
}).then(function(data) {
sport.resolve(data);
});
return sport.promise;
},
getSport: function(data) {
var sport = $q.defer();
$http({
method: 'GET',
url: backendlink+'/sports/'+data+'.json',
}).then(function(data) {
sport.resolve(data);
});
return sport.promise;
}
}
}
})();<file_sep>/src/app/components/eventList/eventList.controller.js
(function() {
'use strict';
angular
.module('client')
.controller('EventListController', EventListController);
/** @ngInject */
function EventListController($scope, $rootScope, eventService, sportService, Facebook) {
var vm = this;
vm.events = [];
Facebook.api('/me', function(user) {
$scope.$apply(function() {
$rootScope.$broadcast('fbLoginHappened', user);
});
});
eventService.getEvents().then(function(response) {
var sports = [];
sportService.getSports().then(function(sports_response){
sports_response.data.forEach(function(sport) {
sports[sport.id] = sport.name;
});
response.data.forEach(function(event) {
var datetime = new Date(event.start_time);
datetime = (datetime.getDate() + "-" + (datetime.getMonth() + 1) + "-" + datetime.getFullYear() + " " + datetime.toLocaleTimeString());
vm.events.push(
{event_id: event.id, sport_name: sports[event.sport_id], user_name: event.user_id, location: event.location, time: datetime}
);
});
});
$scope.events = vm.events;
});
}
})();<file_sep>/src/app/serverApi/eventService.service.js
(function() {
'use strict';
angular
.module('client')
.service('eventService', eventService);
/** @ngInject */
function eventService($http, $q, backendlink) {
return {
getEvents: function(data) {
var event = $q.defer();
$http({
method: 'GET',
url: backendlink+'events.json',
data: data
}).then(function(data) {
event.resolve(data);
});
return event.promise;
},
getEvent: function(data) {
var event = $q.defer();
$http({
method: 'GET',
url: backendlink+'events/'+data+'.json',
}).then(function(data) {
event.resolve(data);
});
return event.promise;
},
createEvent: function(data) {
console.log(data);
var event = $q.defer();
$http({
method: 'POST',
url: backendlink+'events.json',
data: data
}).then(function(data) {
event.resolve(data);
});
return event.promise;
}
}
}
})();<file_sep>/src/app/index.route.js
(function() {
'use strict';
angular
.module('client')
.config(routerConfig);
/** @ngInject */
function routerConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state('home', {
url: '/',
templateUrl: 'app/main/main.html',
controller: 'MainController',
controllerAs: 'main'
}).state('eventDetail', {
url: '/eventDetail/:id',
templateUrl: 'app/components/eventDetail/eventDetail.html',
controller: 'EventController',
onEnter: ['$state', 'Facebook', function($state, Facebook) {
Facebook.getLoginStatus(function(response) {
if (response.status != 'connected') {
$state.go('home');
}
});
}]
}).state('addEvent', {
url: '/addEvent',
templateUrl: 'app/components/addEvent/addEvent.html',
controller: 'addEventController',
controllerAs: 'controller',
onEnter: ['$state', 'Facebook', function($state, Facebook) {
Facebook.getLoginStatus(function(response) {
if (response.status != 'connected') {
$state.go('home');
}
});
}]
}).state('eventList', {
url: '/eventList',
templateUrl: 'app/components/eventList/eventList.html',
controller: 'EventListController',
onEnter: ['$state', 'Facebook', function($state, Facebook) {
Facebook.getLoginStatus(function(response) {
if (response.status != 'connected') {
$state.go('home');
}
});
}]
}).state('myEvents', {
url: '/myEvents',
templateUrl: 'app/components/myEvents/myEvents.html',
controller: 'myEventsController',
onEnter: ['$state', 'Facebook', function($state, Facebook) {
Facebook.getLoginStatus(function(response) {
if (response.status != 'connected') {
$state.go('home');
}
});
}]
}).state('eventParticipants', {
url: '/eventParticipants/:id',
templateUrl: 'app/components/eventParticipants/eventParticipants.html',
controller: 'EventParticipantsController',
onEnter: ['$state', 'Facebook', function($state, Facebook) {
Facebook.getLoginStatus(function(response) {
if (response.status != 'connected') {
$state.go('home');
}
});
}]
}).state('giveFeedback', {
url: '/feedback',
templateUrl: 'app/components/feedback/feedback.html',
controller: 'giveFeedbackController',
onEnter: ['$state', 'Facebook', function($state, Facebook) {
Facebook.getLoginStatus(function(response) {
if (response.status != 'connected') {
$state.go('home');
}
});
}]
})
$urlRouterProvider.otherwise('/');
}
})();
<file_sep>/src/app/serverApi/feedbackService.service.js
(function() {
'use strict';
angular
.module('client')
.service('feedbackService', feedbackService);
function feedbackService($http, $q, backendlink) {
return {
sendFeedback: function(data) {
var event = $q.defer();
$http({
method: 'POST',
url: backendlink+'feedbacks.json',
data: data
}).then(function(data) {
event.resolve(data);
});
return event.promise;
}
}
}
})();<file_sep>/src/app/components/addEvent/addEvent.controller.js
(function() {
'use strict';
angular
.module('client')
.controller('addEventController', addEventController);
/** @ngInject */
function addEventController($scope, $timeout, $state, $rootScope, Facebook, sportService, eventService, googleAddress, $cookieStore, $location, Notification) {
var vm = this;
vm.time = null;
vm.minute = null;
vm.sport = {};
vm.participants;
vm.place;
$scope.eventData = {};
vm.eventAddress = "Choose location on map";
Facebook.api('/me', function(user) {
$scope.$apply(function() {
$rootScope.$broadcast('fbLoginHappened', user);
});
});
vm.directionsService = new google.maps.DirectionsService();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function success(position) {
vm.map = {
center: {
latitude : position.coords.latitude,
longitude : position.coords.longitude
},
bounds: new google.maps.LatLngBounds(),
zoom: 15,
options: {
mapTypeControl: true,
panControl: true,
zoomControl: true,
clickable: true
},
events: {
click: function (mapModel, eventName, originalEventArgs) {
vm.markers = [];
var lat = originalEventArgs[0].latLng.lat();
var lng = originalEventArgs[0].latLng.lng();
var marker = {
id: 1,
coords: {
latitude: lat,
longitude: lng
}
};
vm.markers.push(marker);
;
googleAddress.getAddress(lat, lng).then(function successCallback(response) {
vm.eventAddress = response.data.results[0].formatted_address;
});
$scope.$digest();
}
}
};
}
function error(err) {
vm.map = {
center: {
latitude : 0,
longitude : 0
},
bounds: new google.maps.LatLngBounds(),
zoom: 1,
options: {
mapTypeControl: true,
panControl: true,
zoomControl: true,
clickable: true
},
events: {
click: function (mapModel, eventName, originalEventArgs) {
vm.markers = [];
var lat = originalEventArgs[0].latLng.lat();
var lng = originalEventArgs[0].latLng.lng();
var marker = {
id: 1,
coords: {
latitude: lat,
longitude: lng
}
};
vm.markers.push(marker);
;
googleAddress.getAddress(lat, lng).then(function successCallback(response) {
vm.eventAddress = response.data.results[0].formatted_address;
});
$scope.$digest();
}
}
};
};
vm.markers = [];
vm.markers.push(vm.marker);
sportService.getSports().then(function(sports_response){
vm.sports = [];
sports_response.data.forEach(function(sport) {
vm.sports.push(
{id: sport.id, name: sport.name}
);
});
});
function convertTime() {
}
vm.createEvent = createEvent;
function createEvent() {
var start_date = new Date(vm.date);
var start_time = new Date(vm.time);
start_time = start_time.toTimeString();
start_time = (start_time.split(" "))[0];
var start = start_date.getFullYear() + "-" + (start_date.getMonth() + 1) + "-" + start_date.getDate() + " " + start_time;
var eventData = {user_id: $cookieStore.get('user_id'), sport_id: vm.sport, start_time: start, duration: 2,
registration_min: vm.registration_min, registration_limit: vm.registration_limit, location: vm.eventAddress, description: vm.description};
eventService.createEvent(eventData).then(function() {
Notification.success('Event was created.');
$timeout(function() {
$state.go('myEvents');
}, 2000);
});
}
vm.marker = {
id: 0,
coords: {
latitude: 58.3661916,
longitude: 26.69020660000001
},
options: { draggable: false, visible: true},
};
}
})();
angular
.module('client').filter('range', function() {
return function(input, min, max) {
min = parseInt(min); //Make string input int
max = parseInt(max);
for (var i=min; i<max; i++)
input.push(i);
return input;
};});
| ee878b6c03ec84672d5b51255e2011f69c6d3212 | [
"JavaScript",
"HTML"
] | 12 | HTML | alaponin/TindomondoClient | 0a1e2780ace490b3cad579f48824eae8d665792a | 3d533adb101eb1d823e7d2d3e84c1eb9d3061881 | |
refs/heads/master | <repo_name>bububa/Clear-History<file_sep>/clearhistory.py
import time
from cmd import *
#----------------------------------------------------------------------------------
# Intro
#----------------------------------------------------------------------------------
clear()
raw_input("Press enter to begin...")
print("MyCustomOS")
time.sleep(0.4)
print("Loading CoreOSFiles")
say(1.1, "Connecting to the network")
say(1.2, "Connected")
say(1.1, "Initializing myCustomChat")
say(1.3, "Error! Send function not initialized")
say(1.1, "No friends online")
say(1.1, "Reading from USB")
say(1.2, "Now executing Training Program")
time.sleep(3)
clear()
load_commands()
#==================================================================================
# Stage 1
#----------------------------------------------------------------------------------
# Very early in the morning.
# This takes place in the offices of Pheonixeon Corp.
# The protagonist is just starting his new job as a security consultant.
# He enters an empty room. He then inserts a USB flash drive into his computer as
# he was instructed by his manager over the phone.
#==================================================================================
load_stage_1()
managerName = "<NAME>" #Just so I can change it easily if I want.
say(0, "Hello, I'm " + managerName + ".\n")
say(1, "I'm sorry that I had you bring your own laptop.\nYour office isn't yet ready so you have to use the empty storage room for now.\nI have something to do so I can't come in to work today\nbut I think we can start training with this USB flash drive with instructions.\nLets Begin.\n")
raw_input("Press Enter to Continue")
say(1, "First, I'll teach you how to connect to other computers on the network.\nType 'connect The name of the computer'.\n")
say(1, "The computers on this network are usually called 'full name of the employee'\n followed by their 'job'.\n")
say(1, "The names don't have any spaces, only underscores.\n")
raw_input("Press Enter to Continue")
say(1, "Now, I want you to connect to 'Steve_Waller_Security_Consultant'\nIt's case-sensitive so be sure to remember.\n")
raw_input("Press Enter to Continue")
say(2, "\nMost of the time.\n The computers will be password protected.\nYou can easily bypass it with the 'crack' command.\n")
say(1, "That won't completely do all the work for you but it'll make it easier.\nIt'll show you the amount of letters the password is along with hints \nof some letters contained.\n")
raw_input("Press Enter to Continue")
say(1, "Just type in a letter at a time to check if it's contained in the word.\nKind of like 'Hangman'\n")
say(1, "Now crack the password.")
say(1, "type: crack Steve_Waller_Security_Consultant\n")
while True:
if cmd() == ["crack", "Steve_Waller_Security_Consultant"] : break
say(1, "\nNow that the password has been entered, you can connect to it.\n")
say(1, "You type it in this format: connect (name_of_computer)\nNow connect to Steve_Waller_Security_Consultant\n")
while True:
if cmd() == ["connect", "Steve_Waller_Security_Consultant"] : break
say(1, "\nTo see all the files contained in the computer use the 'ls' command.\n")
say(1, "type: ls\n")
while True:
if cmd() == ["ls"]: break
say(1, "\nTo read files use the 'cat' command\nfollowed by the file you want to read.\n")
say(1, "In this format: cat (name_of_file)\nTry reading SteveMail.hist.\n")
while True:
if cmd() == ["cat", "SteveMail.hist"]: break
say(1.5, "Good. Now try to decrypt employLst.lst by using the 'decrypt' command\nfollowed by the filename and password(if you have it).\n")
say(1, "That command brings up the jumbled keyword.\nThe letters in the keyword are shifted by a certain number.\n")
raw_input("Press Enter to Continue")
say(1, "For example 'a' shifted by -1 will be 'z'.\nAnd if 'a' is shifted by 1 it will be 'b'.\nIts your job to find out the decryption code\n(the number of letters the keyword is shifted by.)\n")
raw_input("Press Enter to Continue")
say(1, "You can use the keyword 'scan' followed the name of the computer to view its specs.\n")
say(1, "In this format to reveal the jumbled word: decrypt (filename)\n")
say(1, "In this format to enter the password: decrypt (filename) (Password)\n")
say(1, "Type this to see the specs: scan (Name_Of_Computer)\n")
say(1, "Now decrypt employLst.lst\n")
while True:
if cmd() == ["decrypt", "employLst.lst", "password"]: break
say(1, "\nGood. Now I'm going to need you to retrieve all the files from the computer.")
say(1, "Use the 'download' command followed by the filename\nto download any file to your computer.\n")
say(1, "Like this: download (filename)\n")
while True:
cmd()
if "savedFragment2.ry"in Home_Computer.files and "SteveMail.hist" in Home_Computer.files and "employLst.lst" in Home_Computer.files: break
say(1, "\nOnce you've downloaded the file,\ndisconnect from the computer by using the 'disconnect' function.\n")
say(1, "Format: disconnect\n")
while True:
if cmd() == ["disconnect"] : break
say(1, "\nNow upload savedFragment2.ry to using the 'upload' command\nfollowed by the fileame you want to upload, then the computer name.\n")
say(1, "Format: upload (filename) (Name_Of_Computer)")
say(0, "Send it to 'Amitav_Gutipaty_Manager'\n")
while True:
if cmd() == ["upload", "savedFragment2.ry", "Amitav_Gutipaty_Manager"]: break
say(2, "\nYou have just given me highly classified information about the company.\nBut since this company has a closed network I couldn't get in it through the inside computers.\n")
say(1, "But with your computer I could access the internet\nand everything will be traced back to you.\n")
say(5, "Good Bye")
say(9, "")
fill_screen()
clear()
#====================================================================================
# Stage 2
#------------------------------------------------------------------------------------
# The protagonist has just been told that he's been had.
#=====================================================================================
load_stage_2()
girlName = "HaxorGurl"
imGirl = girlName + " says: "
say(4, girlName + " is now online.")
say(3, imGirl + "Hey!")
say(2, imGirl + "its really early!")
say(3, imGirl + "Aren't u supposed to be @ work?! o_0")
say(2, imGirl + "Answer me! >_<")
say(4, imGirl + "Dats it! I'm scanning u! >:D")
say(5, imGirl + "Ohh! you ARE at work....")
say(3.8, imGirl + "lol, you're using David's crappy ass OS?!")
say(2.3, imGirl + "It doesn't let you send messages, huh?")
say(2.4, imGirl + "You know he just used that to spy on girls' conversations...")
say(2.1, imGirl + "Anyways~")
say(3.3, imGirl + "I just read on a blog..")
say(3.5, imGirl + "that the company you now work for just got hacked.")
say(3.5, imGirl + "The blog says that the company is not letting anybody leave")
say(2.3, imGirl + "until they catch the culprit.")
say(3.3, imGirl + "So far the only leads the cops have is a new employee")
say(5, imGirl + "was seen bringing a personal laptop. But they can't find him.")
say(3, imGirl + "Wait a minute...")
say(1, imGirl + "Thats....")
say(6, imGirl + "you!")
say(4.2, imGirl + "that's strange though,")
say(3.2, imGirl + "because this other guy is taking credit for it.")
say(2, imGirl + "But he says the cops will never find him cuz he's in hiding.")
say(3.3, imGirl + "it must be a mistake, you have to clear your name...")
say(3.5, imGirl + "look around the network for some proof!")
say(3.2, imGirl + "before the cops find you. D:")
say(3.1, imGirl + "If you want,")
say(5, imGirl + "you can upload files to me and I'll see if i can helps. :3")
say(2.1, imGirl + "Just upload to 'haxorgurl'.")
say(4.1, imGirl + "Don't worry, I'll give you the files back")
say(6.1, imGirl + "A word to the wise...")
say(4, imGirl + "Download anything that might be useful later")
say(3, imGirl + "Try connecting to some computers on the network...")
say(5.3, imGirl + "Now get to searchinnnN!!!!")
while True:
cmd()
if "savedFragment3.ih" in Home_Computer.files and "savedFragment0.jby" in Home_Computer.files: break
say(3, "SECURITY TRIGGERED")
say(3.3, "NOW TRIGGERING SECURITY MEASURES")
fill_screen()
clear()
#======================================================================================
# Stage 3
#--------------------------------------------------------------------------------------
# Security was just triggered which means all the computers were switched.
#============================================================================================
load_stage_3_1()
say(1.5, imGirl + "wut was dat?! D:")
say(2.2, imGirl + "An update on that dude's blog...")
say(3, imGirl + "he says that security\nhas been activated.")
say(2.3, imGirl + "o_o")
say(6, imGirl + "not")
say(6, imGirl + "good")
say(2.1, imGirl + "pick up the pace!")
while True:
cmd()
if final_conditions() == True: break
fill_screen()
clear()
load_stage_3_2()
say(1, imGirl + "what cause thkat/")
say(2.2, imGirl + "caused that?")
say(2.3, imGirl + "send the file to me")
while True:
if cmd() == ["upload", "pandorasBox.exe", "haxorgurl"]: break
say(1.1, imGirl + "lets see")
say(1, imGirl + "har harhahar har!!!")
say(2.5, imGirl + "this guy is a dummy! XD")
say(2.5, imGirl + "He wrote this from his home computer!!")
say(3, imGirl + "I was able to extract all his location information!!!")
say(2.3, imGirl + "Imma give this to the cops.")
say(2.3, imGirl + "maybe I'll get a reward for giving tips hehehe :P")
say(1.2, imGirl + "brb")
say(10, imGirl + "urgh, they put me on hold >:C")
say(5, imGirl + "okay hold on, they're processing.")
say(5, imGirl + "haha they said my tip was helpfulllll ^^")
say(2.5, imGirl + "oh, Pheonixeon's website posted something!")
say(3, imGirl + "'Thanks to an anonymous tip,")
say(3, imGirl + "the hacker has been identified as a recently laid off employee.")
say(5, imGirl + "Even though he just hacked through our least important")
say(3, imGirl + "and least secure network we are working our hardest to get things")
say(2, imGirl + "back to normal.'")
say(4, imGirl + "That was damn quick!")
say(3, imGirl + "They're not a top company for nothing...")
say(1, imGirl + "it seems that you're off the hook! :D")
say(2.5, imGirl + "but this pandora file.....")
say(2.5, imGirl + "only contains personal conversations between employees...")
say(5, imGirl + "I guess that's all the 'least important' network contained.")
say(2.3, imGirl + "either way, congrats on your new job XD")
say(2.3, imGirl + "well, i'm off! see ya after work!")
say(1.4, imGirl + "oh...")
say(3.5, imGirl + "The guy's fetish....")
say(4, imGirl + "is peanut butter....go figure :/")
say(1, girlName + " is now offline.")
# EXIT the game
<file_sep>/Constants.py
# This string is shown when user enters the 'ls' command
file_header = """
Files:
-------"""
Haxor_Gurl_Responses = { "SteveMail.hist" : "A cute new employee? I wonder who she means? o_o That must be quite a fetish!",
"RichardMemo.txt" : "So if somebody triggers security the computers available to you are switched around? Weird. :/",
"ses.png" : ">:/ This isn't the time for this!! @_@; poor donkey.",
"employees.lst" : "Dang o_O! That Sally is quite old for a receptionist.",
"TyrellaMail.hst" : "No doubt that 'new recruit' is u, huh. :p",
"AmitavMemo.txt" : "....Does he mean the file extensions? I guess you have to read them in order?",
"savedFragment0.jby" : "They seem to be numbered. Try to collect all of them together in your computer.^^",
"savedFragment1.ihc" : "They seem to be numbered. Try to collect all of them together in your computer.^^",
"savedFragment2.ry" : "They seem to be numbered. Try to collect all of them together in your computer.^^",
"savedFragment3.ih" : "They seem to be numbered. Try to collect all of them together in your computer.^^",
"pandorasBox.exe" : "Thnx ^_^"}
Haxor_Random_Responses = ["I don't know what to tell you.", "I don't know what this is.", "I dunno what this is. :(", "Sorry, I can't help you with this.", "You're on your on on this one. :)"]
# This string is shows when the user enters 'help' command
help = """
<> = required, || = optional
ls List files on current computer
cat <file> Displays file
connect <computer> Connect to given computer
disconnect Return to home computer
scan <computer> Get information on given computer
crack <computer> |password| Crack given computer's password
decrypt <file> Decrypt encrypted file
download <file> Download file to home computer
upload <file> <computer> Upload given file to given computer
help Provides help information
"""
home_computer = """
My Computer
---------------------------
CPU: Intel Celeron D @ 1.3 Ghz
RAM: 256 MB
OS: MyCustomOS
"""
Steve_Waller_Security_Consultant = """
<NAME>er Securty Consultant
----------------------------------------
CPU: Intel i7 Extreme 8 cores @ 3.4 GHz
RAM: 8GB
OS: Windows8
"""
Steve_Mail = """
------------------------------------------------------------
From: <NAME>
Hey, do you remember the encryption code for our employee
files?
To: <NAME>
Why do you want to know? And hey, how about dinner tonight?
From: <NAME>
I told you, Steve! We're over! Now just tell me the code!!
To: <NAME>
It's against policy to say! You're a receptionist! why the
hell would you want to know the code?! Only Security Consultants
would want to know that.
From: <NAME>
It's to help a cute new employee! He forgot it and I want to look smart so
I can ride him!! Cuz i know he'll be better than you!! Now
if you don't tell me I'LL TELL EVERYONE ABOUT YOUR FETISH!!
To: <NAME>
FUUUCK! OKay bitch! I can't tell you directly but its the
amount of RAM on your computer. Its on the sticker on your
computer you dumb bitch.
P.S. I hope he gives you the AIDS.
-----------------------------------------------------------
"""
Sally_Stark_Receptionist = """
Sally Stark Receptionist
--------------------------------------
CPU: Intel i7 Extreme 8 cores @ 3.4Ghz
RAM: 8GB
OS: Windows8
"""
Sally_Mail = """
From: <NAME>
Hey, Sal. I need a big favor from you! I need to take my
kid to the doctor. Could you clock me in anyway? Appreciate it.
To: <NAME>
No problem, I hope he gets better because I know you love your little boy.
To: <NAME>
Remember me? It's Sally, the receptionist. I just wanted to say
that I found out the code for you. It's 8.
From: <NAME>
Thank you so much, ma'am. You are a life saver. It would be
so embarrassing to ask for such important information from my
boss. Especially right after he just told me. So, thanks again.
To: <NAME>
No problem. And what's with the ma'am stuff? Just call me Sally."
From: <NAME>
Haha okay Sally. The code you gave me worked for most of the files
except for one. I don't know what the file does, I'll ask my boss.
"""
Richard_Moliere_Security_Consultant = """
<NAME> Security Consultant
--------------------------------------
CPU: Intel i7 Extreme 8 cores @ 3.4Ghz
RAM: 8GB
OS: Windows8
"""
Richard_Mail = """
To: <NAME>
I'm sorry to disturb you but I have a file here sitting on my computer.
I can't open it with our current encryption code. Do you know how to
decrypt it?
From: <NAME>
No.
To: <NAME>
So, do I just leave it alone?
From: <NAME>
Yes.
"""
Richard_Memo = """
Things to remember:
1. The decryption code for our files is 8.
But when security is comprimised it turns into the opposite plus the ram contained.
Then the network will re-arrange itself. Which means some computers will not be hooked up.
But some others will.
2. I was told not to mess that wierd savedFragment file.
3. Call Sally by her first name...even though she's like 20 years older than me.
4. Our HR Manager really loves her little boy. His name is Chris.
5. Don't fuck this up.
"""
Tyrella_Jensen_HR_Manager = """
Tyrella_Jensen HR Manager
--------------------------------------
CPU: Intel i7 Extreme 8 cores @ 3.4Ghz
RAM: 4GB
OS: Windows8
"""
Tyrella_Mail = """
To: <NAME>
We're were very honored to have you work for us. But as a
result of the recent economy we have no choice but to let
you go. We wish you luck and you should recieve your final
check by the end of the week. Thank you.
From: <NAME>
What?! Bullshit!!!! if the whole shit about the economy is
true, then you wouldn't be hiring more motherfucking security
consultants! I just trained that stupid little jerk-off and
now you're firing me? FUCk you! and all your shit. I'm gonna
go work for Google....fuck you and Pheonixeon.
To: <NAME>
Please refrain from using vulgar language. And both of those
consultants will make less than what you make. I will ask
that you train this new recruit as well before you leave. Thanks :)
From: <NAME>
Oh, I'm gonna train him good alright.
"""
Amitav_Gutipaty_Manager = """
Amitav Gutipaty Manager
--------------------------------------
CPU: Intel i7 Extreme 8 cores @ 3.4Ghz
RAM: 16GB
OS: Windows8
"""
Amitav_Memo = """
The connection: The name of the son and the job of the mother
The ends of the files Encrypted by the age of the new employee will give me Passage.
Once the fragments are happy together with the son and mother, they will gossip.
"""
Chris_Jensen_HR_Manager = """
<NAME> HR Manager
--------------------------------------
CPU: Intel i7 Extreme 8 cores @ 3.4Ghz
RAM: 4GB
OS: Windows8
"""<file_sep>/cmd.py
from resources import *
import time
import random
import os
# Public variables
command_list = {}
success_flag = False
#----------------------------------------------------------------------------------
# im(numOfSecToWait, stringToPrint)
# So I don't have to keep typing time.sleep()
# ---------------------------------------------------------------------------------
def say(num, str):
time.sleep(num)
print(str)
#----------------------------------------------------------------------------------
# Clears the console
#----------------------------------------------------------------------------------
def clear():
os.system(['clear', 'cls'][os.name=='nt'])
def random_line():
characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'l', 'm', 'n', 'o',
'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '0', '!', '@', '#', '$', '%', '^', '&',
'*', '(', ')', ',', '.', ';', '[', ']', '{', '}', ':', '"', '<', '>',
'?']
line = ""
for i in range(78):
line += characters[random.randint(0, len(characters) - 1)]
return line
def fill_screen():
for i in range(10000):
print random_line()
# This function displays the the files to the user
def ls():
if current_computer.files:
print Constants.file_header
for file in current_computer.files:
if current_computer.files[file].encrypted:
print file, "(encrypted)"
else:
print file
print "\n"
else:
print "No files."
# This functions displays the text of a file if not encrypted
def cat(file_name = None):
if file_name:
if file_name in current_computer.files:
file = current_computer.files[file_name]
if file.encrypted != True:
print file.text
else:
print "File is encrypted, cannot display content."
else:
print "%s does not exist." % file_name
else:
print "Please enter name of file you wish to open."
def connect(name = None):
if name != "":
if name in computer_list:
if computer_list[name].protected == False:
global current_computer
current_computer = computer_list[name]
print "Connecting to %s..." % current_computer.name
time.sleep(2)
print "Connected to %s." % current_computer.name
else:
print name, "is password protected, cannot connect."
else:
print name, "does not exist or is not connected."
else:
print "No address given, try again.."
def disconnect():
global current_computer
if current_computer == Home_Computer:
print "Can't disconnect from home computer."
return
current_computer = Home_Computer
print "Disconnecting..."
time.sleep(2)
print "Disconnected."
def scan(computer_name = None):
if computer_name:
if computer_name in computer_list:
print computer_list[computer_name].specs
else:
print computer_name, "does not exist or is not connected."
else:
print "Enter name of computer you wish to scan."
def crack(computer_name = None, password = None):
if computer_name:
if computer_name in computer_list:
if computer_list[computer_name].protected == True:
if password:
if computer_list[computer_name].password == password:
computer_list[computer_name].protected = False
print "Access granted, you can now connect."
else:
print "Access denied."
else:
global success_flag
success_flag = computer_list[computer_name].crack()
if success_flag == True:
computer_list[computer_name].protected = False
print "Access granted, you can now connect."
else:
print computer_name, "does not need to be cracked."
else:
print computer_name, "does not exist or is not connected."
else:
print "Please enter name of computer you wish to crack."
def decrypt(file_name = None, password = None):
if file_name:
if file_name in current_computer.files:
if current_computer.files[file_name].encrypted == True:
if password:
if current_computer.files[file_name].password == <PASSWORD>:
current_computer.files[file_name].encrypted = False
print file_name, "decrypted, you can now access content"
else:
print "Running decrypter..."
time.sleep(1)
print "Displaying encryption keyword:", current_computer.files[file_name].encrypted_password
else:
print file_name, "is not encrypted."
else:
print file_name, "does not exist."
else:
print "Enter filename."
def download(file_name = None):
if file_name:
if file_name in current_computer.files:
print "Downloading %s..." % file_name
Home_Computer.files[file_name] = current_computer.files[file_name]
del current_computer.files[file_name]
time.sleep(1)
print "Transfer complete."
else:
print file_name, "is not a valid filename."
else:
print "Enter name of file you wish to download."
def upload(file_name = None, computer_name = None):
if file_name and computer_name:
if file_name in Home_Computer.files:
if computer_name in computer_list:
if computer_list[computer_name].protected == False:
print "Transfering %s to %s..." % (file_name, computer_name)
computer_list[computer_name].files[file_name] = Home_Computer.files[file_name]
del Home_Computer.files[file_name]
time.sleep(1)
print "Transfer complete."
else:
print "Cannot upload file, %s is protected." % computer_name
elif computer_name == "haxorgurl":
Haxor_Gurl(file_name)
else:
print computer_name, "does not exist or is not connected."
else:
print file_name, "is not a valid filename"
else:
print "Enter valid file and computer name."
def help():
print Constants.help
# Load the command list into the command_list dictionary
def load_commands():
command_list["ls"] = ls
command_list["cat"] = cat
command_list["connect"] = connect
command_list["disconnect"] = disconnect
command_list["scan"] = scan
command_list["crack"] = crack
command_list["decrypt"] = decrypt
command_list["download"] = download
command_list["upload"] = upload
command_list["help"] = help
def load_stage_1():
global computer_list
computer_list = load_stage1_computers()
def load_stage_2():
global computer_list
computer_list = load_stage2_computers()
def load_stage_3_1():
global computer_list
computer_list = load_stage3_computers()
def load_stage_3_2():
global computer_list
computer_list["Chris_Jensen_HR_Manager"].files = Chris_Jensen_Files()
def cmd():
while True:
command = raw_input(current_computer.prompt).split()
if command:
if command[0] in command_list:
if len(command) == 1:
try:
command_list[command[0]]()
except:
pass
else:
return command
elif len(command) == 2:
try:
command_list[command[0]](command[1])
except:
print "Too many arguments given"
else:
return command
elif len(command) == 3:
try:
command_list[command[0]](command[1], command[2])
except:
print "Too many arguments given."
else:
return command
else:
print "Too many parameters, re-enter command."
return command
else:
print command[0], "is not a valid command"
return command
else:
return None
def final_conditions():
return "savedFragment0.jby" in computer_list["Chris_Jensen_HR_Manager"].files and "savedFragment1.ihc" in computer_list["Chris_Jensen_HR_Manager"].files and "savedFragment2.ry" in computer_list["Chris_Jensen_HR_Manager"].files and "savedFragment3.ih" in computer_list["Chris_Jensen_HR_Manager"].files<file_sep>/resources.py
import time
import Constants
import random
def Haxor_Gurl(file_name):
if file_name:
if file_name in Constants.Haxor_Gurl_Responses:
print "HaxorGurl says: ", Constants.Haxor_Gurl_Responses[file_name]
else:
print "HaxorGurl says: ", Constants.Haxor_Random_Responses[random.randint(0, 4)]
def protect_password(password, hints):
result = ""
if password and hints:
for letter in password:
if letter in hints:
result = result + letter + " "
else:
result = result + "_ "
return result
def get_guess():
while True:
guess = raw_input("Guess:> ")
if len(guess) != 1:
print "Only one character guesses accepted."
else:
return guess
# This class represents a computer
class Computer(object):
def __init__(self, name, specs, protected, password = None, hints = None, tries = None):
self.name = name
self.prompt = "user@%s:> " % name
self.files = {}
self.specs = specs
self.protected = protected
self.password = <PASSWORD>
self.protected_password = protect_password(password, hints)
self.hints = hints
self.tries = tries
def crack(self):
current_tries = 0
incorrect_guesses = []
print "Starting cracking program..."
time.sleep(2)
while(current_tries != self.tries):
print "Password:", self.protected_password
print "Tries left: %s" % (self.tries - current_tries)
if incorrect_guesses:
print "Guesses:", ''.join(incorrect_guesses)
guess = get_guess()
if guess in self.password:
self.hints += guess
self.protected_password = protect_password(self.password, self.hints)
if not '_' in self.protected_password:
print "The password for %s is %s" % (self.name, self.password)
return True
elif guess in incorrect_guesses:
print "Already attempted that character."
time.sleep(1)
continue
else:
current_tries = current_tries + 1
incorrect_guesses.append(guess)
print "Too many incorrect guesses, reseting..."
return False
def encrypt(text, shift = 1):
if text:
return ''.join([[ch,chr((ord(ch) - ord(['A','a'][ch.islower()]) + shift)%26+ord(['A','a'][ch.islower()]))][ch.isalpha()] for ch in text])
else:
return None
# This class represents a file
class File(object):
def __init__(self, name, text, is_encrypted, password = None, shift = None):
self.name = name
self.text = text
self.encrypted = is_encrypted
self.password = <PASSWORD>
self.shift = shift
self.encrypted_password = encrypt(password, shift)
def Home_Computer_Files():
files = {}
core_os_files = File("CoreOSFiles.bndl", "Unable to read", False)
files["CoreOSFiles.bndl"] = core_os_files
core_img_files = File("coreImgFiles.bndl", "Unable to read", False)
files["coreImgFiles.bndl"] = core_img_files
core_script = File("coreScript.bndl", "Unable to read", False)
files["coreScript.bndl"] = core_script
ses_crk = File("sesCrk.txt", "Pandora's (i is sqrt of: ?)", False)
files["sesCrk.txt"] = ses_crk
ses = File("ses.png", "256kb image file retrieved from http://www.elcachondo.net/", True, "box", -1)
files["ses.png"] = ses
error_log = File("errorLog.txt", "Damn send function, I'll write it later, not like I need it to evesdrop on conversations...", False)
files["errorLog.txt"] = error_log
return files
Home_Computer = Computer("My_Computer", Constants.home_computer, False)
Home_Computer.files = Home_Computer_Files()
current_computer = Home_Computer
computer_list = {}
def Steve_Waller_Files():
files = {}
saved_fragment = File("savedFragment2.ry", "N/A", True, "lakjdhgfnhkjfbhfhfyghkfjujutrrfrtyujrturgtttygreeetryerlirvioej", 1)
files["savedFragment2.ry"] = saved_fragment
employ_list = File("employLst.lst", "<NAME>\n<NAME>\n<NAME>\n<NAME>\n", True, "password", 8)
files["employLst.lst"] = employ_list
steve_mail = File("SteveMail.hist", Constants.Steve_Mail, False)
files["SteveMail.hist"] = steve_mail
return files
def load_stage1_computers():
global computer_list
Steve_Waller_Security_Consultant = Computer("Steve_Waller_Security_Consultant", Constants.Steve_Waller_Security_Consultant, True, "password", "<PASSWORD>", 10)
Steve_Waller_Security_Consultant.files = Steve_Waller_Files()
computer_list["Steve_Waller_Security_Consultant"] = Steve_Waller_Security_Consultant
return computer_list
def Sally_Stark_Files():
files = {}
saved_fragment_3 = File("savedFragment3.ih", "N/A", True, "asdfjklroidgthjrgtyt464tyer5rgyhrdrfk7yte3wegfgtfktryjrjrt6gjoidfj", 1)
files["savedFragment3.ih"] = saved_fragment_3
present_employ = File("presentEmploy.lst", "Present Employees:\n<NAME>\n<NAME>\<NAME>\n<NAME>\n<NAME>", False)
files["presentEmploy.lst"] = present_employ
sally_mail = File("SallyMail.hist", Constants.Sally_Mail, True, "sally", 8)
files["SallyMail.hist"] = sally_mail
return files
def Richard_Moliere_Files():
files = {}
saved_fragment_0 = File("savedFragment0.jby", "N/A", True, "skjdoidfuvhjerujri473kijtduyhjt58eujfie498e490odeie490we9odeirni", 1)
files["savedFragment0.jby"] = saved_fragment_0
richard_mail = File("RichardMail.hist", Constants.Richard_Mail, True, "password", 8)
files["RichardMail.hist"] = richard_mail
richard_memo = File("RichardMemo.txt", Constants.Richard_Memo, True, "gingerbread", 8)
files["RichardMemo.txt"] = richard_memo
return files
def load_stage2_computers():
global computer_list
Sally_Stark_Receptionist = Computer("Sally_Stark_Receptionist", Constants.Sally_Stark_Receptionist, False)
Sally_Stark_Receptionist.files = Sally_Stark_Files()
computer_list["Sally_Stark_Receptionist"] = Sally_Stark_Receptionist
Richard_Moliere_Security_Consultant = Computer("Richard_Moliere_Security_Consultant", Constants.Richard_Moliere_Security_Consultant, False)
Richard_Moliere_Security_Consultant.files = Richard_Moliere_Files()
computer_list["Richard_Moliere_Security_Consultant"] = Richard_Moliere_Security_Consultant
return computer_list
def Tyrella_Jensen_Files():
files = {}
employees = File("employees.lst", "<NAME>\nAge: 40\n Receptionist\n\n<NAME>\nAge: 33\nSecurity Consultant", True, "christopher", -4)
files["employees.lst"] = employees
tyrella_mail = File("TyrellaMail.hist", Constants.Tyrella_Mail, True, "crissyboo", -4)
files["TyrellaMail.hist"] = tyrella_mail
saved_fragment_1 = File("savedFragment1.ihc", "N/A", True, "irimckjrmey5uih598ersuhig54uierfsuih4t7eskus7ie8i4hvuhs4ihswiuhoisgrieds", 1)
files["savedFragment1.ihc"] = saved_fragment_1
return files
def Amitav_Gutipaty_Files():
files = {}
amitav_memo = File("AmitavMemo.txt", Constants.Amitav_Memo, True, "amitav", 8)
files["AmitavMemo.txt"] = amitav_memo
return files
def Chris_Jensen_Files():
files = {}
pandoras_box = File("pandorasBox.exe", "Unable to read", False)
files["pandorasBox.exe"] = pandoras_box
return files
def load_stage3_computers():
global computer_list
del computer_list["Steve_Waller_Security_Consultant"]
del computer_list["Sally_Stark_Receptionist"]
Tyrella_Jensen_HR_Manager = Computer("Tyrella_Jensen_HR_Manager", Constants.Tyrella_Jensen_HR_Manager, True, "chris", "cs", 3)
Tyrella_Jensen_HR_Manager.files = Tyrella_Jensen_Files()
computer_list["Tyrella_Jensen_HR_Manager"] = Tyrella_Jensen_HR_Manager
Amitav_Gutipaty_Manager = Computer("Amitav_Gutipaty_Manager", Constants.Amitav_Gutipaty_Manager, True, "google", "o", 3)
Amitav_Gutipaty_Manager.files = Amitav_Gutipaty_Files()
computer_list["Amitav_Gutipaty_Manager"] = Amitav_Gutipaty_Manager
Chris_Jensen_HR_Manager = Computer("Chris_Jensen_HR_Manager", Constants.Chris_Jensen_HR_Manager, True, "pheonixeon", "", 3)
computer_list["Chris_Jensen_HR_Manager"] = Chris_Jensen_HR_Manager
return computer_list | ac3829dd132552536a71a03115a9759854653111 | [
"Python"
] | 4 | Python | bububa/Clear-History | 82f2398a26c08a610510e722b53b8b2e0bcdc8d5 | 0505677829fc47e8245d5913f6d78d711ed666c8 | |
refs/heads/master | <file_sep>using System;
namespace LinqToDB.DataProvider.SapHana
{
using Mapping;
public class SapHanaMappingSchema : MappingSchema
{
public SapHanaMappingSchema() : base(ProviderName.SapHana)
{
}
protected SapHanaMappingSchema(string configuration) : base(configuration)
{
}
}
}
| 1d7ec5665f5c1a7895138d977c67a4f2fec08f4d | [
"C#"
] | 1 | C# | reavic/linq2db | 1e641e1d5ea35ec181d4458187ad019a97ef193f | 46869d277d8e8937a43d9336c4cfe1f98e12a68f | |
refs/heads/master | <file_sep>package com.squareandcube.balaji.syncsqlitedatabasewithserver;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.widget.Toast;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Iterator;
import javax.net.ssl.HttpsURLConnection;
public class NetworkStateChecker extends BroadcastReceiver {
//context and database helper object
private Context context;
private DatabaseHelper db;
@Override
public void onReceive(Context context, Intent intent) {
this.context = context;
db = new DatabaseHelper(context);
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
Toast.makeText(context,"checking connection",Toast.LENGTH_LONG).show();
//if there is a network
if (activeNetwork != null) {
//if connected to wifi or mobile data plan
if (activeNetwork.getType() == ConnectivityManager.TYPE_WIFI || activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE) {
//getting all the unsynced names
Cursor cursor = db.getUnsyncedNames();
if (cursor.moveToFirst()) {
do {
Toast.makeText(context,"connected",Toast.LENGTH_LONG).show();
//calling the method to save the unsynced name to MySQL
saveName(
cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_ID)),
cursor.getString(cursor.getColumnIndex(DatabaseHelper.COLUMN_NAME))
);
} while (cursor.moveToNext());
}
}
}
}
public void saveName(final int id, final String name) {
class SendJsonDataTOServer extends AsyncTask<String, Void, String> {
protected void onPreExecute(){
super.onPreExecute();
}
protected String doInBackground(String... params) {
try {
URL url = new URL("https://pusuluribalaji66.000webhostapp.com/CabManagement/public/practice"); // here is your URL path
JSONObject jsonObject = new JSONObject();
jsonObject.put("name", name);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(jsonObject));
writer.flush();
writer.close();
os.close();
int responseCode=conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
BufferedReader in=new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuffer sb = new StringBuffer("");
String line="";
while((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}
else {
return "false : " + responseCode;
}
}
catch(Exception e){
return "Exception: " + e.getMessage();
}
}
@Override
protected void onPostExecute( String result) {
super.onPostExecute(result);
if (result != null) {
try {
JSONObject js = new JSONObject(result);
if(js.has("errorFalse")){
//updating the status in sqlite
db.updateNameStatus(id, MainActivity.NAME_SYNCED_WITH_SERVER);
//sending the broadcast to refresh the list
context.sendBroadcast(new Intent(MainActivity.DATA_SAVED_BROADCAST));
//Toast.makeText(context,result,Toast.LENGTH_SHORT).show();
}
if(js.has("errorTrue")){
Toast.makeText(context,result,Toast.LENGTH_SHORT).show();
}
}catch (Exception e){
e.printStackTrace();
}
}
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
new SendJsonDataTOServer().execute();
}
public String getPostDataString(JSONObject params) throws Exception {
StringBuilder result = new StringBuilder();
boolean first = true;
Iterator<String> itr = params.keys();
while(itr.hasNext()){
String key= itr.next();
Object value = params.get(key);
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(key, "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(value.toString(), "UTF-8"));
}
return result.toString();
}
}
| 1633c57d47195d805d7eb1c8417bfc349677d60e | [
"Java"
] | 1 | Java | balaji66/SyncSqliteDatabaseWithServer | 5e635e425aecc83c6ac0daca60851151ab126675 | 63f470550e2b69d68290c984a569c4335fc2e9ae | |
refs/heads/master | <file_sep># guessword
Code I made for my Practicum test.
<file_sep>#include <iostream>
#include <cstdlib>
#include <string>
#include <conio.h>
#include <ctime>
using namespace std;
int check = 0, n, hp = 8, att = 0, saved = 0, combo = 0, temp = 0;
string assign, nama;
char arr[100], strip[100], attempt[100], guess, mode = '0', category = '0', pass = '0';
bool finish = 1, cont = 1, confirm = false;
struct player {
string name;
int solved;
};
void match(char f, int n);
void attempts(char f);
void initiate();
void choose();
void input();
void the_game();
void continues();
void color();
void country();
void food();
void intro();
void sorting();
int main() {
player plays[4];
plays[0].name = "JOE";
plays[1].name = "IVN";
plays[2].name = "BOT";
plays[3].name = "Unknown";
plays[0].solved = 6;
plays[1].solved = 2;
plays[2].solved = 20;
plays[3].solved = 0;
cout << "===================================================" << endl;
cout << "\t Welcome to 'Guess the Word!'" << endl << endl;
cout << "\t\t Created by:" << endl;
cout << "\t\t JurgenStr" << endl << endl;
cout << "\t Press any key to continue..." << endl;
cout << "===================================================" << endl;
system("pause");
system("cls");
cout << "===================================================" << endl;
cout << "\t Hello! What's your name?" << endl;
cout << "\t 3 characters needed." << endl;
cout << "===================================================\t" << endl;
while (nama.length() < 3 || nama.length() > 3) {
getline(cin, nama);
for (int i=0;i<nama.length();i++) {
nama[i] = toupper(nama[i]);
}
plays[3].name = nama;
}
while (cont == 1) {
plays[3].solved = temp;
combo = 0;
initiate();
while (mode == '1') {
input();
the_game();
continues();
}
while (mode == '2') {
choose();
while (category == '1') {
country();
the_game();
continues();
}
while (category == '2') {
color();
the_game();
continues();
}
while (category == '3') {
food();
the_game();
continues();
}
}
while (mode == '3') {
intro();
}
while (mode == '4') {
plays[3].solved = temp;
for(int i=0;i<4;i++){
for(int j=0;j<4;j++){
if(plays[i].solved > plays[j].solved){
swap(plays[j],plays[i]);
}
}
}
cout << "===================================================" << endl;
cout << " LEADERBOARD" << endl;
cout << "===================================================" << endl;
for (int i=0; i<4; i++) {
cout << i+1 << ". " << plays[i].name << "\t\t\t\t" << plays[i].solved << endl;
}
cout << endl;
mode = '0';
system("pause");
system("cls");
}
while (mode == '5') {
system("cls");
return 0;
}
}}
// Algorithm to check match
void match (char f, int n) {
system("cls");
finish = 1;
for (int i=0;i<n;i++) {
if (toupper(f) == arr[i]) {
strip[i] = toupper(f);
saved = 1;
}}
if (att >= 1) {
for (int i=0;i<att;i++) {
if (toupper(f) == attempt[i]) {
saved = 2;
}}}
if (saved == 0) {
cout << "===================================================" << endl;
cout << "\t\t Oof, wrong!" << endl;
--hp;
attempts(f);}
if (saved == 1) {
cout << "===================================================" << endl;
cout << "\t\tYou got it right!" << endl;
attempts(f);}
if (saved == 2) {
cout << "===================================================" << endl;
cout << "\t\tYou've tried that before..." << endl;}
}
void attempts (char f) {
attempt[att] = toupper(f);
att++;}
void initiate() {
while (mode != '1' && mode != '2' && mode != '3' && mode != '4' && mode != '5') {
system("cls");
cout << "===================================================" << endl;
cout << "Player: " << nama << endl;
cout << "===================================================" << endl;
cout << "Choose mode:" << endl;
cout << "1. Manual Input" << endl;
cout << "2. Preset Words" << endl;
cout << "3. How to Play" << endl;
cout << "4. Leaderboard" << endl;
cout << "5. Quit Game" << endl << endl;
cout << "Enter number to choose: ";
cin >> mode;
cin.ignore();
}
system("cls");}
void choose() {
while (category != '1' && category != '2' && category != '3'){
system("cls");
cout << "===================================================" << endl;
cout << " PRESET MODE" << endl;
cout << "===================================================" << endl;
cout << "In this mode, you'll be given a mystery word." << endl;
cout << "The goal is simple, guess the word." << endl;
cout << "Each time you guessed the word, you'll get +2 HP." << endl << endl;
cout << "Until now, you've completed " << combo << " rounds." << endl << endl;
system("pause");
system("cls");
cout << "===================================================" << endl;
cout << " PRESET MODE" << endl;
cout << "===================================================" << endl;
cout << "Health Points (Remaining Attempts): " << hp << endl << endl;
cout << "Rounds completed: " << combo << endl << endl;
cout << "Choose category:" << endl;
cout << "1. Country" << endl;
cout << "2. Color" << endl;
cout << "3. Food" <<endl << endl;
cout << "Enter '1' or '2' or '3' to choose: ";
cin >> category;
cin.ignore();
}
system("cls");}
void country() {
string words[17] = {
"indonesia", "inggris", "jepang", "malaysia", "thailand", "afrika selatan",
"china", "singapura", "myanmar", "vietnam", "brazil",
"argentina", "belanda", "jerman", "rusia",
"honduras", "senegal"
};
srand(time(0));
int r = (rand() % 16);
assign = words[r];
n = assign.size();
for (int j = 0; j < n; j++) {
assign[j] = toupper(assign[j]);
}
assign.copy(arr, assign.size() + 1);
arr[n] = '\0';
system("cls");}
void color() {
string words[17] = {
"merah", "hitam", "orange", "magenta", "violet", "perak",
"kuning", "putih", "abu abu", "emas", "nila",
"hijau", "ungu", "pink", "dongker",
"biru", "coklat"
};
srand(time(0));
int r = (rand() % 16);
assign = words[r];
n = assign.size();
for (int j = 0; j < n; j++) {
assign[j] = toupper(assign[j]);
}
assign.copy(arr, assign.size() + 1);
arr[n] = '\0';
system("cls");}
void food() {
string words[17] = {
"nasi goreng", "burger", "kentang goreng", "nugget", "risol", "nasi telur",
"mie goreng", "pizza", "es kepal milo", "sosis", "tahu bakso crispy",
"magelangan", "roti bakar", "bakwan kawi", "bakso",
"ikan bakar", "ayam goreng"
};
srand(time(0));
int r = (rand() % 16);
assign = words[r];
n = assign.size();
for (int j = 0; j < n; j++) {
assign[j] = toupper(assign[j]);
}
assign.copy(arr, assign.size() + 1);
arr[n] = '\0';
system("cls");}
void input() {
cout << "===================================================" << endl;
cout << " MANUAL MODE" << endl;
cout << "===================================================" << endl;
cout << "2 players needed." << endl;
cout << "The first player will give the mystery word." << endl;
cout << "The second player must guess the word with 8 HP." << endl << endl;
system("pause");
cout << endl << "Input the mystery word here: ";
do {
getline(cin, assign);
n = assign.size();
for (int j = 0; j < n; j++) {
assign[j] = toupper(assign[j]);
}
assign.copy(arr, assign.size() + 1);
arr[n] = '\0';
check++;
} while (check == 0);
system("cls");}
void the_game() {
// Game Start
cout << "----------GAME READY----------" << endl;
for (int i=0;i<n;i++) {
strip[i] = '*';
if (assign[i] == ' ') {
strip[i] = assign[i]; }
}
system("pause");
system("cls");
while (pass == '0') {
saved = 0;
if (mode == '1') {
cout << "===================================================" << endl;
cout << " MANUAL MODE" << endl;
cout << "===================================================" << endl;
}
if (mode == '2') {
cout << "===================================================" << endl;
cout << " PRESET MODE" << endl;
cout << "===================================================" << endl;
}
cout << "Words: " << n << endl;
cout << "HP: " << hp << endl << endl;
for (int i=0;i<n;i++) {
cout << strip[i];
}
cout << endl;
cout << "Input attempts: ";
if (att != 0) {
for (int j = 0;j <= att; j++) {
cout << attempt[j] << " ";
}
}
cout << endl;
do {
cin >> guess;}
while (! (( guess >= 'a' && guess <= 'z' ) || ( guess >= 'A' && guess <= 'Z' )) );
cin.ignore();
match(guess, n);
// Checking if finished
for (int i=0;i<n;i++) {
if (strip[i] != arr[i]) {
finish = 0;
break;
}
if (i == (n-1) && finish == 1) {
cout << endl << "\t\t ";
for (int j=0;j<n;j++) {
cout << strip[j];
}
cout << "\n\n\t Good job! You solved it!" << endl;
cout << "===================================================\n\n";
pass = '1';
att++;
}
}
if (hp <= 0) {
system("cls");
cout << "===================================================" << endl;
cout << "GAME OVER" << endl << endl;
cout << "The word was: " << endl;
pass = '2';
for (int i=0;i<n; i++) {
cout << assign[i];
}
cout << "\n\n===================================================" << endl;
cout << endl;
}} system("pause");}
void continues() {
system("cls");
if (mode == '2' && pass == '1') {
combo++;
temp++;
++hp; ++hp;
confirm = true;
}
cout << "===========================================================" << endl;
cout << "\t\t\tContinue?\n\n";
cout << " Press any key to continue, or press 'N' to stop." << endl;
cout << "===========================================================" << endl;
cin >> guess;
cin.ignore();
if (confirm) {
if (guess == 'n' || guess == 'N') {
pass = '0';
for (int i=0;i<att;i++) {
attempt[i] = ' ';}
att = 0;
category = '0';
temp = combo;
mode = '0';
confirm = 0;
//temp = combo;
initiate();
}}
if (guess == 'n' || guess == 'N') {
cont = false;}
category = '0';
if (confirm == 1) {
pass = '0';
confirm = 0;
for (int i=0;i<att;i++) {
attempt[i] = ' ';}
att = 0;
choose();
}
if (mode == '1' || pass == '2') {
pass = '0';
hp = 8;
combo = 0;
mode = '0';
}
if (mode == '2' && pass == '2') {
pass = '0';
hp = 8;
temp = combo;
mode = '0';
}
for (int i=0;i<att;i++) {
attempt[i] = ' ';
}
att = 0;
// att = 0;
// pass = '0';
// category = '0';
system("cls");
}
void intro() {
cout << "=====================================================================" << endl;
cout << "\t\tWelcome to Guess The Word!" << endl << endl;
cout << "Your task is simple. Guess the mysterious word in each round!" << endl;
cout << "You'll be given 8 HP (Health Points) in the beginning of the game." << endl;
cout << "Every time you guessed the word, 2 HP will be added to your HP pool." << endl << endl;
cout << "Press 'Enter' to go back..." << endl;
cout << "=====================================================================" << endl;
getchar();
att = 0;
mode = '0';
category = '0';
system("cls");
}
/* do {
cin >> guess;}
while (! (( guess >= 'a' && guess <= 'z' ) || ( guess >= 'A' && guess <= 'Z' )) );
cin.ignore(); */
| fcc6f934b2e1cae4dfffe86b35a1d9a421a72907 | [
"Markdown",
"C++"
] | 2 | Markdown | JurgenStrek/word-guess | 40b133a554d72ca46159548849966aee85c4c592 | 33e48b1159c4424078f5ef3130a71da644914e01 | |
refs/heads/master | <repo_name>Thioubado/o<file_sep>/themes/olympos/partials/footer.htm
<div class="main-footer">
<div class="container">
<h3>Our footer</h3>
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Minima est atque ratione consequatur dicta amet ad, corporis pariatur aperiam sunt provident quia? Commodi totam aspernatur quibusdam magni quo, praesentium facilis.</p>
</div>
</div><file_sep>/config/BdD/momo_movies_.sql
-- phpMyAdmin SQL Dump
-- version 4.8.0
-- https://www.phpmyadmin.net/
--
-- Hôte : localhost
-- Généré le : jeu. 26 avr. 2018 à 03:16
-- Version du serveur : 10.1.31-MariaDB
-- Version de PHP : 7.2.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de données : `o`
--
-- --------------------------------------------------------
--
-- Structure de la table `momo_movies_`
--
CREATE TABLE `momo_movies_` (
`id` int(10) UNSIGNED NOT NULL,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`description` text COLLATE utf8mb4_unicode_ci,
`year` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
--
-- Déchargement des données de la table `momo_movies_`
--
INSERT INTO `momo_movies_` (`id`, `name`, `description`, `year`) VALUES
(1, 'Inception Momo', '<p>Sed vehicula ex eget enim euismod, vitae laoreet magna convallis. Vestibulum fermentum ut massa id auctor. Vivamus est velit, porttitor sed dui vel, fermentum viverra ex. Morbi dapibus tincidunt porta. Donec lectus dolor, pellentesque at blandit a, porttitor ut ex. Aenean non po</p>', 2011),
(2, 'Fight club Momo', '<p>orem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus auctor ullamcorper nunc eget auctor. Nulla metus nisi, ultrices ac tellus vel, volutpat cursus nulla. Donec rutrum malesuada nibh non posuere. Pellentesque ultricies, turpis sed auctor pharetra, nulla erat euismod eros, id porttitor mauris i</p>', 1999),
(3, 'American beauty Momo', '<p>eget lobortis sem nibh euismod nisi. Sed vehicula ex eget enim euismod, vitae laoreet magna convallis. Vestibulum fermentum ut massa id auctor. Vivamus est velit, porttitor sed dui vel, fermentum viverra ex. Morbi dapibus tincidunt porta. Donec lectus dolor, pellentesque at blandit a, porttitor ut ex.</p>', 2001);
--
-- Index pour les tables déchargées
--
--
-- Index pour la table `momo_movies_`
--
ALTER TABLE `momo_movies_`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT pour les tables déchargées
--
--
-- AUTO_INCREMENT pour la table `momo_movies_`
--
ALTER TABLE `momo_movies_`
MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=4;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| 5d1fdc8b0c99a336c9bc9de0e74e77fa8e6637c5 | [
"SQL",
"HTML"
] | 2 | HTML | Thioubado/o | 9b16e819957470c8dbce2288f09c6bd9afd05cac | 501ca93a0964dfb5d6deb095006b11f55e4ba61f | |
refs/heads/master | <file_sep>//
// Created by Zealydalal on 4/18/2016.
//
#include <iostream>
#include <ctime>
#include "dropbox.h"
#include "/Dropbox-C-master/memStream/include/memStream.h"
using namespace std;
class Encrypt_and_Upload_to_Dropbox
{
public:
int encryptFunction();
const char* strFromBool(bool b);
void displayAccountInfo(drbAccountInfo *info);
void displayMetadata(drbMetadata *meta, char *title);
void displayMetadataList(drbMetadataList* list, char* title);
};
const char* Encrypt_and_Upload_to_Dropbox::strFromBool(bool b) { return b ? "true" : "false"; }
/*!
* \brief Display a drbAccountInfo item in stdout.
* \param info account informations to display.
* \return void
*/
void Encrypt_and_Upload_to_Dropbox::displayAccountInfo(drbAccountInfo* info) {
if(info) {
printf("---------[ Account info ]---------\n");
if(info->referralLink) printf("referralLink: %s\n", info->referralLink);
if(info->displayName) printf("displayName: %s\n", info->displayName);
if(info->uid) printf("uid: %d\n", *info->uid);
if(info->country) printf("country: %s\n", info->country);
if(info->email) printf("email: %s\n", info->email);
if(info->quotaInfo.datastores) printf("datastores: %u\n", *info->quotaInfo.datastores);
if(info->quotaInfo.shared) printf("shared: %u\n", *info->quotaInfo.shared);
if(info->quotaInfo.quota) printf("quota: %u\n", *info->quotaInfo.quota);
if(info->quotaInfo.normal) printf("normal: %u\n", *info->quotaInfo.normal);
}
}
/*!
* \brief Display a drbMetadataList item in stdout.
* \param list list to display.
* \param title display the title before the list.
* \return void
*/
void Encrypt_and_Upload_to_Dropbox::displayMetadataList(drbMetadataList* list, char* title) {
if (list){
printf("---------[ %s ]---------\n", title);
for (int i = 0; i < list->size; i++) {
displayMetadata(list->array[i], list->array[i]->path);
}
}
}
/*!
* \brief Display a drbMetadata item in stdout.
* \param meta metadata to display.
* \param title display the title before the metadata.
* \return void
*/
void Encrypt_and_Upload_to_Dropbox::displayMetadata(drbMetadata* meta, char* title) {
if (meta) {
if(title) printf("---------[ %s ]---------\n", title);
if(meta->hash) printf("hash: %s\n", meta->hash);
if(meta->rev) printf("rev: %s\n", meta->rev);
if(meta->thumbExists) printf("thumbExists: %s\n", strFromBool(*meta->thumbExists));
if(meta->bytes) printf("bytes: %d\n", *meta->bytes);
if(meta->modified) printf("modified: %s\n", meta->modified);
if(meta->path) printf("path: %s\n", meta->path);
if(meta->isDir) printf("isDir: %s\n", strFromBool(*meta->isDir));
if(meta->icon) printf("icon: %s\n", meta->icon);
if(meta->root) printf("root: %s\n", meta->root);
if(meta->size) printf("size: %s\n", meta->size);
if(meta->clientMtime) printf("clientMtime: %s\n", meta->clientMtime);
if(meta->isDeleted) printf("isDeleted: %s\n", strFromBool(*meta->isDeleted));
if(meta->mimeType) printf("mimeType: %s\n", meta->mimeType);
if(meta->revision) printf("revision: %d\n", *meta->revision);
if(meta->contents) displayMetadataList(meta->contents, "Contents");
}
}
int Encrypt_and_Upload_to_Dropbox::encryptFunction()
{
int err;
void* output;
char *app_key = "your consumer key";
char *app_secret = "your consumer secret";
char *t_key = NULL; //< access token key
char *t_secret = NULL; //< access token secret
drbInit();
drbClient* cli = drbCreateClient(app_key, app_secret, t_key, t_secret);
// Request a AccessToken if undefined (NULL)
if(!t_key || !t_secret) {
drbOAuthToken* reqTok = drbObtainRequestToken(cli);
if (reqTok) {
char* url = drbBuildAuthorizeUrl(reqTok);
printf("Please visit %s\nThen press Enter...\n", url);
free(url);
fgetc(stdin);
drbOAuthToken* accTok = drbObtainAccessToken(cli);
if (accTok) {
// This key and secret can replace the NULL value in t_key and
// t_secret for the next time.
printf("key: %s\nsecret: %s\n", accTok->key, accTok->secret);
} else{
fprintf(stderr, "Failed to obtain an AccessToken...\n");
return EXIT_FAILURE;
}
} else {
fprintf(stderr, "Failed to obtain a RequestToken...\n");
return EXIT_FAILURE;
}
}
// Set default arguments to not repeat them on each API call
drbSetDefault(cli, DRBOPT_ROOT, DRBVAL_ROOT_AUTO, DRBOPT_END);
// Read account Informations
output = NULL;
err = drbGetAccountInfo(cli, &output, DRBOPT_END);
if (err != DRBERR_OK) {
printf("Account info error (%d): %s\n", err, (char*)output);
free(output);
} else {
drbAccountInfo* info = (drbAccountInfo*)output;
displayAccountInfo(info);
drbDestroyAccountInfo(info);
}
// List root directory files
output = NULL;
err = drbGetMetadata(cli, &output,
DRBOPT_PATH, "/",
DRBOPT_LIST, true,
// DRBOPT_FILE_LIMIT, 100,
DRBOPT_END);
if (err != DRBERR_OK) {
printf("Metadata error (%d): %s\n", err, (char*)output);
free(output);
} else {
drbMetadata* meta = (drbMetadata*)output;
displayMetadata(meta, "Metadata");
drbDestroyMetadata(meta, true);
}
time_t rawtime;
struct tm * timeinfo;
char buffer[80];
char buffer2[80];
time (&rawtime);
timeinfo = localtime(&rawtime);
strftime(buffer,80,"%d%m%Y%I%M%S",timeinfo);
strftime(buffer2,80,"%d-%m-%Y %I:%M:%S",timeinfo);
std::string timestr(buffer);
std::string datestr(buffer2);
cout<<"Enter File Name:"<<endl;
string fname;
cin>>fname;
//Random private key generation
char *s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < 10; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
// Free all client allocated memory
drbDestroyClient(cli);
// Global Cleanup
drbCleanup();
return EXIT_SUCCESS;
}
<file_sep>//
// Created by Zealydalal on 4/18/2016.
//
#include <iostream>
#include <string>
#include <dropbox.h>
#include <memStream.h>
using namespace std;
class Decrypt_and_Download_from_Dropbox
{
public:
void decryptFunction();
private:
void displayAccountInfo(drbAccountInfo *info);
void displayMetadata(drbMetadata *meta, char *title);
void displayMetadataList(drbMetadataList* list, char* title);
};
void Decrypt_and_Download_from_Dropbox::decryptFunction()
{
int err;
void *output;
char *app_key = "your consumer key";
char *app_secret = "your consumer secret";
char *t_key = NULL; //< access token key
char *t_secret = NULL; //< access token secret
char *filename = NULL; //name of file to be downloaded
string directory = "/Download/"; //default directory
drbInit();
drbClient* cli = drbCreateClient(app_key, app_secret, t_key, t_secret);
// Request a AccessToken if undefined (NULL)
if(!t_key || !t_secret) {
drbOAuthToken* reqTok = drbObtainRequestToken(cli);
if (reqTok) {
char* url = drbBuildAuthorizeUrl(reqTok);
printf("Please visit %s\nThen press Enter...\n", url);
free(url);
fgetc(stdin);
drbOAuthToken* accTok = drbObtainAccessToken(cli);
if (accTok) {
// This key and secret can replace the NULL value in t_key and
// t_secret for the next time.
printf("key: %s\nsecret: %s\n", accTok->key, accTok->secret);
} else{
fprintf(stderr, "Failed to obtain an AccessToken...\n");
}
} else {
fprintf(stderr, "Failed to obtain a RequestToken...\n");
}
}
// Set default arguments to not repeat them on each API call
drbSetDefault(cli, DRBOPT_ROOT, DRBVAL_ROOT_AUTO, DRBOPT_END);
// Read account Informations
output = NULL;
err = drbGetAccountInfo(cli, &output, DRBOPT_END);
if (err != DRBERR_OK) {
printf("Account info error (%d): %s\n", err, (char*)output);
free(output);
} else {
drbAccountInfo* info = (drbAccountInfo*)output;
displayAccountInfo(info);
drbDestroyAccountInfo(info);
}
// List root directory files
output = NULL;
err = drbGetMetadata(cli, &output,
DRBOPT_PATH, "/",
DRBOPT_LIST, true,
// DRBOPT_FILE_LIMIT, 100,
DRBOPT_END);
if (err != DRBERR_OK) {
printf("Metadata error (%d): %s\n", err, (char*)output);
free(output);
} else {
drbMetadata* meta = (drbMetadata*)output;
displayMetadata(meta, "Metadata");
drbDestroyMetadata(meta, true);
}
//Getting the filename the user wish to download
cout << "Input the name of file you want to download:";
cin >> filename;
FILE *file = fopen(directory+"tmp", "w"); // Write it in temp file
output = NULL;
err = drbGetFile(cli, &output,
DRBOPT_PATH, "/tmp",
DRBOPT_IO_DATA, file,
DRBOPT_IO_FUNC, fwrite,
DRBOPT_END);
fclose(file);
if (err != DRBERR_OK) {
printf("Get File error (%d): %s\n", err, (char*)output);
free(output);
} else {
displayMetadata((drbMetadata*)output, "Get File Result");
drbDestroyMetadata((drbMetadata*)output, true);
}
//Decrypt the downloaded file and write into dest file
// Free all client allocated memory
drbDestroyClient(cli);
// Global Cleanup
drbCleanup();
}
/*!
* \brief Display a drbAccountInfo item in stdout.
* \param info account informations to display.
* \return void
*/
void Decrypt_and_Download_from_Dropbox::displayAccountInfo(drbAccountInfo* info) {
if(info) {
printf("---------[ Account info ]---------\n");
if(info->referralLink) printf("referralLink: %s\n", info->referralLink);
if(info->displayName) printf("displayName: %s\n", info->displayName);
if(info->uid) printf("uid: %d\n", *info->uid);
if(info->country) printf("country: %s\n", info->country);
if(info->email) printf("email: %s\n", info->email);
if(info->quotaInfo.datastores) printf("datastores: %u\n", *info->quotaInfo.datastores);
if(info->quotaInfo.shared) printf("shared: %u\n", *info->quotaInfo.shared);
if(info->quotaInfo.quota) printf("quota: %u\n", *info->quotaInfo.quota);
if(info->quotaInfo.normal) printf("normal: %u\n", *info->quotaInfo.normal);
}
}
const char* strFromBool(bool b) { return b ? "true" : "false"; }
/*!
* \brief Display a drbMetadata item in stdout.
* \param meta metadata to display.
* \param title display the title before the metadata.
* \return void
*/
void Decrypt_and_Download_from_Dropbox::displayMetadata(drbMetadata* meta, char* title) {
if (meta) {
if(title) printf("---------[ %s ]---------\n", title);
if(meta->hash) printf("hash: %s\n", meta->hash);
if(meta->rev) printf("rev: %s\n", meta->rev);
if(meta->thumbExists) printf("thumbExists: %s\n", strFromBool(*meta->thumbExists));
if(meta->bytes) printf("bytes: %d\n", *meta->bytes);
if(meta->modified) printf("modified: %s\n", meta->modified);
if(meta->path) printf("path: %s\n", meta->path);
if(meta->isDir) printf("isDir: %s\n", strFromBool(*meta->isDir));
if(meta->icon) printf("icon: %s\n", meta->icon);
if(meta->root) printf("root: %s\n", meta->root);
if(meta->size) printf("size: %s\n", meta->size);
if(meta->clientMtime) printf("clientMtime: %s\n", meta->clientMtime);
if(meta->isDeleted) printf("isDeleted: %s\n", strFromBool(*meta->isDeleted));
if(meta->mimeType) printf("mimeType: %s\n", meta->mimeType);
if(meta->revision) printf("revision: %d\n", *meta->revision);
if(meta->contents) displayMetadataList(meta->contents, "Contents");
}
}
/*!
* \brief Display a drbMetadataList item in stdout.
* \param list list to display.
* \param title display the title before the list.
* \return void
*/
void Decrypt_and_Download_from_Dropbox::displayMetadataList(drbMetadataList* list, char* title) {
if (list){
printf("---------[ %s ]---------\n", title);
for (int i = 0; i < list->size; i++) {
displayMetadata(list->array[i], list->array[i]->path);
}
}
}<file_sep>//
// Created by Zealydalal on 4/18/2016.
//
#ifndef CRYPTO_PROJECT_2_DECRYPT_AND_DOWNLOAD_FROM_DROPBOX_H
#define CRYPTO_PROJECT_2_DECRYPT_AND_DOWNLOAD_FROM_DROPBOX_H
class Decrypt_and_Download_from_Dropbox
{
public:
void decryptFunction();
};
#endif //CRYPTO_PROJECT_2_DECRYPT_AND_DOWNLOAD_FROM_DROPBOX_H
<file_sep>cmake_minimum_required(VERSION 3.5)
project(Crypto_Project_2)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
aux_source_directory(./Dropbox-C-master/crypto CRYPTO_LIB_DIR)
include_directories( ./Dropbox-C-master/crypto )
add_library(Cryptopp ${CRYPTO_LIB_DIR})
aux_source_directory(./Dropbox-C-master/Dropbox/src DROPBOX_LIB_DIR)
include_directories( ./Dropbox-C-master/Dropbox/include ./Dropbox-C-master/jansson-2.7/src ./Dropbox-C-master/liboauth-1.0.3/src ./Dropbox-C-master/memStream/include)
add_library(Dropbox ${DROPBOX_LIB_DIR})
set(SOURCE_FILES main.cpp Encrypt_and_Upload_to_Dropbox.cpp Decrypt_and_Download_from_Dropbox.cpp)
add_executable(Crypto_Project_2 ${SOURCE_FILES})
target_link_libraries(Crypto_Project_2 Cryptopp Dropbox)<file_sep>#include <iostream>
#include "Encrypt_and_Upload_to_Dropbox.h"
#include "Decrypt_and_Download_from_Dropbox.h"
using namespace std;
int main() {
cout << "Select from the choices" << endl;
cout << "1. Encrypt and upload a file:" << endl;
cout << "2. Decrypt and download a file:" << endl;
int n;
cin >> n;
Encrypt_and_Upload_to_Dropbox encryptfile;
Decrypt_and_Download_from_Dropbox decryptfile;
if(n==1)
encryptfile.encryptFunction();
else if(n==2)
decryptfile.decryptFunction();
return 0;
}<file_sep>//
// Created by Zealydalal on 4/18/2016.
//
#ifndef CRYPTO_PROJECT_2_ENCRYPT_AND_UPLOAD_TO_DROPBOX_H
#define CRYPTO_PROJECT_2_ENCRYPT_AND_UPLOAD_TO_DROPBOX_H
class Encrypt_and_Upload_to_Dropbox
{
public:
void encryptFunction();
};
#endif //CRYPTO_PROJECT_2_ENCRYPT_AND_UPLOAD_TO_DROPBOX_H
| 56c543cba70552c44c216fcab750eb874e44fca8 | [
"CMake",
"C++"
] | 6 | C++ | zealdalal/Crypto_Proj_2 | 1a9b53ae216ad42480c0f3fbbb8352e8f7ffd284 | 94f33609017fe7d09103a9aef233be417a82ea5c | |
refs/heads/master | <file_sep>package com.szikora.ccvid;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
public class ProfileActivity extends AppCompatActivity {
private SharedPreferences mPrefs;
private EditText newPassword, passwordAgain;
private TextView profileLabel;
private TextInputLayout newPasswordLayout, passwordAgainLayout;
private ImageView profileImage;
private String currentUserEmail;
private String [] messagesToUser;
private Gson gson;
private User user;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
initialization();
setProfile();
}
private void initialization() {
currentUserEmail = getIntent().getStringExtra("email");
newPassword = (EditText) findViewById(R.id.newPasswordField);
passwordAgain = (EditText) findViewById(R.id.passwordAgainField);
profileLabel = (TextView) findViewById(R.id.profileLabel);
newPasswordLayout = (TextInputLayout) findViewById(R.id.newPasswordLayout);
passwordAgainLayout = (TextInputLayout) findViewById(R.id.passwordAgainLayout);
profileImage = (ImageView) findViewById(R.id.profileImage);
mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
gson = new Gson();
user = new User();
messagesToUser = new String[] {
"Passwords do not match!",
"Successfully saved changes!",
};
}
private void setProfile() {
profileLabel.setText(currentUserEmail);
String profileImageName = currentUserEmail.replace("@", "").replace(".", "");
int profileImageId = getResources().getIdentifier(profileImageName, "drawable", getPackageName());
profileImage.setImageResource(profileImageId);
}
public void saveButtonClick(View view) {
if (!newPassword.getText().toString().matches(SigningActivity.passwordRegex)) {
newPasswordLayout.setError(SigningActivity.messageToUser[5]);
passwordAgainLayout.setError(null);
} else if (!newPassword.getText().toString().equals(passwordAgain.getText().toString())) {
passwordAgainLayout.setError(messagesToUser[0]);
newPasswordLayout.setError(null);
} else {
updateUser();
newPasswordLayout.setError(null);
passwordAgainLayout.setError(null);
Toast.makeText(this, messagesToUser[1], Toast.LENGTH_LONG).show();
}
}
private void updateUser() {
SharedPreferences.Editor prefsEditor = mPrefs.edit();
user.setEmail(currentUserEmail);
user.setPassword(newPassword.getText().toString());
String userJson = gson.toJson(user);
prefsEditor.putString(user.getEmail(), userJson);
prefsEditor.apply();
}
}
| 2ae5f241dcc67b5e2f86699acd76a3c197befdf4 | [
"Java"
] | 1 | Java | AtillaSzikora/I_ANDROID_ccVid | 475252dec9963d9e9d4859057529fca8dd1278a6 | d2e20fccb7940308e13e4cc0308aec1dbe3d7eb3 | |
refs/heads/master | <repo_name>vincea92/basic-node-rest-api<file_sep>/routes.js
'use strict';
var express = require("express");
var router = express.Router();
//GET /users/vince
router.get("/players/iginla", function(req, res){
res.json({
name: "<NAME>",
goals: "27",
assists: "65",
points: "92",
team: "<NAME>",
position: "Right Wing"
});
});
module.exports = router;
| 7f4323300ca9d0bcb68ede5b820334439824f45a | [
"JavaScript"
] | 1 | JavaScript | vincea92/basic-node-rest-api | 156e641598aa761997896188b2728cd0916c3d56 | 53d330f8bd91f1161f3e906e6c07ca6c7e3e5b52 | |
refs/heads/master | <repo_name>jb-wagner/alex-gram<file_sep>/src/models/user.ts
export default class User {
username: string;
name: string;
image: string;
constructor(username: string, name: string, image: string) {
this.username = username;
this.name = name;
this.image = image;
}
}
<file_sep>/src/models/location.ts
type Coordinates = [Number, Number];
export default class Location {
name: string = "";
coordinates: Coordinates | undefined = undefined;
}
<file_sep>/src/models/feed.ts
import { Post } from "./post";
export default class Feed {
posts: Post[] = [];
}
<file_sep>/README.md
# Run Application
## Typescript
```
yarn build-watch
```
## Expo
```
expo start
```<file_sep>/src/models/index.ts
import { Post, postGenerator } from "./post";
import Feed from "./feed";
import User from "./user";
import Location from "./location";
export { Post, Feed, User, Location, postGenerator };
<file_sep>/src/models/post.ts
import User from "./user";
import Location from "./location";
export class Post {
image: string;
caption: string;
user: User;
likes: Number;
location: Location | null;
constructor(
image: string,
caption: string,
user: User,
likes: Number,
location: Location | null = null
) {
this.image = image;
this.caption = caption;
this.user = user;
this.likes = likes;
this.location = location;
}
}
var imageLocations = [
"http://placebear.com/{width}/{height}",
"http://placekitten.com/{width}/{height}",
"http://fillmurray.com/{width}/{height}",
"http://www.placecage.com/{width}/{height}",
"http://lorempizza.com/{width}/{height}"
];
var captions = [
"Jig Is Up",
"Cut The Mustard",
"Curiosity Killed The Cat",
"<NAME>",
"All Greek To Me",
"Burst Your Bubble",
"Under the Weather",
"Close But No Cigar",
"On Cloud Nine",
"Son of a Gun",
"Money Doesn't Grow On Trees",
"Jack of All Trades Master of None",
"Under Your Nose",
"Ring Any Bells?",
"Mountain Out of a Molehill",
"No Ifs, Ands, or Buts",
"No-Brainer",
"Scot-free",
"Roll With the Punches",
"Jaws of Death",
"Swinging For the Fences",
"Up In Arms",
"Foaming At The Mouth",
"Heads Up",
"Man of Few Words",
"Jaws of Life",
"A Piece of Cake",
"Head Over Heels",
"Back To the Drawing Board",
"Short End of the Stick",
"Know the Ropes",
"My Cup of Tea",
"Like Father Like Son",
"There's No I in Team",
"Between a Rock and a Hard Place",
"Birds of a Feather Flock Together",
"Fish Out Of Water",
"Fight Fire With Fire",
"Wouldn't Harm a Fly",
"Dropping Like Flies",
"Right Off the Bat",
"Playing For Keeps",
"Rain on Your Parade",
"Goody Two-Shoes",
"Wild Goose Chase",
"Down To The Wire",
"Go For Broke",
"On the Same Page",
"Drawing a Blank",
"Quality Time",
"Put a Sock In It",
"Keep Your Shirt On",
"A Dime a Dozen",
"Beating a Dead Horse",
"Par For the Course",
"Cut To The Chase",
"Easy As Pie",
"Quick On the Draw",
"Keep On Truckin'",
"Cup Of Joe",
"Yada Yada",
"Love Birds",
"It's Not All It's Cracked Up To Be",
"You Can't Teach an Old Dog New Tricks",
"Greased Lightning",
"Tough It Out"
];
var users = [
new User(
"World's Best Boss",
"<NAME>",
"http://www.businessnewsdaily.com/images/i/000/008/678/original/michael-scott-the-office.PNG?1431534974"
),
new User(
"dschrute",
"<NAME>",
"https://tse4.mm.bing.net/th?id=OIP.AG4E30Kqq-yephzM7PBCQwHaHa&w=212&h=194&c=7&o=5&dpr=1.25&pid=1.7"
),
new User(
"jimmyhalpert",
"<NAME>",
"https://tse1.mm.bing.net/th?id=OIP.Qyjj9XwNbT1dwGfKOelEvgHaHa&pid=Api"
),
new User(
"pambam",
"<NAME>",
"http://images.buddytv.com/btv_2_500261069_1_434_593_0_/pam-beesly-photos.jpg"
),
new User(
"wuphf_creator",
"<NAME>",
"http://img3.wikia.nocookie.net/__cb20140726043954/theoffice/images/e/e0/Ryan2.jpg"
),
new User(
"the_narddog",
"<NAME>",
"http://i2.cdnds.net/11/38/618_ustv_the_office_andy_bernard.jpg"
),
new User(
"stan_the_man",
"<NAME>",
"https://tse3.mm.bing.net/th?id=OIP.j9qTl-PnLZ9IFzFDKPAtMQHaJ4&pid=Api"
),
new User(
"justKev",
"<NAME>",
"https://images.rapgenius.com/54e03e0b8cc2e06aeff73429221709c3.749x1000x1.png"
),
new User(
"cat_lover",
"<NAME>",
"http://www.officetally.com/wp-content/uploads/2009/04/angela-kinsey-angela-martin-the-office-2.jpg"
),
new User(
"oscar",
"<NAME>",
"https://tse2.mm.bing.net/th?id=OIP.PEc4nYJj6ovr3sdRkDlQOAHaJ4&pid=Api"
),
new User(
"phyllis",
"<NAME>",
"http://www.officetally.com/wp-content/uploads/2009/03/phyllis-smith-phyllis-lapin-vance-the-office.jpg"
)
];
declare global {
interface Array<T> {
randomElement(): T;
}
}
Array.prototype.randomElement = function() {
return this[Math.floor(Math.random() * this.length)];
};
export function postGenerator(): Post[] {
var posts: Post[] = [];
for (var i: number = 0; i < 15; i++) {
let imageUrl = imageLocations
.randomElement()
.replace("{width}", "" + Math.floor(300 + Math.random() * 200))
.replace("{height}", "" + Math.floor(200 + Math.random() * 200));
posts.push(
new Post(
imageUrl,
captions.randomElement(),
users.randomElement(),
Math.floor(Math.random() * 150)
)
);
}
return posts;
}
| 4c5c9806b4a8a8d27d8cedca9c6a91c14f2243c0 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | jb-wagner/alex-gram | d094e132268eb6cece2242ab098e1ff7803738e5 | 14e21c7d479b6e7b9f994c4601eb733d2380dbbb | |
refs/heads/master | <repo_name>ZWhit196/experimental_server<file_sep>/helpers/Forms.py
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, validators
import database
class Register_Form(FlaskForm):
username = StringField('Username',[validators.Length(min=3, max=30)])
password = PasswordField('New Password', [
validators.DataRequired(),
validators.EqualTo('confirm', message='Passwords must match')
])
confirm = PasswordField('<PASSWORD>')
def validate(self):
# run the normal validators
rv = FlaskForm.validate(self)
if not rv:
return False
# password validation checks
if len(self.password.data) < 5: # Too short
self.password.errors.append("The password must be 5 or more characters long, contain 1 number and 1 letter.")
return False
if self.password.data.isalpha(): # Only alpha char
self.password.errors.append("The password must be 5 or more characters long, contain 1 number and 1 letter.")
return False
if self.password.data.isdigit(): # Only numerical
self.password.errors.append("The password must be 5 or more characters long, contain 1 number and 1 letter.")
return False
if database.Username_used(self.username.data): # check if username taken
self.email.errors.append('Email has already been registered.')
return False
return True
class Login_Form(FlaskForm):
username = StringField('Username',[validators.Length(min=3, max=30)])
password = PasswordField('<PASSWORD>', [
validators.DataRequired(),
])
def validate(self):
# run the normal validators
rv = FlaskForm.validate(self)
if not rv:
return False
# password validation checks
if len(self.password.data) < 5: # Too short
self.password.errors.append("The password must be 5 or more characters long, contain 1 number and 1 letter.")
return False
if self.password.data.isalpha(): # Only alpha char
self.password.errors.append("The password must be 5 or more characters long, contain 1 number and 1 letter.")
return False
if self.password.data.isdigit(): # Only numerical
self.password.errors.append("The password must be 5 or more characters long, contain 1 number and 1 letter.")
return False
return True<file_sep>/views/tests.py
import os
from flask import Blueprint, request, Response, flash, jsonify, redirect
from flask_login import login_required
from flask.templating import render_template
from flask.helpers import url_for
from file_management.folder import FolderManager
from helpers import Error, Load_data
test_router = Blueprint('test', __name__, template_folder='templates')
SERVABLES = "static/servables/"
@test_router.route("/tests", methods=["GET"])
def home():
filename = "example"
url = SERVABLES+"vid/"+filename+'.mp4'
return render_template("testing.html", url=url)
@test_router.route("/tests/folder")
@login_required
def make_base():
FM = FolderManager()
print(FM)
print(FM.Get_urls())
# print(FM.Create_personal_base())
return "<p>Folder manager test</p>"
# @test_router.route("/tests/vid/<filename>")
def get_vid(filename):
pass
# url = SERVABLES+"vid/"+filename
# print(url)
#
# def generate_stream(url):
# with open(url) as vid:
# # print(vid, dir(vid))
# for l in vid.readlines():
# yield l
#
# return Response( generate_stream(url) )<file_sep>/configs.py
import os
def GenerateKey():
return os.urandom(64)
DB_NAME = 'home_server'
DEV = {
'CUSTOM_TEST_URL': True,
'DEBUG': True,
# 'JS_TEST': True,
'SECRET_KEY': 'key',
'SQLALCHEMY_TRACK_MODIFICATIONS': False,
'SQLALCHEMY_DATABASE_URI': 'sqlite:///'+DB_NAME+'.db',
'WTF_CSRF_SECRET_KEY': 'key'
}
DEPLOY = {
'CUSTOM_TEST_URL': False,
'DEBUG': False,
# 'JS_TEST': False,
'SECRET_KEY': GenerateKey(),
'SQLALCHEMY_TRACK_MODIFICATIONS': False,
'SQLALCHEMY_DATABASE_URI': 'sqlite:///'+DB_NAME+'.db',
'WTF_CSRF_SECRET_KEY': GenerateKey()
}
def get_conf( c="DEPLOY" ):
if c == "DEPLOY":
return DEPLOY
elif c == "DEV":
return DEV
else:
return DEPLOY<file_sep>/views/front.py
from flask import Blueprint, request, Response, flash, jsonify
from flask.templating import render_template
from flask.helpers import url_for
front_router = Blueprint('front', __name__, template_folder='templates')
@front_router.route("/", methods=["GET"])
def home():
return render_template("front/home.html")<file_sep>/templates/front/home.html
{% extends "base.html" %}
{% block includes %}
{% endblock %}
{% set title = 'Home' %}
{% block header %}
{% include 'header.html'%}
{% endblock %}
{% block content %}
<div id="content" class="home">
<div class="container">
<div class="content">
<h3>Home Placeholder</h3>
{% if current_user.is_authenticated %}
<p>You are logged in.</p>
<ul>
<li><a href="/tests">testing page</a></li>
<li><a href="/tests/folder">test folder</a></li>
</ul>
{% else %}
<p>You are NOT logged in. <a href="/login">Login here.</a></p>
{% endif %}
</div>
</div>
</div>
{% endblock %}
<file_sep>/readme.txt
:EXPERIMENTAL SERVER STUFF:
So this is basically a server I'm using to experiment with stuff.
Probably not super useful for anything, but y'know, practise for better stuff, right?
:HANDY URLS I WANT TO HOLD ONTO FOR NOW:
https://blog.miguelgrinberg.com/post/flask-video-streaming-revisited
https://www.reddit.com/r/Python/comments/4go8n4/how_can_i_set_up_a_youtubestyle_video_server/?st=jdps4r6k&sh=69602a34
https://github.com/go2starr/py-flask-video-stream/blob/master/server.py<file_sep>/database/__init__.py
from database import DB, Querys
# DB.py
db = DB.db
# Querys.py
def Get_user(u):
return Querys._Find_user(u)
def New_user(u, pw):
return Querys._Create_user(u, pw)
def Username_used(u):
return Querys._Check_username_used(u)
def Reset_password(u, pw):
return Querys._Reset_user_password(pw, u)<file_sep>/home_server.py
import os
import traceback
from flask import Flask, request, jsonify
from flask.templating import render_template
from flask_login import LoginManager
from configs import get_conf, DB_NAME
from database import db
from models import User
from views import Routes
ERRORS = {400: "There was an issue with the request.", 403: "Access is denied.", 404: "This page/resource was not found.", 500: "An internal server error occured."}
def createNewKey():
return os.urandom(64)
def setup_database(app):
with app.app_context():
db.create_all()
def create_app():
app = Flask(__name__)
conf = get_conf("DEV")
for key in conf:
app.config[key] = conf[key]
db.init_app(app)
# login manager
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'accounts.login'
# keeps the user in the session
@login_manager.user_loader
def load_user(uid):
return User.query.get(int(uid))
@app.errorhandler(400)
@app.errorhandler(403)
@app.errorhandler(404)
@app.errorhandler(500)
def error_loading(ex):
cd = 500
if ex.code:
cd = ex.code
msg = ERRORS[cd]
if cd == 500:
traceback.print_exc()
if request.method == "POST":
return Error(msg, status=ex.code)
return render_template('error.html', err=cd, msg=msg)
rs = Routes(True)
for route in rs:
app.register_blueprint( route )
return app
def run_app():
app = create_app()
if not os.path.isfile(DB_NAME+'.db'):
setup_database(app)
app.run(host="0.0.0.0", port=5001)
if __name__ == "__main__":
run_app()<file_sep>/views/accounts.py
import traceback
from flask import Blueprint, request, Response, flash, jsonify, abort, redirect
from flask_login import login_user, logout_user, current_user, login_required
from flask.templating import render_template
from flask.helpers import url_for
from database import Username_used, New_user, Get_user
import helpers
# import
accounts_router = Blueprint('accounts', __name__, template_folder='templates')
@accounts_router.route("/login", methods=["GET","POST"])
def login():
form = helpers.Login_form()
if request.method == 'GET':
return render_template('accounts/login.html', form=form)
if form.validate_on_submit(): # Basically the `POST` request
username = form.username.data.lower()
password = form.password.data
registered_user = Get_user(username)
if registered_user is not None:
login_user(registered_user, remember=True)
flash("You are logged in.")
return redirect(url_for("front.home"))
flash("Username or password is invalid.")
return redirect(url_for("accounts.login"))
@accounts_router.route("/logout", methods=["GET","POST"])
def logout():
logout_user()
flash("You have been logged out.")
return redirect(url_for('front.home'))
@accounts_router.route("/create", methods=["GET","POST"])
def create():
try:
form = helpers.Reg_form()
if form.validate_on_submit(): # Basically the `POST` request
taken = Username_used(form.username.data.lower())
if not taken:
user = New_user( form.username.data.lower(), form.password.data )
login_user(user, remember=True)
# Setup folder and update reg.json
# FM.Create_personal_base() # Create your personal folder
flash("User has been created. Welcome!")
return redirect(url_for("front.home"))
flash("That username has already been taken.")
return redirect(url_for("accounts.create"))
if form.username.errors or form.password.errors:
for err in form.username.errors:
flash(err)
for err in form.password.errors:
flash(err)
return redirect(url_for("accounts.create"))
return render_template("accounts/create.html", form=form)
except Exception as e:
traceback.print_exc()
print("Error in create:",e)
if request.method == "POST":
return helpers.Error(error="SERVER", status=500)
abort(500)<file_sep>/views/__init__.py
'''
Register the views here.
'''
from views.front import front_router
from views.accounts import accounts_router
from views.tests import test_router
routes = [
front_router,
accounts_router
]
def Routes(dev=False):
l = list(routes)
if dev:
l.extend( [test_router] )
return l<file_sep>/helpers/Request_handling.py
import json
def _Request_data(rd):
rd = rd.decode("utf-8")
return json.loads(rd)<file_sep>/helpers/__init__.py
from helpers import Forms, Error_helper, Request_handling
# WTForms
def Reg_form():
return Forms.Register_Form()
def Login_form():
return Forms.Login_Form()
# Request data
def Load_data(r):
return Request_handling._Request_data(r)
# Error_helper
def Error(content="Error occured", error='REQUEST', status=400):
return Error_helper._Get_error(content, error, status)<file_sep>/models.py
import datetime
from passlib.hash import pbkdf2_sha512
from database.DB import db
class User(db.Model):
uid = db.Column('uid', db.Integer, primary_key=True, nullable=False)
username = db.Column(db.String(256), unique=True, nullable=False)
password = db.Column(db.Text, nullable=False)
account_created = db.Column(db.DateTime())
last_login = db.Column(db.DateTime())
def __init__(self, username, password):
self.username = username.lower()
self.set_password(password)
self.account_created = datetime.datetime.now()
self.last_login = datetime.datetime.now()
def __repr__(self):
return '<User: {}>'.format(self.username)
# functions for login manager
def is_authenticated(self):
return True
def is_active(self):
return True
def is_anonymous(self):
return False
def get_id(self):
return str(self.uid)
# End login manager func.
def commit_self(self):
db.session.add(self)
db.session.commit()
def set_password(self, password):
''' hashes and salts a new password '''
self.password = <PASSWORD>.encrypt(password, rounds=200000, salt_size=16)
def verify_password(self, password):
''' verifies a password '''
return pbkdf2_sha512.verify(password, self.password)
def update_password(self, password):
''' sets and saves a password '''
self.set_password(password)
self.commit_self()
def update_login(self):
''' updates time since last login '''
self.last_login = datetime.datetime.now()
self.commit_self()<file_sep>/file_management/files.py
'''
This is intended for managing the files of a user.
Adding, removing, moving, and retrieving names handled here.
'''
from flask_login import current_user<file_sep>/file_management/folder.py
'''
Folder management, i.e. creating/removing folders and updating reg.json,
is performed here.
'''
import os
from flask_login import current_user
class FolderManager(object):
'''
Class for object management.
'''
base_url = "./static/servables/"
shared_video = "./static/servables/vid/"
shared_music = "./static/servables/music/"
music_url = ""
video_url = ""
def __init__(self):
self.base_url += current_user.username + "/"
self.music_url = self.base_url + "music/"
self.video_url = self.base_url + "video/"
def __repr__(self):
return "<Folder: {}>".format(self.base_url)
def Get_urls(self):
URLS = {
"BASE": self.base_url,
"SHARED MUSIC": self.shared_music,
"SHARED VIDEO": self.shared_video
}
return URLS
# Create
def Create_personal_base(self):
'''
Creates the base personal folder for a user.
'''
try:
os.makedirs(self.base_url, exist_ok=True)
return True
except Exception as e:
print("Create error:",e)
raise NotImplementedError
def Add_personal_subfolder(self, name):
raise NotImplementedError
# Retrieve
def Retrieve_folder_list(self):
raise NotImplementedError
# Remove
def Remove_folder(self):
raise NotImplementedError<file_sep>/static/js/utils.js
var ajaxobj = null, callback = null, errorback = null, showncol = null;
function SetAjaxArgs(o, c, e) { ajaxobj = o; callback = c; errorback = e; }
function NullAjaxArgs() { ajaxobj = null; callback = null; errorback = null; }
function AjaxCall() {
$.ajax({
url: window.location,
method: 'POST',
data: JSON.stringify( ajaxobj ),
contentType: 'application/json'
}).done(function(dt) {
callback(dt);
NullAjaxArgs();
}).fail(function(e) {
console.log("Failed processing", e.status, e.responseJSON.Message);
alert("Data Request Error: "+String(e.status)+"\n"+e.responseJSON.Message);
errorback();
NullAjaxArgs();
});
}
function isInArray(target, array) {
if( array.indexOf(target)>-1 ) return true;
return false;
}
function ToggleLoader(id, l_id) {
if (!l_id) l_id = ".loader";
if (typeof id == "object" && id.length > 0) for (var i=0; i<id.length; i++) $( id[i] ).find(l_id).toggle();
else if (typeof id == "string") $(id).find(l_id).toggle();
}
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
function togglePassField(el) {
// Toggle readability of password field given, switch between hidden text and readable text.
if ( $( el ).prop("type") == "password" ) {
$( el ).prop("type", "text");
$( el ).prop("placeholder", "password");
} else {
$( el ).prop("type", "password");
$( el ).prop("placeholder", "********");
}
}<file_sep>/file_management/youtuber.py
'''
Experimenting with pytube will be done here,
otherwise this will be a manual download system
of vid.
'''<file_sep>/database/Querys.py
from database.DB import db
from models import User
def _Create_user(username, password):
''' Create a user and commit it to the database. '''
u = User(username, password)
db.session.add(u)
db.session.commit()
return u
def _Find_user(username):
''' Find a user by email. '''
return User.query.filter_by(username=username).first()
def _Check_username_used(username):
''' Checks whether an email is used. '''
if User.query.filter_by(username=username).first():
return True
return False
def _Reset_user_password(password, username):
''' Reset password. '''
u = User.query.filter_by(username=username).first()
if u:
u.update_password(password)
return True
return False | 7075bd3b4c8878ac37e528fa1ff28c7ada552d99 | [
"JavaScript",
"Python",
"Text",
"HTML"
] | 18 | Python | ZWhit196/experimental_server | c1be62abad71d9468dd91ee4e089a2f05405087a | 950805721320a3a2b558c3107f79d4480c4a709d | |
refs/heads/main | <file_sep>setInterval(() => {
let dd = new Date();
let hh = dd.getHours();
let mm = dd.getMinutes();
let ss = dd.getSeconds();
let month = dd.getMonth() + 1;
let day = dd.getDate();
let year = dd.getFullYear();
if (month < 10) month = '0' + month;
if (day < 10) day = '0' + day;
if (hh < 10) hh = '0' + hh;
if (mm < 10) mm = '0' + mm;
if (ss < 10) ss = '0' + ss;
document.querySelector('.date').innerHTML = `${day} : ${month} : ${year}`;
document.querySelector('.time').innerHTML = `${hh} : ${mm} : ${ss}`;
}, 500)
let time = 0;
let setMinutes = 0;
function setSeconds() {
time++;
let mins = Math.floor(time / 10 / 60);
let secs = Math.floor(time / 10 % 60);
let hours = Math.floor(time / 10 / 60 / 60);
let tenths = time % 10;
if (mins < 10) {
mins = "0" + mins;
}
if (secs < 10) {
secs = "0" + secs;
}
document.querySelector(".seconds-description").innerHTML = hours + ":" + mins + ":" + secs + ":" + tenths + "0";
}
function startInterval() {
intervalID = setInterval(setSeconds, 100);
}
function stopInterval() {
clearInterval(intervalID);
}
function createTimeList() {
let p = document.createElement('p');
let seconds = document.querySelector('.seconds-description').textContent;
p.textContent = seconds;
document.querySelector('.result-loop').appendChild(p);
}
function resetTimeList() {
time = 0;
clearInterval(intervalID);
document.querySelector('.seconds-description').textContent = "0:00:00:00";
document.querySelector('.result-loop').innerHTML = "";
}
function increaseMinute() {
total = document.querySelector('.minutes').textContent;
if (total < 59) {
setMinutes++;
if (total < 9) {
setMinutes = "0" + setMinutes;
}
}
document.querySelector('.minutes').textContent = setMinutes;
}
function decreaseMinutes() {
total = document.querySelector('.minutes').textContent;
if (total != "00" && total < 59 && total > 0) {
setMinutes--;
if (total < 9) {
setMinutes = "0" + setMinutes;
}
document.querySelector('.minutes').textContent = setMinutes;
}
}
let myTimer;
function clock() {
if(setMinutes > 0){
myTimer = setInterval(myClock, 1000);
let c = document.querySelector('.minutes').textContent * 60;
function myClock() {
--c
let seconds = c % 60;
let secondsInMinutes = (c - seconds) / 60;
let minutes = secondsInMinutes % 60;
document.querySelector(".counter-minutes").textContent = (minutes < 10 ? "0" : "") + String(minutes) + ":";
document.querySelector(".counter-seconds").textContent = (seconds < 10 ? "0" : "") + String(seconds);
if (c == 0) {
clearInterval(myTimer);
}
}
}
}
function clockPause() {
clearInterval(myTimer);
}
function clockReset(){
document.querySelector(".counter-minutes").textContent = "00 :";
document.querySelector(".counter-seconds").textContent = "00";
document.querySelector('.minutes').textContent = "00";
clearInterval(myTimer);
setMinutes = 0;
}
| 9a5b7db69317dcbb14be3274d041f9a2ee0c3002 | [
"JavaScript"
] | 1 | JavaScript | Buherchuk/date-and-clocks | ba690ec6055dfc21a3985e32360113e37c724cd5 | 0a5f4b1a42738382b578f6876fdfba8e204941d4 | |
refs/heads/master | <repo_name>gmontamat/histopathologic-cancer-detection<file_sep>/README.md
# histopathologic-cancer-detection
Code for the Kaggle competition "Histopathologic Cancer Detection"
<file_sep>/full_process.py
#!/usr/bin/env python
"""
Full process
"""
import keras.backend as K
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import pickle
import tensorflow as tf
from keras.applications.resnet50 import ResNet50, preprocess_input
from keras.callbacks import Callback, EarlyStopping, ReduceLROnPlateau
from keras.layers import Dense, Dropout, Flatten, GlobalAveragePooling2D, BatchNormalization
from keras.models import Model, load_model
from keras.optimizers import Adam, SGD
from keras.preprocessing.image import load_img, img_to_array, ImageDataGenerator
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import StratifiedKFold, GroupKFold
# Configure Keras and TensorFlow so that they use the GPU
tf_config = tf.ConfigProto(allow_soft_placement=True)
tf_config.gpu_options.allow_growth = True
sess = tf.Session(config=tf_config)
K.set_session(sess)
data_path = os.path.join(os.getcwd(), 'input')
train_path = os.path.join(data_path, 'train')
labels_path = os.path.join(data_path, 'train_labels.csv')
df = pd.read_csv(labels_path)
def crop_roi(img, roi_size=48):
"""Crop a square region in the center of the image."""
size = img.shape[0]
roi_ul = (int(size / 2 - roi_size / 2), int(size / 2 - roi_size / 2))
roi_lr = (int(size / 2 + roi_size / 2), int(size / 2 + roi_size / 2))
return img[roi_ul[1]: roi_lr[1], roi_ul[0]: roi_lr[0]]
def load_image(img_id, img_size=96, roi_size=None):
"""Load image using its id. Resize and crop is optional."""
img_path = os.path.join(train_path, '{}.tif'.format(img_id))
img = load_img(img_path, target_size=(img_size, img_size))
img = img_to_array(img)
if roi_size:
return crop_roi(img, roi_size)
return img
wsi_path = os.path.join(data_path, 'patch_id_wsi.csv')
df = df.merge(pd.read_csv(wsi_path), left_on='id', right_on='id', how='left')
df.wsi = df.wsi.str.split("_", expand=True)[3]
df.wsi.fillna(np.random.choice(df[pd.notnull(df.wsi)].wsi.values), inplace=True)
img_size = 96
roi_size = None # Do not crop center square
if roi_size is None:
size = img_size
else:
size = roi_size
images = []
labels = []
wsis = []
for idx, row in df.iterrows():
img_id, label, wsi = row
img = load_image(img_id, img_size=img_size, roi_size=roi_size)
img = img.reshape(1, size, size, 3)
images.append(img)
labels.append(label)
wsis.append(wsi)
images = np.concatenate(images, axis=0)
labels = np.array(labels).reshape(images.shape[0], 1)
wsis = np.array(wsis).reshape(images.shape[0], 1)
print("images: {}".format(images.shape))
print("labels: {}".format(labels.shape))
class RocCallback(Callback):
"""Define a callback which returns train ROC AUC after each epoch."""
def __init__(self, training_data, validation_data=None):
self.x = training_data[0]
self.y = training_data[1]
self.validation = validation_data is not None
if self.validation:
self.x_val = validation_data[0]
self.y_val = validation_data[1]
def on_train_begin(self, logs={}):
return
def on_train_end(self, logs={}):
y_pred = self.model.predict(self.x)
roc = roc_auc_score(self.y, y_pred)
if self.validation:
y_pred_val = self.model.predict(self.x_val)
roc_val = roc_auc_score(self.y_val, y_pred_val)
print('\rroc-auc: {} - roc-auc-val: {}'.format(round(roc, 5), round(roc_val, 5)), end=80 * ' ' + '\n')
else:
print('\rroc-auc: {}'.format(round(roc, 5)), end=80 * ' ' + '\n')
return
def on_epoch_begin(self, epoch, logs={}):
return
def on_epoch_end(self, epoch, logs={}):
return
def on_batch_begin(self, batch, logs={}):
return
def on_batch_end(self, batch, logs={}):
return
def focal_loss(gamma=2., alpha=.25):
def focal_loss_fixed(y_true, y_pred):
pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))
pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))
return (
-K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1 + K.epsilon()))
-K.sum((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0 + K.epsilon()))
)
return focal_loss_fixed
def build_model():
resnet = ResNet50(include_top=False, weights='imagenet', input_shape=(size, size, 3), pooling='avg')
x = resnet.output
# x = Flatten()(x)
# x = GlobalAveragePooling2D()(x)
x = BatchNormalization()(x)
x = Dropout(0.8)(x)
x = Dense(1024, activation='relu')(x)
x = BatchNormalization()(x)
x = Dropout(0.8)(x)
x = Dense(512, activation='relu')(x)
x = Dropout(0.8)(x)
x = Dense(1, activation='sigmoid')(x)
return Model(inputs=[resnet.input], outputs=[x])
model = build_model()
model.summary()
kfold = 20
gkf = GroupKFold(n_splits=kfold)
k = 0
for train_idx, test_idx in gkf.split(images, labels.squeeze(), groups=wsis.squeeze()):
k += 1
# Get train and test set for this fold
train_images = images[train_idx, :, :, :]
train_labels = labels[train_idx, :]
test_images = images[test_idx, :, :, :]
test_labels = labels[test_idx, :]
# Define train (augmentation) and test generators
train_generator = ImageDataGenerator(
# shear_range=0.1,
# zoom_range=0.1,
horizontal_flip=True,
vertical_flip=True,
rotation_range=10.,
fill_mode='reflect',
# width_shift_range=0.1,
# height_shift_range=0.1,
preprocessing_function=preprocess_input
)
train_generator.fit(train_images)
test_images = preprocess_input(test_images)
# Compile model and train
model = build_model()
model.compile(
# loss='binary_crossentropy',
loss=focal_loss(alpha=.25, gamma=2),
# optimizer=SGD(lr=1e-2, momentum=0.9, nesterov=True),
optimizer=Adam(lr=1e-4),
metrics=['accuracy']
)
callbacks = [
RocCallback(training_data=(train_images, train_labels), validation_data=(test_images, test_labels)),
ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=5, mode='auto'),
EarlyStopping(monitor='val_loss', min_delta=1e-4, patience=10, mode='auto')
]
model.fit_generator(
train_generator.flow(train_images, train_labels, batch_size=256),
steps_per_epoch=len(train_images) / 256,
epochs=500,
validation_data=(test_images, test_labels),
callbacks=callbacks
)
model.save('resnet50_kfold{}.h5'.format(k))
del images
del labels
images = []
labels = []
test_path = os.path.join(data_path, 'test')
submission_path = os.path.join(data_path, 'sample_submission.csv')
submission = pd.read_csv(submission_path).drop('label', axis=1)
def load_image(img_id, img_size=96, roi_size=None):
"""Load image using its id. Resize and crop is optional."""
img_path = os.path.join(test_path, '{}.tif'.format(img_id))
img = load_img(img_path, target_size=(img_size, img_size))
img = img_to_array(img)
if roi_size:
return crop_roi(img, roi_size)
return img
test_images = []
for idx, row in submission.iterrows():
img_id = row[0]
img = load_image(img_id, img_size=img_size, roi_size=roi_size)
img = img.reshape(1, size, size, 3)
test_images.append(img)
test_images = np.concatenate(test_images, axis=0)
tta_steps = 4
fold_predictions = []
for k in range(kfold):
model = load_model('resnet50_kfold{}.h5'.format(k + 1), compile=False)
predictions = []
for i in range(tta_steps):
y_pred = model.predict_generator(
train_generator.flow(test_images, batch_size=256, shuffle=False),
steps=len(test_images) / 256
)
predictions.append(y_pred)
fold_predictions.append(np.mean(predictions, axis=0))
predictions = np.mean(fold_predictions, axis=0).squeeze().tolist()
submission['label'] = predictions
submission.to_csv('submission.csv', index=False)
| 65ede4e9d21b7a93a03271d2316911f9693abe96 | [
"Markdown",
"Python"
] | 2 | Markdown | gmontamat/histopathologic-cancer-detection | 70617cb4158f2a8045ee0e6a95ff26772f002580 | 2b509a83ba6a63f94050d2aeccdf38320e19baea | |
refs/heads/master | <file_sep># FixMe-Mobile
Mobile app for FixMe Application
<file_sep>import { createStackNavigator, createAppContainer } from 'react-navigation';
import LoginScreen from '../screens/Login/LoginScreen.js';
const MainStack = createStackNavigator(
{
Home: {
screen: LoginScreen
},
},
{
initialRouteName: 'Home',
}
);
const MainApp = createAppContainer(MainStack);
export default MainApp;<file_sep>import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font, Icon } from 'expo';
import AppNavigator from './navigation/AppNavigator';
import { hasServicesEnabledAsync } from 'expo-location';
import MainApp from './utils/MainStack.js';
export default class App extends React.Component {
state = {
isLoadingComplete: false,
};
onNavigationStateChange = (previous, current) => {
const screen = {
current: this.getCurrentRouteName(current),
previous: this.getCurrentRouteName(previous),
};
if (screen.previous !== screen.current) {
track(screen.current);
}
};
getCurrentRouteName = (navigation) => {
const route = navigation.routes[navigation.index];
return route.routes ? this.getCurrentRouteName(route) : route.routeName;
};
renderLoading = () => (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
renderApp = () => (
<View style={{ flex: 1 }}>
<MainApp />
</View>
);
render() {
return (
<View style={{ flex: 1 }}>
<MainApp />
</View>
);
};
_loadResourcesAsync = async () => {
return Promise.all([
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
Font.loadAsync({
// This is the font that we are using for our tab bar
...Icon.Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free
// to remove this if you are not using it in your app
//'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf'),
}),
]);
};
_handleLoadingError = error => {
// In this case, you might want to report the error to your error
// reporting service, for example Sentry
console.warn(error);
};
_handleFinishLoading = () => {
this.setState({ isLoadingComplete: true });
};
}
| d8d29f38ed22e427cc018dfaf41e2c914c687b3e | [
"Markdown",
"JavaScript"
] | 3 | Markdown | Ambada-Soft/FixMe-Mobile | 65a2952c639f2d1c3caa64031436408162a6aad6 | bc9b5da10e82f927282e6309d91d94f4d0064128 | |
refs/heads/master | <file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
</head>
<body>
<?php
//Create the client object
$soapclient = new SoapClient('http://clima.inifap.gob.mx/data/webservice.asmx?WSDL');
//Use the functions of the client, the params of the function are in
//the associative array
// variables que usamos de entrada para solicitar informacion
$edo=10;
$numero=33;
$estacion=33;
//juntamos todos los paramentros en esa variable para posteriormente mandarlos a llamar
$params = array('numero' => $numero,'estacion' => $estacion, 'edo' => $edo);
// $params = array('edo' => '10'); // id del estado del cual queremos obtener las estaciones
//establecemos las conexiones y mandamos los parametros
$responseGetEstaciones = $soapclient->GetEstaciones($params);
$responseGetEstacionesString = $responseGetEstaciones->GetEstacionesResult; // convertir de objeto a string
// Parse information
$xml = $responseGetEstaciones->GetEstacionesResult;
$doc = new DOMDocument();
$doc->loadXML($xml);
// VARIABLES que nos va arrojar
$arrayEstacionesNombre = [];
$arrayEstacionesNumero = [];
for ($i=0; $i < 22; $i++) {
$arrayEstacionesNumero[] = $doc->getElementsByTagName('numero')->item($i)->nodeValue;
$arrayEstacionesNombre[] = $doc->getElementsByTagName('nombre')->item($i)->nodeValue;
}
//imprime todas las estaciones
/*for ($j=0; $j < 22; $j++) {
echo "Estación número: " . $arrayEstacionesNumero[$j] . " Nombre: " , $arrayEstacionesNombre[$j] . "<br>";
}
*/
//var_dump($responseGetEstaciones);
?>
<form id="form1" name="form1"method="post" action="soapFunction_3-copia2.php">
selecciones estacion-------->
<select name="select_estaciones" >
<?php
for ($j=0; $j < 22; $j++) { ?>
<option value= <?php echo $arrayEstacionesNumero[$j]?> > <?php echo $arrayEstacionesNombre[$j]."</br>";
}
?> </option>
</select>
<input type="submit" value= "enviar datos">
<?php
//$nombre= $_POST ["select_estaciones"];
?>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Fusion tables</title>
<style type="text/css">
#map_canvas {
width: 650px;
height: 450px;
margin-bottom: 10px;
top:0%;
left:0%;
}
</style>
<!--
Customize the content security policy in the meta tag below as needed. Add 'unsafe-inline' to default-src to enable inline JavaScript.
For details, see http://go.microsoft.com/fwlink/?LinkID=617521
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
-->
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>app</title>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
//definir capa fusion Tables
var capa1 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1QmqsXAFzy6Ngivk8YXM0ZG2OEPttTiWKPs_Lv5pH'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa2 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1O2Xjgu4DaLVANS7zPMwO_fIajhvVPkuEFtZ0LUcx'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa3 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1-evLAUWaXGtGY3QasNLavAsP9VIeZTMaBqw4aw-r'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa4 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1vGQYZWyRr_EUvIXLd_mnmOLzhiayBIwAv7Z1N1lT'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa5 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1bulqje2AuwBdIOrVHcfNjm4nWzWafCV_ZqUlbDjP'
},
options:{
styleId: 2,
templateId: 2
}
});
function initialize(){
//Latitud y Longitud del centro del mapa Google Maps
var posicion = new google.maps.LatLng(19.292222222222, -99.653888888889);
//Opciones de Mapa
var opcionesmap = {
zoom: 8,
center: posicion,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), opcionesmap);
//Se establece si las capas se dibujan en el mapa
capa1.setMap(map);
capa2.setMap(map); //Si se coloca null el mapa no se dibuja de inicio
capa3.setMap(map); //Si se coloca null el mapa no se dibuja de inicio
capa4.setMap(map); //Si se coloca null el mapa no se dibuja de inicio
capa5.setMap(map); //Si se coloca null el mapa no se dibuja de inicio
}
function enciendecapas(seleccionTablaID){
if (seleccionTablaID == "1QmqsXAFzy6Ngivk8YXM0ZG2OEPttTiWKPs_Lv5pH"){
if (document.getElementById("capa1").checked == true) {
if(capa1.getMap() == null) { capa1.setMap(map); }
}
if (document.getElementById("capa1").checked == false) {
capa1.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1O2Xjgu4DaLVANS7zPMwO_fIajhvVPkuEFtZ0LUcx"){
if (document.getElementById("capa2").checked == true) {
if(capa2.getMap() == null) { capa2.setMap(map); }
}
if (document.getElementById("capa2").checked == false) {
capa2.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1-evLAUWaXGtGY3QasNLavAsP9VIeZTMaBqw4aw-r"){
if (document.getElementById("capa3").checked == true) {
if(capa3.getMap() == null) { capa3.setMap(map); }
}
if (document.getElementById("capa3").checked == false) {
capa3.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1vGQYZWyRr_EUvIXLd_mnmOLzhiayBIwAv7Z1N1lT"){
if (document.getElementById("capa4").checked == true) {
if(capa4.getMap() == null) { capa4.setMap(map); }
}
if (document.getElementById("capa4").checked == false) {
capa4.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1bulqje2AuwBdIOrVHcfNjm4nWzWafCV_ZqUlbDjP"){
if (document.getElementById("capa5").checked == true) {
if(capa5.getMap() == null) { capa5.setMap(map); }
}
if (document.getElementById("capa5").checked == false) {
capa5.setMap(null); /*Apaga Capa*/
}
}//FIN IF
}
</script>
</head>
<!-- logo inifap -->
<div class="logo">
<a href="#" class="image fit"><img src="images/inifap.png" alt="" /></a>
</div>
<?php include("include/header.html");?>
<body onLoad="initialize()">
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
<div class="inner">
<header>
<h1><a href="index.html" id="logo">Estaciones Agroclimáticas</a></h1>
<br>
</header>
</div>
<!-- lista de links para el DEZPLAZAMIENTO -->
<nav id="nav">
<ul>
<li><a href="#MAPA" id="MAPA-link" class="skel-layers-ignoreHref"><span class="icon fa-home">MAPA</span></a></li>
<li><a href="#15minutos" id="15minutos-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Datos cada 15 minutos</span></a></li>
<li><a href="#estadisticos" id="estadisticos-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Datos estadisticos</span></a></li>
<li><a href="#humedadrelativa" id="humedadrelativa-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Temperatura y humedadrelativa</span></a></li>
<li><a href="#Pronostico" id="Pronostico-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Pronostico</span></a></li>
</ul>
</nav>
<!-- MAPA -->
<section id="MAPA" class="one dark cover">
<div class="container">
<header>
<h1>Estaciones </h1>
</header>
<!-- <footer>
<a href="#portfolio" class="button scrolly">Magna Aliquam</a>
</footer> -->
</div>
</section>
<table>
<tr>
<td>
<div id="map_canvas" ></div>
</td>
</tr>
</table>
<table>
<tr>
<td>
<form>
<!--Controles para apagar y encender capas-->
<input type="checkbox" value="1QmqsXAFzy6Ngiv<KEY>"id="capa1" onClick="enciendecapas(this.value);" checked="checked">Municipios<br>
<input type="checkbox" value="1<KEY>LV<KEY>"id="capa2" onClick="enciendecapas(this.value);" checked="checked">Uso de suelo<br>
<input type="checkbox" value="1-evLAUWaXGtGY3QasNLavAsP9VIeZTMaBqw4aw-r"id="capa3" onClick="enciendecapas(this.value);" checked="checked">Edafologia<br>
<input type="checkbox" value="1vGQYZWyRr_EUvIXLd_mnmOLzhiayBIwAv7Z1N1lT"id="capa4" onClick="enciendecapas(this.value);" checked="checked">Hidrologia<br>
<input type="checkbox" value="1bulqje2AuwBdIOrVHcfNjm4nWzWafCV_ZqUlbDjP"id="capa5" onClick="enciendecapas(this.value);" checked="checked">Frontera agricola
</form>
</td>
<td>
<form>
<input type="button" value="Boton" />
<button type="button">Cargar estaciones</button>
</form>
<form action="/action_page.php">
estacion: <select name="cars">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</form>
</td>
</tr>
</table>
<!-- Datos cada 15 minutos -->
<section id="15minutos" class="two">
<div class="container">
<header>
<h1>Datos cada 15 minutos</h1>
<table border="1">
<tr>
<th>Velocidad del viento</th>
<th>---datos---</th>
</tr>
<tr>
<th scope="col">Direccion del viento;</th>
<th scope="col"> </th>
</tr>
</table
</header>
<p></p>
</div>
</section>
<!-- Datos estadisticos -->
<section id="estadisticos" class="three">
<div class="container">
<header>
<h1>Datos Estadisticos</h1>
</header>
</div>
</section>
<!-- Temperatura y humedad relativa -->
<section id="humedadrelativa" class="four">
<div class="container">
<header>
<h1>Temperatura y humedad relativa</h1>
</header>
</div>
</section> <!-- Pronostico -->
<section id="Pronostico" class="five">
<div class="container">
<header>
<h1>Pronostico</h1>
<table border= "1" , id= pronostico>
<tr>
<th scope="col">Dia 1</th>
<th scope="col">Datos;</th>
</tr>
<tr>
<th scope="col">Precipitacion</th>
<td> </td>
</tr>
<tr>
<th>Temperatura maxima</th>
<th>---datos---</th>
</tr>
<tr>
<th>Temperatura minima</th>
<th>---datos---</th>
</tr>
<tr>
<th>Temperatura media</th> <th>---datos---</th>
</tr>
</table
</header>
</div>
</section>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
</head>
<body>
<?php
//Create the client object
$soapclient = new SoapClient('http://clima.inifap.gob.mx/data/webservice.asmx?WSDL');
//Use the functions of the client, the params of the function are in
//the associative array
// variables que usamos de entrada para solicitar informacion
$edo=10;
$numero=33;
$estacion=33;
$nombre='Ocampo';
//juntamos todos los paramentros en esa variable para posteriormente mandarlos a llamar
$params = array('numero' => $numero,'estacion' => $estacion, 'edo' => $edo,'nombre' =>$nombre);
// $params = array('edo' => '10'); // id del estado del cual queremos obtener las estaciones
//establecemos las conexiones y mandamos los parametros
$responseGetEstaciones = $soapclient->GetEstaciones($params);
$responseGetEstacionesString = $responseGetEstaciones->GetEstacionesResult; // convertir de objeto a string
// Parse information
$xml = $responseGetEstaciones->GetEstacionesResult;
$doc = new DOMDocument();
$doc->loadXML($xml);
// VARIABLES que nos va arrojar
$arrayEstacionesNombre = [];
$arrayEstacionesNumero = [];
for ($i=0; $i < 22; $i++) {
$arrayEstacionesNumero[] = $doc->getElementsByTagName('numero')->item($i)->nodeValue;
$arrayEstacionesNombre[] = $doc->getElementsByTagName('nombre')->item($i)->nodeValue;
}
//imprime todas las estaciones
/*for ($j=0; $j < 22; $j++) {
echo "Estación número: " . $arrayEstacionesNumero[$j] . " Nombre: " , $arrayEstacionesNombre[$j] . "<br>";
}
*/
//var_dump($responseGetEstaciones);
?>
selecciones estacion-------->
<select name="select" id="select">
<option value="selecionar">selecciona la estacion</option>
<?php
for ($j=0; $j < 22; $j++) { ?>
<option value= <?php echo $arrayEstacionesNumero[$j]?> > <?php echo $arrayEstacionesNombre[$j] . "</br>";
}
?></option>
</select>
<?php
// VARIABLES que nos va obtener
$arrayGetEstacionesPorNumero = [];
$arrayGetEstacionesPorNumero = [];
$nombre='Ocampo';
//juntamos todos los paramentros en esa variable para posteriormente mandarlos a llamar
$paramsnombre = array('nombre' =>$nombre);
//conseguir el numero y nombre la estacion seleccionada
$responseGetEstacionesPorNombre = $soapclient->GetEstacionesPorNombre($paramsnombre);
$responseGetEstacionesPorNombreString = $responseGetEstacionesPorNombre->GetEstacionesPorNombreResult; // convertir de objeto a string
// Parse information
$xml_nombre = $responseGetEstacionesPorNombre->GetEstacionesPorNombreResult;
$doc_nombre = new DOMDocument();
$doc_nombre->loadXML($xml_nombre);
for ($i=0; $i < 1; $i++) {
$arrayGetEstacionesPorNumero[] = $doc->getElementsByTagName('numero')->item($i)->nodeValue;
$arrayGetEstacionesPorNombre[] = $doc->getElementsByTagName('nombre')->item($i)->nodeValue;
}
//imprime todas las estaciones
for ($j=0; $j < 1; $j++) {
echo "Estación : " . $arrayGetEstacionesPorNumero[$j] . " Nombre: " , $arrayGetEstacionesPorNombre[$j] . "<br>";
}
?>
|
<?php
//// estacuiones datos
$responseEstacionDatos = $soapclient->EstacionDatos($params);
$responseEstacionDatosString = $responseEstacionDatos->EstacionDatosResult;
// Parse information
$xml_datos = $responseEstacionDatos->EstacionDatosResult;
$doc_datos = new DOMDocument();
$doc_datos->loadXML($xml_datos);
$arrayEstacionDatosFecha = [];
$arrayEstacionDatosPrec = [];
$arrayEstacionDatosTemp = [];
$arrayEstacionDatosDir = [];
$arrayEstacionDatosVel = [];
$arrayEstacionDatosRad = [];
$arrayEstacionDatosHumr = [];
$arrayEstacionDatosHumh = [];
?>
---------------- Datos de la estacion ------------------
<table>
<tr>
<td>Fecha:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosFecha[] = $doc_datos->getElementsByTagName('fecha')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo " " . $arrayEstacionDatosFecha[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>precipitacion:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosPrec[] = $doc_datos->getElementsByTagName('prec')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosPrec[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>temperatura:</td>
<td>
<?php
//temperatura
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosTemp[] = $doc_datos->getElementsByTagName('temt')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosTemp[$j] . " <br>";
}
?>
</td>
</tr>
<tr>
<td>direccion del viento:</td>
<td>
<?php
//direccion del viento
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosDir[] = $doc_datos->getElementsByTagName('dirv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosDir[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Velocidad del viento: </td>
<td>
<?php
//VELOCIDAD DEL VIENTO
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosVel[] = $doc_datos->getElementsByTagName('velv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosVel[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Radiacion:</td>
<td>
<?php
//radiacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosRad[] = $doc_datos->getElementsByTagName('radg')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosRad[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Humedad r:</td>
<td>
<?php
//humedad r
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosHumr[] = $doc_datos->getElementsByTagName('humr')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosHumr[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Humedad H:</td>
<td>
<?php
//Humedad h
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosHumh[] = $doc_datos->getElementsByTagName('humh')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosHumh[$j] . "<br>";
}
?>
</td>
</tr>
</table>
------------------datos estadisticos----------------
<?php
$arrayGetEstadisticosFecha = [];
$arrayGetEstadisticosprecAcumulada = [];
$arrayGetEstadisticosTempMax = [];
$arrayGetEstadisticosTempMin = [];
$arrayGetEstadisticosTempMed = [];
$arrayGetEstadisticosHumR = [];
$arrayGetEstadisticosDirV = [];
$arrayGetEstadisticosVelV = [];
$arrayGetEstadisticosDirVText = [];
//// estacuiones datos
$responseGetEstadisticos = $soapclient->GetEstadisticos ($params);
$responseGetEstadisticosString = $responseGetEstadisticos ->GetEstadisticosResult;
// Parse information
$xml_estadisticos = $responseGetEstadisticos->GetEstadisticosResult;
$doc_estadisticos = new DOMDocument();
$doc_estadisticos->loadXML($xml_estadisticos);
?>
<table>
<tr>
<td>Fecha:</td>
<td>
<?php
//fecha
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosFecha[] = $doc_estadisticos->getElementsByTagName('fecha')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo "" . $arrayGetEstadisticosFecha[$j] . "<br>";
}
?>
</td>
</tr>
<td>precipitacion:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosPrec[] = $doc_estadisticos->getElementsByTagName('prec')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosPrec[$j] . "<br>";
}
?>
</td>
</tr>
<td>temperatura maxima:</td>
<td>
<?php
//: temperatura maxima
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMax[] = $doc_estadisticos->getElementsByTagName('tmax')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMax[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>Temperatura minina:</td>
<td>
<?php
//: temperatura mínima
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMin[] = $doc_estadisticos->getElementsByTagName('tmin')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMin[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>temperatura media:</td>
<td>
<?php
//temperatura media
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMed[] = $doc_estadisticos->getElementsByTagName('tmed')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMed[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>humedad relativa:</td>
<td>
<?php
//humedad relativa
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosHumR[] = $doc_estadisticos->getElementsByTagName('humr')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosHumR[$j] . "<br>";
}
?>
</td>
</tr>
<td>velocidad del viento:</td>
<td>
<?php
//: velocidad del viento
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosVelV[] = $doc_estadisticos->getElementsByTagName('velv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosVelV[$j] . " km/h" ."<br>";
}
?>
</td>
</tr>
<td>dirección del viento:</td>
<td>
<?php
//: dirección del viento
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosDirV[] = $doc_estadisticos->getElementsByTagName('dirv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosDirV[$j] ;
}
?>
</td>
</tr>
<td>con direccion hacia el: </td>
<td>
<?php
//dirección del viento en formato texto
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosDirVText[] = $doc_estadisticos->getElementsByTagName('dirvTexto')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosDirVText[$j] . "<br>";
}
?>
</td>
</tr>
<td>precipitacion acumulada:</td>
<td>
<?php
//precipitacion acumulada|
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosprecAcumulada[] = $doc_estadisticos->getElementsByTagName('precAcumulada')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosprecAcumulada[$j] . "<br>";
}
?>
</td>
</tr>
</table>
</body>
</html><file_sep><!DOCTYPE html>
<html>
<head>
<title>Fusion tables</title>
<style type="text/css">
#map_canvas {
width: 650px;
height: 450px;
margin-bottom: 10px;
top:0%;
left:0%;
}
</style>
<!-- Customize the content security policy in the meta tag below as needed. Add 'unsafe-inline' to default-src to enable inline JavaScript.
For details, see http://go.microsoft.com/fwlink/?LinkID=617521
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
-->
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>app</title>
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<KEY>&callback=initMap">
</script>
<script type="text/javascript">
//definir capa fusion Tables
var capa1 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1QmqsXAFzy6Ngivk8YXM0ZG2OEPttTiWKPs_Lv5pH'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa2 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1O<KEY>'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa3 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1-evLAUWaXGtGY3QasNLavAsP9VIeZTMaBqw4aw-r'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa4 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1vGQYZWyRr_EUvIXLd_mnmOLzhiayBIwAv7Z1N1lT'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa5 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1bulqje2AuwBdIOrVHcfNjm4nWzWafCV_ZqUlbDjP'
},
options:{
styleId: 2,
templateId: 2
}
});
var capa6 = new google.maps.FusionTablesLayer({
query: {
select: 'geometry',
from: '1Oi5hOeI-D7QQv0VbbPdz6xWQ_6v74tkR_JtdX-e9'
},
options:{
styleId: 2,
templateId: 2
}
});
function initialize(){
//Latitud y Longitud del centro del mapa Google Maps
var posicion = new google.maps.LatLng(19.292222222222, -99.653888888889);
//Opciones de Mapa
var opcionesmap = {
zoom: 8,
center: posicion,
panControl: true,
zoomControl: true,
scaleControl: true,
mapTypeId: google.maps.MapTypeId.HYBRID
};
map = new google.maps.Map(document.getElementById("map_canvas"), opcionesmap);
//Se establece si las capas se dibujan en el mapa
capa1.setMap(map);
capa2.setMap(null); //Si se coloca null el mapa no se dibuja de inicio
capa3.setMap(null); //Si se coloca null el mapa no se dibuja de inicio
capa4.setMap(null); //Si se coloca null el mapa no se dibuja de inicio
capa5.setMap(null); //Si se coloca null el mapa no se dibuja de inicio
capa6.setMap(map); //Si se coloca null el mapa no se dibuja de inicio
}
function enciendecapas(seleccionTablaID){
if (seleccionTablaID == "1QmqsXAFzy6Ngivk8YXM0ZG2OEPttTiWKPs_Lv5pH"){
if (document.getElementById("capa1").checked == true) {
if(capa1.getMap() == null) { capa1.setMap(map); }
}
if (document.getElementById("capa1").checked == false) {
capa1.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1O2Xjgu4DaLVANS7zPMwO_fIajhvVPkuEFtZ0LUcx"){
if (document.getElementById("capa2").checked == true) {
if(capa2.getMap() == null) { capa2.setMap(map); }
}
if (document.getElementById("capa2").checked == false) {
capa2.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1-evLAUWaXGtGY3QasNLavAsP9VIeZTMaBqw4aw-r"){
if (document.getElementById("capa3").checked == true) {
if(capa3.getMap() == null) { capa3.setMap(map); }
}
if (document.getElementById("capa3").checked == false) {
capa3.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1vGQYZWyRr_EUvIXLd_mnmOLzhiayBIwAv7Z1N1lT"){
if (document.getElementById("capa4").checked == true) {
if(capa4.getMap() == null) { capa4.setMap(map); }
}
if (document.getElementById("capa4").checked == false) {
capa4.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1bulqje2AuwBdIOrVHcfNjm4nWzWafCV_ZqUlbDjP"){
if (document.getElementById("capa5").checked == true) {
if(capa5.getMap() == null) { capa5.setMap(map); }
}
if (document.getElementById("capa5").checked == false) {
capa5.setMap(null); /*Apaga Capa*/
}
}//FIN IF
if (seleccionTablaID == "1Oi5hOeI-D7QQv0VbbPdz6xWQ_6v74tkR_JtdX-e9"){
if (document.getElementById("capa6").checked == true) {
if(capa6.getMap() == null) { capa6.setMap(map); }
}
if (document.getElementById("capa6").checked == false) {
capa6.setMap(null); /*Apaga Capa*/
}
}//FIN IF
function consultaestaciones()
{
<?php
$yeah = 5;
echo $yeah;
?>
}
}
</script>
</head>
<body onLoad="initialize()">
<!-- logo inifap -->
<div class="logo">
<article class="item">
<a href="#" class="image fit"><img src="images/inifap.png" alt="" /></a>
<!--o puede llevarnos al lin la imagen a inicio con este codigo
<a href="index.html" class="image fit"><img src="imagenes/inifap.jpg" alt="" /></a>
-->
</article>
</div>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
<div class="inner">
<header>
<h1><a href="index.html" id="logo">ESTACIONES AGROCLIMATICAS</a></h1>
<hr />
</header>
</div>
<!-- lista de links para el DEZPLAZAMIENTO -->
<nav id="nav">
<ul>
<li><a href="#MAPA" id="MAPA-link" class="skel-layers-ignoreHref"><span class="icon fa-home">MAPA</span></a></li>
<li><a href="#15minutos" id="15minutos-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Datos cada 15 minutos</span></a></li>
<li><a href="#estadisticos" id="estadisticos-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Datos estadisticos</span></a></li>
<li><a href="#humedadrelativa" id="humedadrelativa-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Temperatura y humedadrelativa</span></a></li>
<li><a href="#Pronostico" id="Pronostico-link" class="skel-layers-ignoreHref"><span class="icon fa-th">Pronostico</span></a></li>
</ul>
</nav>
<!-- MAPA -->
<section id="MAPA" class="one dark cover">
<div class="container">
<header>
<h1>Estaciones </h1>
</header>
<!-- <footer>
<a href="#portfolio" class="button scrolly">Magna Aliquam</a>
</footer> -->
</div>
</section>
<table>
<tr>
<td>
<div id="map_canvas" ></div>
</td>
</tr>
</table>
<table>
<tr>
<td>
<form>
<!--Controles para apagar y encender capas-->
<input type="checkbox" value="1Oi5hOeI-D7QQv0VbbPdz6xWQ_6v74tkR_JtdX-e9"id="capa6" onClick="enciendecapas(this.value);" checked="checked">Estaciones agroclimáticas<br>
<input type="checkbox" value="1QmqsXAFzy6Ngivk8YXM0ZG2OEPttTiWKPs_Lv5pH"id="capa1" onClick="enciendecapas(this.value);" checked="checked">Municipios<br>
<input type="checkbox" value="1O2Xjgu4DaLVANS7zPMwO_fIajhvVPkuEFtZ0LUcx"id="capa2" onClick="enciendecapas(this.value);" checked="checked">Uso de suelo<br>
<input type="checkbox" value="1-evLAUWaXGtGY3QasNLavAsP9VIeZTMaBqw4aw-r"id="capa3" onClick="enciendecapas(this.value);" checked="checked">Edafologia<br>
<input type="checkbox" value="1vGQYZWyRr_EUvIXLd_mnmOLzhiayBIwAv7Z1N1lT"id="capa4" onClick="enciendecapas(this.value);" checked="checked">Hidrologia<br>
<input type="checkbox" value="1bulqje2AuwBdIOrVHcfNjm4nWzWafCV_ZqUlbDjP"id="capa5" onClick="enciendecapas(this.value);" checked="checked">Frontera agricola<br>
</form>
</td>
<td>
<?php
//Create the client object
$soapclient = new SoapClient('http://clima.inifap.gob.mx/data/webservice.asmx?WSDL');
//Use the functions of the client, the params of the function are in
//the associative array
// variables que usamos de entrada para solicitar informacion
$edo=10;
$numero=33;
$estacion=33;
//juntamos todos los paramentros en esa variable para posteriormente mandarlos a llamar
$params = array('numero' => $numero,'estacion' => $estacion, 'edo' => $edo);
// $params = array('edo' => '10'); // id del estado del cual queremos obtener las estaciones
//establecemos las conexiones y mandamos los parametros
$responseGetEstaciones = $soapclient->GetEstaciones($params);
$responseGetEstacionesString = $responseGetEstaciones->GetEstacionesResult; // convertir de objeto a string
// Parse information
$xml = $responseGetEstaciones->GetEstacionesResult;
$doc = new DOMDocument();
$doc->loadXML($xml);
// VARIABLES que nos va arrojar
$arrayEstacionesNombre = [];
$arrayEstacionesNumero = [];
for ($i=0; $i < 22; $i++) {
$arrayEstacionesNumero[] = $doc->getElementsByTagName('numero')->item($i)->nodeValue;
$arrayEstacionesNombre[] = $doc->getElementsByTagName('nombre')->item($i)->nodeValue;
}
//imprime todas las estaciones
/*for ($j=0; $j < 22; $j++) {
echo "Estación número: " . $arrayEstacionesNumero[$j] . " Nombre: " , $arrayEstacionesNombre[$j] . "<br>";
}
*/
//var_dump($responseGetEstaciones);
?>
<form id="form1" name="form1"method="post" >
Estacion
<select name="select_estaciones" onchange= "seleccionaestacion("this.form")" >
<?php
for ($j=0; $j < 22; $j++) { ?>
<option value= <?php echo $arrayEstacionesNumero[$j]?> > <?php echo $arrayEstacionesNombre[$j]."</br>";
}
?> </option>
</select>
<input type="submit" value= "Consultar">
</form>
</td>
</tr>
</table>
<!-- Datos cada 15 minutos -->
<section id="15minutos" class="two">
<div class="container">
<header>
<h1>Datos Estadisticos</h1>
<table border="1">
<tr>
<th>Velocidad del viento</th>
<th>---datos---</th>
</tr>
<tr>
<th scope="col">Direccion del viento;</th>
<th scope="col"> </th>
</tr>
</table
</header>
<p></p>
</div>
</section>
<!-- aqui empieza las tablas -->
<?php
$soapclient = new SoapClient('http://clima.inifap.gob.mx/data/webservice.asmx?WSDL');
//variables
//echo $_POST ["select_estaciones"];
$edo=10;
$numero = $_POST ["select_estaciones"];
//echo $estacion;
?>
<?php
//Create the client object
//Use the functions of the client, the params of the function are in
//the associative array
// variables que usamos de entrada para solicitar informacion
//juntamos todos los paramentros en esa variable para posteriormente mandarlos a llamar
$params = array('numero' => $numero,'estacion' => $numero, 'edo' => $edo);
// $params = array('edo' => '10'); // id del estado del cual queremos obtener las estaciones
?>
<?php
//// estacuiones datos
$responseEstacionDatos = $soapclient->EstacionDatos($params);
$responseEstacionDatosString = $responseEstacionDatos->EstacionDatosResult;
// Parse information
$xml_datos = $responseEstacionDatos->EstacionDatosResult;
$doc_datos = new DOMDocument();
$doc_datos->loadXML($xml_datos);
$arrayEstacionDatosFecha = [];
$arrayEstacionDatosPrec = [];
$arrayEstacionDatosTemp = [];
$arrayEstacionDatosDir = [];
$arrayEstacionDatosVel = [];
$arrayEstacionDatosRad = [];
$arrayEstacionDatosHumr = [];
$arrayEstacionDatosHumh = [];
?>
<h1>Datos Estadisticos</h1>
---------------- Datos de la estacion ------------------
<table>
<tr>
<td>Fecha y hora:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosFecha[] = $doc_datos->getElementsByTagName('fecha')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo " " . $arrayEstacionDatosFecha[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>precipitacion:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosPrec[] = $doc_datos->getElementsByTagName('prec')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosPrec[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>temperatura:</td>
<td>
<?php
//temperatura
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosTemp[] = $doc_datos->getElementsByTagName('temt')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosTemp[$j] . " <br>";
}
?>
</td>
</tr>
<tr>
<td>direccion del viento:</td>
<td>
<?php
//direccion del viento
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosDir[] = $doc_datos->getElementsByTagName('dirv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosDir[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Velocidad del viento: </td>
<td>
<?php
//VELOCIDAD DEL VIENTO
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosVel[] = $doc_datos->getElementsByTagName('velv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosVel[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Radiacion:</td>
<td>
<?php
//radiacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosRad[] = $doc_datos->getElementsByTagName('radg')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosRad[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Humedad r:</td>
<td>
<?php
//humedad r
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosHumr[] = $doc_datos->getElementsByTagName('humr')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosHumr[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Humedad H:</td>
<td>
<?php
//Humedad h
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosHumh[] = $doc_datos->getElementsByTagName('humh')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosHumh[$j] . "<br>";
}
?>
</td>
</tr>
</table>
------------------datos estadisticos----------------
<?php
$arrayGetEstadisticosFecha = [];
$arrayGetEstadisticosprecAcumulada = [];
$arrayGetEstadisticosTempMax = [];
$arrayGetEstadisticosTempMin = [];
$arrayGetEstadisticosTempMed = [];
$arrayGetEstadisticosHumR = [];
$arrayGetEstadisticosDirV = [];
$arrayGetEstadisticosVelV = [];
$arrayGetEstadisticosDirVText = [];
//// estacuiones datos
$responseGetEstadisticos = $soapclient->GetEstadisticos ($params);
$responseGetEstadisticosString = $responseGetEstadisticos ->GetEstadisticosResult;
// Parse information
$xml_estadisticos = $responseGetEstadisticos->GetEstadisticosResult;
$doc_estadisticos = new DOMDocument();
$doc_estadisticos->loadXML($xml_estadisticos);
?>
<table>
<tr>
<td>Fecha y hora:</td>
<td>
<?php
//fecha
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosFecha[] = $doc_estadisticos->getElementsByTagName('fecha')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo "" . $arrayGetEstadisticosFecha[$j] . "<br>";
}
?>
</td>
</tr>
<td>precipitacion:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosPrec[] = $doc_estadisticos->getElementsByTagName('prec')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosPrec[$j] . "<br>";
}
?>
</td>
</tr>
<td>temperatura maxima:</td>
<td>
<?php
//: temperatura maxima
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMax[] = $doc_estadisticos->getElementsByTagName('tmax')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMax[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>Temperatura minina:</td>
<td>
<?php
//: temperatura mínima
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMin[] = $doc_estadisticos->getElementsByTagName('tmin')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMin[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>temperatura media:</td>
<td>
<?php
//temperatura media
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMed[] = $doc_estadisticos->getElementsByTagName('tmed')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMed[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>humedad relativa:</td>
<td>
<?php
//humedad relativa
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosHumR[] = $doc_estadisticos->getElementsByTagName('humr')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosHumR[$j] . "<br>";
}
?>
</td>
</tr>
<td>velocidad del viento:</td>
<td>
<?php
//: velocidad del viento
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosVelV[] = $doc_estadisticos->getElementsByTagName('velv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosVelV[$j] . " km/h" ."<br>";
}
?>
</td>
</tr>
<td>dirección del viento:</td>
<td>
<?php
//: dirección del viento
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosDirV[] = $doc_estadisticos->getElementsByTagName('dirv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosDirV[$j] ;
}
?>
</td>
</tr>
<td>con direccion hacia el: </td>
<td>
<?php
//dirección del viento en formato texto
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosDirVText[] = $doc_estadisticos->getElementsByTagName('dirvTexto')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosDirVText[$j] . "<br>";
}
?>
</td>
</tr>
<td>precipitacion acumulada:</td>
<td>
<?php
//precipitacion acumulada|
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosprecAcumulada[] = $doc_estadisticos->getElementsByTagName('precAcumulada')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosprecAcumulada[$j] . "<br>";
}
?>
</td>
</tr>
</table>
<!-- Datos estadisticos -->
<section id="estadisticos" class="three">
<div class="container">
<header>
<h1>Datos Estadisticos</h1>
</header>
</div>
</section>
<!-- Temperatura y humedad relativa -->
<section id="humedadrelativa" class="four">
<div class="container">
<header>
<h1>Temperatura y humedad relativa</h1>
</header>
</div>
</section> <!-- Pronostico -->
<section id="Pronostico" class="five">
<div class="container">
<header>
<h1>Pronostico</h1>
<table border= "1" , id= pronostico>
<tr>
<th scope="col">Dia 1</th>
<th scope="col">Datos;</th>
</tr>
<tr>
<th scope="col">Precipitacion</th>
<td> </td>
</tr>
<tr>
<th>Temperatura maxima</th>
<th>---datos---</th>
</tr>
<tr>
<th>Temperatura minima</th>
<th>---datos---</th>
</tr>
<tr>
<th>Temperatura media</th> <th>---datos---</th>
</tr>
</table
</header>
</div>
</section>
</body>
</html>
<file_sep><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="utf-8">
</head>
<body>
<?php
$soapclient = new SoapClient('http://clima.inifap.gob.mx/data/webservice.asmx?WSDL');
//variables
//echo $_POST ["select_estaciones"];
$edo=10;
$numero = $_POST ["select_estaciones"];
//echo $estacion;
?>
<?php
//Create the client object
//Use the functions of the client, the params of the function are in
//the associative array
// variables que usamos de entrada para solicitar informacion
//juntamos todos los paramentros en esa variable para posteriormente mandarlos a llamar
$params = array('numero' => $numero,'estacion' => $numero, 'edo' => $edo);
// $params = array('edo' => '10'); // id del estado del cual queremos obtener las estaciones
?>
<?php
//// estacuiones datos
$responseEstacionDatos = $soapclient->EstacionDatos($params);
$responseEstacionDatosString = $responseEstacionDatos->EstacionDatosResult;
// Parse information
$xml_datos = $responseEstacionDatos->EstacionDatosResult;
$doc_datos = new DOMDocument();
$doc_datos->loadXML($xml_datos);
$arrayEstacionDatosFecha = [];
$arrayEstacionDatosPrec = [];
$arrayEstacionDatosTemp = [];
$arrayEstacionDatosDir = [];
$arrayEstacionDatosVel = [];
$arrayEstacionDatosRad = [];
$arrayEstacionDatosHumr = [];
$arrayEstacionDatosHumh = [];
?>
---------------- Datos de la estacion ------------------
<table>
<tr>
<td>Fecha y hora:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosFecha[] = $doc_datos->getElementsByTagName('fecha')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo " " . $arrayEstacionDatosFecha[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>precipitacion:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosPrec[] = $doc_datos->getElementsByTagName('prec')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosPrec[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>temperatura:</td>
<td>
<?php
//temperatura
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosTemp[] = $doc_datos->getElementsByTagName('temt')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosTemp[$j] . " <br>";
}
?>
</td>
</tr>
<tr>
<td>direccion del viento:</td>
<td>
<?php
//direccion del viento
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosDir[] = $doc_datos->getElementsByTagName('dirv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosDir[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Velocidad del viento: </td>
<td>
<?php
//VELOCIDAD DEL VIENTO
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosVel[] = $doc_datos->getElementsByTagName('velv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosVel[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Radiacion:</td>
<td>
<?php
//radiacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosRad[] = $doc_datos->getElementsByTagName('radg')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosRad[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Humedad r:</td>
<td>
<?php
//humedad r
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosHumr[] = $doc_datos->getElementsByTagName('humr')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosHumr[$j] . "<br>";
}
?>
</td>
</tr>
<tr>
<td>Humedad H:</td>
<td>
<?php
//Humedad h
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosHumh[] = $doc_datos->getElementsByTagName('humh')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosHumh[$j] . "<br>";
}
?>
</td>
</tr>
</table>
------------------datos estadisticos----------------
<?php
$arrayGetEstadisticosFecha = [];
$arrayGetEstadisticosprecAcumulada = [];
$arrayGetEstadisticosTempMax = [];
$arrayGetEstadisticosTempMin = [];
$arrayGetEstadisticosTempMed = [];
$arrayGetEstadisticosHumR = [];
$arrayGetEstadisticosDirV = [];
$arrayGetEstadisticosVelV = [];
$arrayGetEstadisticosDirVText = [];
//// estacuiones datos
$responseGetEstadisticos = $soapclient->GetEstadisticos ($params);
$responseGetEstadisticosString = $responseGetEstadisticos ->GetEstadisticosResult;
// Parse information
$xml_estadisticos = $responseGetEstadisticos->GetEstadisticosResult;
$doc_estadisticos = new DOMDocument();
$doc_estadisticos->loadXML($xml_estadisticos);
?>
<table>
<tr>
<td>Fecha y hora:</td>
<td>
<?php
//fecha
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosFecha[] = $doc_estadisticos->getElementsByTagName('fecha')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo "" . $arrayGetEstadisticosFecha[$j] . "<br>";
}
?>
</td>
</tr>
<td>precipitacion:</td>
<td>
<?php
//precipitacion
for ($i=0; $i < 1; $i++) {
$arrayEstacionDatosPrec[] = $doc_estadisticos->getElementsByTagName('prec')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayEstacionDatosPrec[$j] . "<br>";
}
?>
</td>
</tr>
<td>temperatura maxima:</td>
<td>
<?php
//: temperatura maxima
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMax[] = $doc_estadisticos->getElementsByTagName('tmax')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMax[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>Temperatura minina:</td>
<td>
<?php
//: temperatura mínima
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMin[] = $doc_estadisticos->getElementsByTagName('tmin')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMin[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>temperatura media:</td>
<td>
<?php
//temperatura media
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosTempMed[] = $doc_estadisticos->getElementsByTagName('tmed')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosTempMed[$j] . "° centigrados" . "<br>";
}
?>
</td>
</tr>
<td>humedad relativa:</td>
<td>
<?php
//humedad relativa
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosHumR[] = $doc_estadisticos->getElementsByTagName('humr')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosHumR[$j] . "<br>";
}
?>
</td>
</tr>
<td>velocidad del viento:</td>
<td>
<?php
//: velocidad del viento
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosVelV[] = $doc_estadisticos->getElementsByTagName('velv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosVelV[$j] . " km/h" ."<br>";
}
?>
</td>
</tr>
<td>dirección del viento:</td>
<td>
<?php
//: dirección del viento
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosDirV[] = $doc_estadisticos->getElementsByTagName('dirv')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosDirV[$j] ;
}
?>
</td>
</tr>
<td>con direccion hacia el: </td>
<td>
<?php
//dirección del viento en formato texto
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosDirVText[] = $doc_estadisticos->getElementsByTagName('dirvTexto')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosDirVText[$j] . "<br>";
}
?>
</td>
</tr>
<td>precipitacion acumulada:</td>
<td>
<?php
//precipitacion acumulada|
for ($i=0; $i < 1; $i++) {
$arrayGetEstadisticosprecAcumulada[] = $doc_estadisticos->getElementsByTagName('precAcumulada')->item($i)->nodeValue;
}
for ($j=0; $j < 1; $j++) {
echo $arrayGetEstadisticosprecAcumulada[$j] . "<br>";
}
?>
</td>
</tr>
</table>
</body>
</html> | 69e36436c1e6e2c4fd018ca8799ceee6eb23541c | [
"PHP"
] | 5 | PHP | jorgemauricio/proyectoAlejandro2 | 91178774274963717d1b3ad5599c442ac3c3b08d | 65de43bd34f287a5b448fd73c4b7ed185b151be5 | |
refs/heads/master | <repo_name>maacpiash/medium-posts-host<file_sep>/index.ts
import express from 'express';
const app = express();
app.get("/", (req, res) => {
res.set('Content-Type', 'application/json')
res.send([
{
id: '1<PASSWORD>',
title: 'The Myth of Digital Ecosystem',
time: 7.558490566037736,
date: 1539612875583,
text: 'How well does the idea of an ecosystem of devices and services hold up in 2018?',
image: 'https://cdn-images-1.medium.com/max/400/1*VrQC868zdZ6jcFjG-VWMNg.jpeg',
url: 'https://medium.com/maacpiash/the-myth-of-digital-ecosystem-1be2df4701f1'
},
{
id: '31dd2e1dc4eb',
title: 'শার্প সমাচার (১) : লিংক নিয়ে প্রাথমিক আলোচনা',
time: 4.185849056603773,
date: 1536245626106,
text: 'না, এই লিংক মানে সেই বিখ্যাত (!) link না।',
image: 'https://cdn-images-1.medium.com/max/400/1*zjFSNUBQRQRv5ErPd2Hh9Q.jpeg',
url: 'https://medium.com/maacpiash/শার্প-সমাচার-১-লিংক-নিয়ে-প্রাথমিক-আলোচনা-31dd2e1dc4eb'
}
]);
});
const PORT = process.env.PORT || 7000;
app.listen(PORT, () => {
console.log(`Server is running in http://localhost:${PORT}`)
})
| 12cd52e3bbc98ad898b12a09227425e94dcd65a8 | [
"TypeScript"
] | 1 | TypeScript | maacpiash/medium-posts-host | 017f67e844cb79a1d6c3077ee959df20f437cb29 | 9e273e7d9deb74deaa2820f39e07643a11881c3d | |
refs/heads/main | <repo_name>antonio-aranda7/PDM1-Jeancarlo-Antonio<file_sep>/README.md
# PDM1-Jeancarlo-Antonio
Aplicaciones de Android Studio CURP, RFC, Amigo Secreto de la materia Electiva de Desarrollo Movil 1
Generador de CURP
https://user-images.githubusercontent.com/72113007/125532504-3f9add21-9000-4f66-a032-410ea950905c.mp4
[CURP_PDM1_Jeancarlo Aranda.pdf](https://github.com/antonio-aranda7/PDM1-Jeancarlo-Antonio/files/6812281/CURP_PDM1_Jeancarlo.Aranda.pdf)
https://chetumaltecnm.sharepoint.com/sites/Videos/Documentos%20compartidos/Forms/AllItems.aspx?id=%2Fsites%2FVideos%2FDocumentos%20compartidos%2FGeneral%2FRecordings%2FReuni%C3%B3n%20en%20%5FGeneral%5F%2D20210712%5F193538%2DGrabaci%C3%B3n%20de%20la%20reuni%C3%B3n%2Emp4&parent=%2Fsites%2FVideos%2FDocumentos%20compartidos%2FGeneral%2FRecordings
Generador de RFC
https://user-images.githubusercontent.com/72113007/125532572-b23ff37c-4374-4871-9aaa-abcffc0fc3bb.mp4
[RFC_PDM1_Jeancarlo Aranda.pdf](https://github.com/antonio-aranda7/PDM1-Jeancarlo-Antonio/files/6812283/RFC_PDM1_Jeancarlo.Aranda.pdf)
https://chetumaltecnm.sharepoint.com/sites/Videos/Documentos%20compartidos/Forms/AllItems.aspx?id=%2Fsites%2FVideos%2FDocumentos%20compartidos%2FGeneral%2FRecordings%2FNueva%20reuni%C3%B3n%20de%20canal%2D20210713%5F164512%2DGrabaci%C3%B3n%20de%20la%20reuni%C3%B3n%2Emp4&parent=%2Fsites%2FVideos%2FDocumentos%20compartidos%2FGeneral%2FRecordings
Amigo Secreto
https://user-images.githubusercontent.com/72113007/125532605-77fa0986-06f4-47df-8050-f4198e926668.mp4
[AmigoSecreto_PDM1_Jeancarlo Aranda.pdf](https://github.com/antonio-aranda7/PDM1-Jeancarlo-Antonio/files/6812285/AmigoSecreto_PDM1_Jeancarlo.Aranda.pdf)
https://chetumaltecnm.sharepoint.com/sites/Videos/Documentos%20compartidos/Forms/AllItems.aspx?id=%2Fsites%2FVideos%2FDocumentos%20compartidos%2FGeneral%2FRecordings%2FNueva%20reuni%C3%B3n%20de%20canal%2D20210713%5F154245%2DGrabaci%C3%B3n%20de%20la%20reuni%C3%B3n%2Emp4&parent=%2Fsites%2FVideos%2FDocumentos%20compartidos%2FGeneral%2FRecordings
<file_sep>/AmigoSecreto-Jeancarlo-Antonio/settings.gradle
rootProject.name='AmigoSecreto_Jeancarlo_Antonio'
include ':app'
<file_sep>/RFC-Jeancarlo-Antonio/settings.gradle
rootProject.name='RFC-Jeancarlo-Antonio'
include ':app'
<file_sep>/CURP-Jeancarlo-Antonio/app/src/main/java/com/example/curp_jeancarlo_antonio/MainActivity.kt
package com.example.curp_jeancarlo_antonio
import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//****************************************************************************************->
val calendario = Calendar.getInstance()
val DD = calendario.get(Calendar.DAY_OF_MONTH)
val MM = calendario.get(Calendar.MONTH)
val AAAA = calendario.get(Calendar.YEAR)
btnFecha.setOnClickListener {
var datePickD = DatePickerDialog(this,DatePickerDialog.OnDateSetListener { view, aaaa, mm, dd ->
var mes = (mm+1).toString()
if (mes.toInt()<10){
mes = "0" + mes
}
var dia = (dd).toString()
if (dia.toInt()<10){
dia = "0" + dia
}
txtViewFecha.setText(""+ dia + "/" + (mes) + "/" + aaaa)},AAAA, MM, DD)
datePickD.show()
}
var genero = ""
radioBtbGroupGenero.setOnCheckedChangeListener { group, i ->
if (i == R.id.radioBtnH)
genero = radioBtnH.text[0].toString()
Toast.makeText(this,genero,Toast.LENGTH_SHORT).show()
if (i == R.id.radioBtnM)
genero = radioBtnM.text[0].toString()
Toast.makeText(this,genero,Toast.LENGTH_SHORT).show()
}
var arrayEstados = arrayOf("AS-Aguascalientes","BC-Baja California","BS-Baja California Sur","CC-Campeche","CL-Coahuila","CM-Colima", "CS-Chiapas","CH-Chihuahua","DF-Distrito Federal","DG-Durango","GT-Guanajuato","GR-Guerrero","HG-Hidalgo","JC-Jalisco","MC-México","MN-Michoacán","MS-Morelos","NT-Nayarit", "NL-Nuevo León","OC-Oaxaca","PL-Puebla","QT-Querétaro","QR-Quintana Roo","SP-San Luis Potosí","SL-Sinaloa","SR-Sonora","TC-Tabasco","TS-Tamaulipas", "TL-Tlaxcala","VZ-Veracruz","YN-Yucatan","ZS-Zacatecas","NE-Nacido en el Extrenjero")
val arrayAdapter = ArrayAdapter(this@MainActivity,android.R.layout.simple_spinner_dropdown_item,arrayEstados)
spinnerEstados.adapter = arrayAdapter
spinnerEstados.onItemSelectedListener = object :AdapterView.OnItemSelectedListener {
override fun onItemSelected(
parent: AdapterView<*>?,
view: View?,
position: Int,
id: Long
) {
val estado = (arrayEstados[position])
txtViewEstados.setText(estado)
}
override fun onNothingSelected(parent: AdapterView<*>?) {
}
}
val mutableValues = mutableListOf("0","1","2","3","4","5","6","7","8","9")
btnGenerar.setOnClickListener {
val name = txtName.text;
val consonanteNombre = SinVocal(name.toString())
var segundaConsonateNombre16 = ""
if (name[0].toLowerCase() == 'a'|| name[0].toLowerCase() == 'e'|| name[0].toLowerCase() == 'i'|| name[0].toLowerCase() == 'o'|| name[0].toLowerCase() == 'u' ){
segundaConsonateNombre16 = consonanteNombre[0].toString().toUpperCase()
}
else{
segundaConsonateNombre16 = consonanteNombre[1].toString().toUpperCase()
}
val apellidoPaterno = txtApePat.text
var apellidoVocal = SinConsonante(apellidoPaterno.toString())
var primerVocalPat2 = ""
if (apellidoPaterno[0].toLowerCase() == 'a'|| apellidoPaterno[0].toLowerCase() == 'e'|| apellidoPaterno[0].toLowerCase() == 'i'|| apellidoPaterno[0].toLowerCase() == 'o'|| apellidoPaterno[0].toLowerCase() == 'u' ){
primerVocalPat2 = apellidoVocal[1].toString().toUpperCase()
}
else{
primerVocalPat2 = apellidoVocal[0].toString().toUpperCase()
}
val consonantePaterno = SinVocal(apellidoPaterno.toString())
var segundaConsonatePat14 = ""
if (apellidoPaterno[0].toLowerCase() == 'a'|| apellidoPaterno[0].toLowerCase() == 'e'|| apellidoPaterno[0].toLowerCase() == 'i'|| apellidoPaterno[0].toLowerCase() == 'o'|| apellidoPaterno[0].toLowerCase() == 'u' ){
segundaConsonatePat14 = consonantePaterno[0].toString().toUpperCase()
}
else{
segundaConsonatePat14 = consonantePaterno[1].toString().toUpperCase()
}
val apellidoMaterno = txtApeMat.text
val consonanteMaterno = SinVocal(apellidoMaterno.toString())
var segundaConsonateMat15 = ""
if (apellidoMaterno[0].toLowerCase() == 'a'|| apellidoMaterno[0].toLowerCase() == 'e'|| apellidoMaterno[0].toLowerCase() == 'i'|| apellidoMaterno[0].toLowerCase() == 'o'|| apellidoMaterno[0].toLowerCase() == 'u' ){
segundaConsonateMat15 = consonanteMaterno[0].toString().toUpperCase()
}
else{
segundaConsonateMat15 = consonanteMaterno[1].toString().toUpperCase()
}
val fecha = txtViewFecha.text.toString()
if(name.length == 0 || apellidoPaterno.length == 0 || apellidoMaterno.length == 0){
Toast.makeText(this,"No ah ingresado todos sus datos",Toast.LENGTH_SHORT).show()
}
else{
var primerPat1 = apellidoPaterno[0].toString().toUpperCase()
var primerMat3 = apellidoMaterno[0].toString().toUpperCase()
var primerNombre4 = name[0].toString().toUpperCase()
var decada5 = fecha[8]
var año6 = fecha[9]
var mes7 = fecha[3]
var mes8 = fecha[4]
var dia9 = fecha[0]
var dia10 = fecha[1]
var genero11 = genero
var estado12 = txtViewEstados.text[0]
var estado13 = txtViewEstados.text[1]
val valor17 = mutableValues.random()
val valor18 = mutableValues.random()
txtViewCURP.text = primerPat1 + primerVocalPat2 + primerMat3 + primerNombre4 + decada5 + año6 + mes7 + mes8 + dia9 + dia10 + genero11 + estado12 + estado13 + segundaConsonatePat14 + segundaConsonateMat15 + segundaConsonateNombre16 + valor17 + valor18
}
}
btbBorrar.setOnClickListener {
var nombre = findViewById<EditText>(R.id.txtName)
nombre.text.clear()
var apePat = findViewById<EditText>(R.id.txtApePat)
apePat.text.clear()
var apeMat = findViewById<EditText>(R.id.txtApeMat)
apeMat.text.clear()
var fecha = findViewById<TextView>(R.id.txtViewFecha)
fecha.setText("Fecha")
var estado = findViewById<TextView>(R.id.txtViewEstados)
estado.setText("Estado")
var curp = findViewById<TextView>(R.id.txtViewCURP)
curp.setText("CURP")
}
//****************************************************************************************<-
}
//*****************************************************************************
fun SinConsonante( text: String ): String {
val resultado = StringBuilder()
for ( char in text ) {
if ( !"bcdfghjklmnñpqrstvwxyz".contains(char.toLowerCase()) ) {
resultado.append( char )
}
}
return resultado.toString()
}
fun SinVocal( text: String ): String {
val resultado = StringBuilder()
for ( char in text ) {
if ( !"aeiou".contains(char.toLowerCase()) ) {
resultado.append( char )
}
}
return resultado.toString()
}
//********************************************************************************************<-
}
<file_sep>/AmigoSecreto-Jeancarlo-Antonio/app/src/main/java/com/example/AmigoSecreto_Jeancarlo_Antonio/MainActivity.kt
package com.example.AmigoSecreto_Jeancarlo_Antonio
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.Collections.shuffle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//****************************************************************************************->
val Amigo = txtAmigo.text;
var listaAmigos = findViewById<ListView>(R.id.listViewAmigos);
var arrayAdapter: ArrayAdapter<*>
val cadenaAmigos = mutableListOf<String>();
var btnAgregar = findViewById<Button>(R.id.btnAgregar);
btnAgregar.setOnClickListener {
cadenaAmigos.add(Amigo.toString())
arrayAdapter = ArrayAdapter(
this,
android.R.layout.simple_list_item_1,
cadenaAmigos
)
listaAmigos.adapter = arrayAdapter;
arrayAdapter.notifyDataSetChanged();
var nombre = findViewById<EditText>(R.id.txtAmigo)
nombre.text.clear()
}
var secreto = findViewById<TextView>(R.id.txtSecreto)
btnSortear.setOnClickListener {
if (cadenaAmigos.size <= 2){
secreto.setText("Agregue más amigos");
}
else{
var amigoSecreto = mutableListOf<String>(cadenaAmigos.toString());
shuffle(cadenaAmigos);
if (amigoSecreto.toString() == cadenaAmigos.toString()){
btnSortear.performClick();
}
else{
secreto.setText(cadenaAmigos.toString());
}
}
}
//****************************************************************************************<-
}
}
<file_sep>/RFC-Jeancarlo-Antonio/app/src/main/java/com/example/rfc_jeancarlo_antonio/MainActivity.kt
package com.example.rfc_jeancarlo_antonio
import android.app.DatePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.*
import kotlinx.android.synthetic.main.activity_main.*
import java.util.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
//****************************************************************************************->
val calendario = Calendar.getInstance()
val DD = calendario.get(Calendar.DAY_OF_MONTH)
val MM = calendario.get(Calendar.MONTH)
val AAAA = calendario.get(Calendar.YEAR)
btnFecha.setOnClickListener {
var datePickD =
DatePickerDialog(this, DatePickerDialog.OnDateSetListener { view, aaaa, mm, dd ->
var mes = (mm + 1).toString()
if (mes.toInt() < 10) {
mes = "0" + mes
}
var dia = (dd).toString()
if (dia.toInt() < 10) {
dia = "0" + dia
}
txtViewFecha.setText("" + dia + "/" + (mes) + "/" + aaaa)
}, AAAA, MM, DD)
datePickD.show()
}
val mutableValues = mutableListOf("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M","N", "O", "P", "Q", "R", "S", "T", "U", "V","W","X", "Y", "Z")
btnGenerar.setOnClickListener {
val name = txtName.text;
val apellidoPaterno = txtApePat.text
var apellidoVocal = SinConsonante(apellidoPaterno.toString())
var primerVocalPat2 = ""
if (apellidoPaterno[0].toLowerCase() == 'a' || apellidoPaterno[0].toLowerCase() == 'e' || apellidoPaterno[0].toLowerCase() == 'i' || apellidoPaterno[0].toLowerCase() == 'o' || apellidoPaterno[0].toLowerCase() == 'u') {
primerVocalPat2 = apellidoVocal[1].toString().toUpperCase()
} else {
primerVocalPat2 = apellidoVocal[0].toString().toUpperCase()
}
val apellidoMaterno = txtApeMat.text
val fecha = txtViewFecha.text.toString()
if (name.length == 0 || apellidoPaterno.length == 0 || apellidoMaterno.length == 0) {
Toast.makeText(this, "No ah ingresado todos sus datos", Toast.LENGTH_SHORT).show()
} else {
var primerPat1 = apellidoPaterno[0].toString().toUpperCase()
var primerMat3 = apellidoMaterno[0].toString().toUpperCase()
var primerNombre4 = name[0].toString().toUpperCase()
var decada5 = fecha[8]
var año6 = fecha[9]
var mes7 = fecha[3]
var mes8 = fecha[4]
var dia9 = fecha[0]
var dia10 = fecha[1]
val valor11 = mutableValues.random()
val valor12 = mutableValues.random()
val valor13 = mutableValues.random()
txtViewRFC.text =
primerPat1 + primerVocalPat2 + primerMat3 + primerNombre4 + decada5 + año6 + mes7 + mes8 + dia9 + dia10 + valor11 + valor12 + valor13
}
}
btbBorrar.setOnClickListener {
var nombre = findViewById<EditText>(R.id.txtName)
nombre.text.clear()
var apePat = findViewById<EditText>(R.id.txtApePat)
apePat.text.clear()
var apeMat = findViewById<EditText>(R.id.txtApeMat)
apeMat.text.clear()
var fecha = findViewById<TextView>(R.id.txtViewFecha)
fecha.setText("Fecha")
var rfc = findViewById<TextView>(R.id.txtViewRFC)
rfc.setText("RFC")
}
//****************************************************************************************<-
}
//********************************************************************************************->
//Metodo para eliminar las consonantes de los textos Nombre y Apellidos
fun SinConsonante( text: String ): String {
//Contruye una cadena
val resultado = StringBuilder()
//Recorre la cadena si hay texto
for (char in text) {
//Si son vocales las guarda en el arreglo
if (!"bcdfghjklmnñpqrstvwxyz".contains(char.toLowerCase())) {
resultado.append(char)
}
}
return resultado.toString()
}
//********************************************************************************************<-
}
<file_sep>/CURP-Jeancarlo-Antonio/settings.gradle
rootProject.name='CURP-Jeancarlo-Antonio'
include ':app'
| 4d602d4c780991a05b51b31fc5fa3e0e0a813b9e | [
"Markdown",
"Kotlin",
"Gradle"
] | 7 | Markdown | antonio-aranda7/PDM1-Jeancarlo-Antonio | 83cd8fbee8baaecfb1a76963eece1df41e010ee0 | 3fa6dff7229926468048c554257f350868dfaaf4 | |
refs/heads/master | <repo_name>bode-mmk/meikojourney<file_sep>/index.php
<?php
use LINE\LINEBot\Constant\HTTPHeader;
use LINE\LINEBot\Event\MessageEvent;
use LINE\LINEBot\Event\MessageEvent\TextMessage;
use LINE\LINEBot\Exception\InvalidEventRequestException;
use LINE\LINEBot\Exception\InvalidSignatureException;
require_once __DIR__ . '/vendor/autoload.php';
$httpClient = new \LINE\LINEBot\HTTPClient\CurlHTTPClient(getenv('CHANNEL_ACCESS_TOKEN'));
$bot = new \LINE\LINEBot($httpClient, ['channelSecret' => getenv('CHANNEL_SECRET')]);
$sign = $_SERVER["HTTP_" . \LINE\LINEBot\Constant\HTTPHeader::LINE_SIGNATURE];
$events = $bot->parseEventRequest(file_get_contents('php://input'), $sign);
// 返答ファイルの読み込み
$response_sentence = file("response_list");
foreach ($events as $event) {
if (!($event instanceof \LINE\LINEBot\Event\MessageEvent) ||
!($event instanceof \LINE\LINEBot\Event\MessageEvent\TextMessage)) {
continue;
}
// 返答リストから該当するものを返答する
foreach($response_sentence as $line){
// Pの発言,芽衣子さんの発言
$response = explode(",", trim($line));
if($event->getText() === $response[0]){
// 絵文字は置換する → (100007とか)
$str = preg_replace_callback('/\(([0-9A-F]{6})\)/',
function($matches) use ($emoticon){
$bin = hex2bin(str_repeat('0', 8 - strlen($matches[1])).$matches[1]);
return mb_convert_encoding($bin, 'UTF-8', 'UTF-32BE');
},
$response[1]
);
$bot->replyText($event->getReplyToken(), $str);
break;
}
}
// 取り敢えず
$mecab = new MeCab\Tagger();
$nodes = $mecab->parseToNode($event->getText());
$response_text = "";
foreach ($nodes as $n){
$response_text = $response_text . $n->getFeature();
}
$bot->replyText($event->getReplyToken(), $response_text);
}<file_sep>/for_heroku/install_extension.sh
cd /tmp
git clone https://github.com/rsky/php-mecab.git
cd php-mecab/mecab
/app/php/bin/phpize
./configure --with-mecab=/usr/local/src/mecab-0.996/mecab-config
make
make install
cd ../../ | f7f02e95b62bb28c92ebb0e4201c2b1a2d3e3cc9 | [
"PHP",
"Shell"
] | 2 | PHP | bode-mmk/meikojourney | 994397f1a8f1333a1216b0eaad7e326900550683 | 77ce974d9d4d55a875eb19cb7116f155b2adfefa | |
refs/heads/master | <file_sep>import React from 'react';
import List from './Components/List.js';
import Contoller from './Components/Contoller.js';
class App extends React.Component{
constructor(){
super();
this.state={
inputValue:'',
data:[
// {text:'aaa',completed:false,id:1},
// {text:'bbb',completed:false,id:2},
// {text:'ccc',completed:false,id:3}
],
visible:'All'
}
}
handleSubmit(e){
e.preventDefault();
let newData =this.state.inputValue.trim();
if(newData.length===0){
alert('输入的内容不可以为空,请重新输入')
}else{
let newItem={
text:newData,
completed:false,
id:new Date().getTime()
}
this.setState({
data:[...this.state.data,newItem]
})
}
this.setState({inputValue:''})
}
handleChange(e){
this.setState({inputValue:e.target.value})
}
handleChecked(id){
let index=this.state.data.findIndex(item=>item.id===id)
this.state.data[index].completed=!this.state.data[index].completed
this.setState({data:this.state.data})
}
handleRemove(id){
let index=this.state.data.findIndex(item=>item.id===id)
this.state.data.splice(index,1)
this.setState({data:this.state.data})
}
handleControl(item){
this.setState({visible:item})
}
componentWillMount(){
if (localStorage.todos) {
this.setState({data: JSON.parse(window.localStorage.getItem('todos') || '[]') })
}
}
render(){
localStorage.setItem('todos',JSON.stringify(this.state.data))
let styles={
div:{
maxWidth:'500px',
margin:'0 auto',
},
h1:{
textAlign: "center"
}
}
let newArray;
switch (this.state.visible) {
case 'Active':
newArray=this.state.data.filter(item=>item.completed==false)
break;
case 'Completed':
newArray=this.state.data.filter(item=>item.completed==true)
break;
default:
newArray=this.state.data
}
return(
<div style={styles.div}>
<h1 style={styles.h1}>ToDo</h1>
<List data={newArray} checked={this.handleChecked.bind(this)} remove={this.handleRemove.bind(this)}/>
<form className="form-inline" onSubmit={this.handleSubmit.bind(this)}>
<div className='form-group'>
<input type='text' className='form-control' value={this.state.inputValue} onChange={this.handleChange.bind(this)}/>
</div>
<button className='btn btn-default'>Add#{newArray.length+1}</button>
</form>
<Contoller visible={this.state.visible} control={this.handleControl.bind(this)}/>
</div>
)
}
}
export default App
<file_sep>import React from 'react';
class List extends React.Component{
constructor(){
super();
this.state={
}
}
render(){
let styles={
ul:{listStyle:'none',color:'#040302',fontSize:'20px'},
span:{cursor:'pointer',color:'#f33426',fontSize:'16px'},
input:{marginTop: '10px',marginRight: '10px'}
}
return(
<ul style={styles.ul}>
{this.props.data.map( (item) =>
<li key={item.id} style={{textDecoration:item.completed?'line-through':'none',backgroundColor:item.completed?'#e2e2e2':'white'}}>
<input style={styles.input} type='checkbox' className='pull-left' defaultChecked={item.completed} onChange={() =>this.props.checked(item.id)}/>
{item.text}
<span style={styles.span} className='glyphicon glyphicon-remove pull-right' aria-hidden="true" onClick={()=>this.props.remove(item.id)}></span>
</li>)}
</ul>
)
}
}
export default List
| e8ed6cafde3e4b1d01551dd0d5176165f0d6e8cb | [
"JavaScript"
] | 2 | JavaScript | happyrachel/Todo | 681e1235f48997d26468189aac7e78540e3a08c4 | 8d717312da51a6a888e3ffbc756b02b0cac18be6 | |
refs/heads/master | <file_sep>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 Service.Common.DB;
using Message.Model;
using Service.Common.Log;
using Service.Common;
namespace WinApp.WinForm.Report
{
public partial class FormSaleDetail : Form
{
Sale SaleInfo = new Sale();
public FormSaleDetail(Int32 sald_id)
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
LoadInfo(sald_id);
}
private void LoadInfo(Int32 SaleID)
{
SaleInfo.FindbyPK(SaleID.ToString());
Text = SaleInfo.TradeNo;
lbTradeNo.Text = SaleInfo.TradeNo;
lbOrderNo.Text = SaleInfo.OrderNo;
lbCustomer.Text = SaleInfo.Customer.ToString();
lbStoreHouse_ID.Text = SaleInfo.StoreHouse_ID.ToString();
lbSaleDate.Text = SaleInfo.SaleDate.ToString("yyyy年M月d日 HH:mm:ss");
lbCheckoutTime.Text = SaleInfo.CheckoutTime.ToString("yyyy年M月d日 HH:mm:ss");
tbxCash.Text = SaleInfo.Cash.ToString("f2");
tbxUnionPay.Text = SaleInfo.UnionPay.ToString("f2");
tbxMemCard.Text = SaleInfo.MemCard.ToString("f2");
tbxOtherPayment.Text = SaleInfo.OtherPayment.ToString("f2");
lbTotalAmount.Text = SaleInfo.TotalAmount.ToString("f2");
if (SaleInfo.Account == "0000")
{
lbAccount.Text = "----";
}
else
{
lbAccount.Text = SaleInfo.Account;
}
ReturnMessage rm = new ReturnMessage();
List<string[]> liWhere = new List<string[]>();
liWhere.Add(new string[] { "CardNO = {0}", SaleInfo.Account });
MemberCard mc = new MemberCard();
DataTable dtmc = mc.GetDataSet("SELECT TOP 1 ID FROM MemberCard", liWhere);
string MbID;
if (dtmc.Rows.Count > 0)
{
MbID = dtmc.Rows[0][0].ToString();
mc.FindbyPK(MbID);
lbMbName.Text = mc.MemberName;
}
else
{
lbMbName.Text = "----";
}
liWhere.Clear();
Employee emp = new Employee();
emp.FindbyPK(SaleInfo.Employee_ID.ToString());
lbEmployeeName.Text = emp.Name;
List<string[]> where = new List<string[]>();
List<string[]> order = new List<string[]>();
where.Add(new string[] { "SaleOrder_ID = {0}", SaleID.ToString() });
order.Add(new string[] { "a.Sale_Dtl_Time", "ASC" });
DataTable dt = SaleInfo.GetDataSet("SELECT a.Sale_Detail_ID,b.Product_ID,b.Code,b.Name AS ProductName,convert(numeric(18,2),a.Price) AS PaidIn1,convert(numeric(18,2),b.Price) AS Price,convert(numeric(18,2),a.Quantity) AS Quantity,convert(numeric(18,2),a.Price/b.Price) AS Discount, convert(numeric(18,2),a.Price*a.Quantity) AS PaidInAmount,a.Employee_ID,c.Name AS ServerName FROM Sale_Detail a LEFT JOIN Product b ON b.Product_ID = a.Product_ID LEFT JOIN Employee c ON c.Employee_ID = a.Employee_ID", where, order);
dataGridView1.DataSource = dt;
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
Close();
}
private void btnPrintAgain_Click(object sender, EventArgs e)
{
DataSet ds = new DataSet();
ds.Tables.Add(((DataTable)dataGridView1.DataSource).Copy());
PrintCommon pc = new PrintCommon();
pc.PrintDataSet(ds, SaleInfo);
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
Int32 selectRow = dataGridView1.CurrentCell.RowIndex;
FormChangeWaiter fcw = new FormChangeWaiter(Convert.ToInt32(dataGridView1.Rows[selectRow].Cells["Sale_Detail_ID"].Value));
if (fcw.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("修改成功!");
LoadInfo(SaleInfo.Sale_ID);
}
dataGridView1.CurrentCell = dataGridView1[0, selectRow];
}
private void btnSaveChange_Click(object sender, EventArgs e)
{
decimal TotalAmount = Convert.ToDecimal(tbxCash.Text) + Convert.ToDecimal(tbxUnionPay.Text) + Convert.ToDecimal(tbxMemCard.Text) + Convert.ToDecimal(tbxOtherPayment.Text);
if (TotalAmount == Convert.ToDecimal(lbTotalAmount.Text))
{
if (Convert.ToDecimal(tbxMemCard.Text)!=SaleInfo.MemCard)
{
decimal Adjustment = Convert.ToDecimal(tbxMemCard.Text) - SaleInfo.MemCard;
string CardNumber = SaleInfo.Account;
if (CardNumber == "0000")
{
FormMemCard fmc = new FormMemCard(Adjustment);
if (fmc.ShowDialog() == DialogResult.OK && fmc.PaymentCard == Adjustment)
{
CardNumber = fmc.CardNo;
}
else
{
MessageBox.Show("会员卡信息操作失败,未保存!");
return;
}
}
ReturnMessage rm = new ReturnMessage();
rm = MemCardOper.MemCardHandle(CardNumber, Adjustment, SaleInfo.TradeNo);
SaleInfo.Account = CardNumber;
if (!rm.IsSucessed)
{
MessageBox.Show("操作失败," + rm.Message);
return;
}
}
SaleInfo.Cash = Convert.ToDecimal(tbxCash.Text);
SaleInfo.UnionPay = Convert.ToDecimal(tbxUnionPay.Text);
SaleInfo.MemCard = Convert.ToDecimal(tbxMemCard.Text);
SaleInfo.OtherPayment = Convert.ToDecimal(tbxOtherPayment.Text);
SaleInfo.Update();
MessageBox.Show("保存成功!");
Close();
}
else
{
MessageBox.Show("金额填写不正确!");
}
}
private void tbxCash_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void tbxUnionPay_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void tbxMemCard_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void tbxOtherPayment_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
}
}<file_sep>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 Service.Common;
using Message.Model;
namespace WinApp.WinForm.Report
{
public partial class FormChangeWaiter : Form
{
Sale_Detail DetailInfo = new Sale_Detail();
public FormChangeWaiter(Int32 Sale_Detail_ID)
{
InitializeComponent();
ControlCommon.BindEmployee(cbWaiter);
DetailInfo.FindbyPK(Sale_Detail_ID.ToString());
cbWaiter.SelectedValue = DetailInfo.Employee_ID;
}
private void btnSave_Click(object sender, EventArgs e)
{
DetailInfo.Employee_ID = Convert.ToInt32(cbWaiter.SelectedValue);
DetailInfo.Update();
DialogResult = DialogResult.OK;
}
}
}
<file_sep>using System;
using Service.Common.Entity;
using System.Collections.Generic;
using System.Data;
namespace Message.Model
{
/// <summary>
/// Sale:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("Sale")]
public partial class Sale : EntityBase<Sale>
{
public Sale()
{ }
#region Model
private int _sale_id;
private DateTime _saledate;
private string _tradeno;
private string _orderNo;
private int _dept_id;
private int _employee_id;
private int _storehouse_id;
private string _address;
private string _account;
private string _gatheringway;
private int _customer;
private decimal _totalAmount;
private decimal _memCard;
private decimal _cash;
private decimal unionPay;
private decimal _otherPayment;
private DateTime _checkoutTime;
private int _state = 1;
/// <summary>
///
/// </summary>
[PrimaryKey("Sale_ID", IsAuto = true)]
public int Sale_ID
{
set { _sale_id = value; }
get { return _sale_id; }
}
/// <summary>
///
/// </summary>
[Property]
public DateTime SaleDate
{
set { _saledate = value; }
get { return _saledate; }
}
/// <summary>
/// 单号
/// </summary>
[Property]
public string TradeNo
{
set { _tradeno = value; }
get { return _tradeno; }
}
/// <summary>
/// 单号
/// </summary>
[Property]
public string OrderNo
{
get { return _orderNo; }
set { _orderNo = value; }
}
/// <summary>
/// 部门ID
/// </summary>
[Property]
public int Dept_ID
{
set { _dept_id = value; }
get { return _dept_id; }
}
/// <summary>
/// 操作员
/// </summary>
[Property]
public int Employee_ID
{
set { _employee_id = value; }
get { return _employee_id; }
}
/// <summary>
/// 房间号
/// </summary>
[Property]
public int StoreHouse_ID
{
set { _storehouse_id = value; }
get { return _storehouse_id; }
}
/// <summary>
/// 地址
/// </summary>
[Property]
public string Address
{
set { _address = value; }
get { return _address; }
}
/// <summary>
/// 会员卡号
/// </summary>
[Property]
public string Account
{
set { _account = value; }
get { return _account; }
}
/// <summary>
/// 采集方式
/// </summary>
[Property]
public string GatheringWay
{
set { _gatheringway = value; }
get { return _gatheringway; }
}
/// <summary>
/// 金额
/// </summary>
[Property]
public decimal TotalAmount
{
get { return _totalAmount; }
set { _totalAmount = value; }
}
/// <summary>
/// 会员卡支付额
/// </summary>
[Property]
public decimal MemCard
{
get { return _memCard; }
set { _memCard = value; }
}
/// <summary>
/// 现金支付额
/// </summary>
[Property]
public decimal Cash
{
get { return _cash; }
set { _cash = value; }
}
/// <summary>
/// 银联卡
/// </summary>
[Property]
public decimal UnionPay
{
get { return unionPay; }
set { unionPay = value; }
}
/// <summary>
/// 其他支付方式
/// </summary>
[Property]
public decimal OtherPayment
{
get { return _otherPayment; }
set { _otherPayment = value; }
}
/// <summary>
/// 顾客手牌号
/// </summary>
[Property]
public int Customer
{
set { _customer = value; }
get { return _customer; }
}
/// <summary>
/// 结帐时间
/// </summary>
[Property]
public DateTime CheckoutTime
{
get { return _checkoutTime; }
set { _checkoutTime = value; }
}
/// <summary>
/// 状态 0:已结帐,1:进行中
/// </summary>
[Property]
public int State
{
set { _state = value; }
get { return _state; }
}
#endregion Model
/// <summary>
/// 生成单号
/// </summary>
/// <returns></returns>
public string getTradCode()
{
List<string[]> where = new List<string[]>();
List<string[]> order = new List<string[]>();
string Today = DateTime.Now.ToString("yyyyMMdd");
where.Add(new string[] { "SaleDate >= {0}", Today });
order.Add(new string[] { "TradeNo", "DESC" });
DataTable dt = this.GetDataSet("SELECT TradeNo FROM Sale", where, order);
if (dt.Rows.Count > 0)
{
return Today + (Convert.ToInt32(dt.Rows[0][0].ToString().Substring(8, 3)) + 1).ToString("000");
}
else
{
return Today + "001";
}
}
}
public class PaymentInfo
{
private decimal totalAmount = 0;
private decimal memCard = 0;
private decimal cash = 0;
private decimal unionPay = 0;
private decimal otherPayment = 0;
private string account = "0000";
/// <summary>
/// 全单总计金额
/// </summary>
public decimal TotalAmount
{
get { return totalAmount; }
set { totalAmount = value; }
}
/// <summary>
/// 会员卡支付额
/// </summary>
public decimal MemCard
{
get { return memCard; }
set { memCard = value; }
}
/// <summary>
/// 现金
/// </summary>
public decimal Cash
{
get { return cash; }
set { cash = value; }
}
/// <summary>
/// 银联
/// </summary>
public decimal UnionPay
{
get { return unionPay; }
set { unionPay = value; }
}
/// <summary>
/// 其他支付方式
/// </summary>
public decimal OtherPayment
{
get { return otherPayment; }
set { otherPayment = value; }
}
/// <summary>
/// 会员卡号
/// </summary>
public string Account
{
get { return account; }
set { account = value; }
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// ProductUnit:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("ProductUnit")]
public partial class ProductUnit : EntityBase<ProductUnit>
{
public ProductUnit()
{}
#region Model
private int _productunit_id;
private string _name;
private int _employee_id;
private DateTime _createdate= DateTime.Now;
private string _remark;
/// <summary>
///
/// </summary>
[PrimaryKey("ProductUnit_ID", IsAuto = true)]
public int ProductUnit_ID
{
set{ _productunit_id=value;}
get{return _productunit_id;}
}
/// <summary>
/// 单位名称
/// </summary>
[Property]
public string Name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
///
/// </summary>
[Property]
public int Employee_ID
{
set{ _employee_id=value;}
get{return _employee_id;}
}
/// <summary>
/// 创建时间
/// </summary>
[Property]
public DateTime CreateDate
{
set{ _createdate=value;}
get{return _createdate;}
}
/// <summary>
///
/// </summary>
[Property]
public string Remark
{
set{ _remark=value;}
get{return _remark;}
}
#endregion Model
}
}
<file_sep>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.Security.Principal;
using System.Threading;
using Message.Model;
using WinApp.Controls;
using WinApp.WinForm.Report;
using WinApp.WinForm.Admin;
using Service.Common;
namespace WinApp.WinForm
{
public partial class MainForm : Form
{
const int AW_VER_NEGATIVE = 0x0008;
const int AW_CENTER = 0x0010;
const int AW_HIDE = 0x10000;
Sale sale = new Sale();
public MainForm()
{
InitializeComponent();
}
private void btnBilling_Click(object sender, EventArgs e)
{
OpenSale(0);
}
private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
{
if (MessageBox.Show("确定要退出程序吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.No)
{
e.Cancel = true;
}
else
{
AnimateWindow(this.Handle, 1000, AW_CENTER | AW_HIDE | AW_VER_NEGATIVE);
System.Environment.Exit(0);
}
}
private void MainForm_Load(object sender, EventArgs e)
{
FormLogin frmLogin = new FormLogin();
DialogResult dr = frmLogin.ShowDialog();
}
private void btnExit_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要退出程序吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
{
AnimateWindow(this.Handle, 1000, AW_CENTER | AW_HIDE | AW_VER_NEGATIVE);
System.Environment.Exit(0);
}
}
private void BindListView()
{
flowLayoutPanel1.Controls.Clear();
List<string[]> where = new List<string[]>();
List<string[]> order = new List<string[]>();
where.Add(new string[] { "State = {0}", "1" });
order.Add(new string[] { "Customer", "ASC" });
DataTable dt = sale.GetDataSet("SELECT * FROM Sale", where, order);
for (int i = 0; i < dt.Rows.Count; i++)
{
UCCustomer btn = new UCCustomer();
btn.Text = dt.Rows[i]["Customer"].ToString();
btn.SaleID = Convert.ToInt32(dt.Rows[i]["Sale_ID"].ToString());
btn.CustemerNo = dt.Rows[i]["Customer"].ToString();
btn.StoreHouse_ID = dt.Rows[i]["StoreHouse_ID"].ToString();
btn.Employee_ID = dt.Rows[i]["Employee_ID"].ToString();
btn.SaleDate = Convert.ToDateTime(dt.Rows[i]["SaleDate"]);
btn.Margin = new Padding(8);
btn.MyEvent += new EventEntrust(btn_MyEvent);
flowLayoutPanel1.Controls.Add(btn);
}
}
void btn_MyEvent(object sender, int e)
{
OpenSale(e);
}
private void OpenSale(Int32 SaleID)
{
FormSale fs1 = new FormSale(this, SaleID);
fs1.Show();
this.Hide();
}
private void MainForm_VisibleChanged(object sender, EventArgs e)
{
BindListView();
lbCurDate.Text = DateTime.Now.ToString("yyyy年M月d日 ") + DateTimeCommon.getWeek(Convert.ToInt32(DateTime.Now.DayOfWeek)) + " 农历:" + DateTimeCommon.GetChineseDate(DateTime.Now);
Employee emp = new Employee();
emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
lbCurUser.Text = emp.Name;
timer1.Start();
if (emp.Dept_ID != 0)
{
btnMaintain.Enabled = false;
btnReportForm.Enabled = false;
}
else
{
btnMaintain.Enabled = true;
btnReportForm.Enabled = true;
}
}
private void btnStatistics_Click(object sender, EventArgs e)
{
FormSaleList fsl = new FormSaleList();
fsl.ShowDialog();
}
private void btnMaintain_Click(object sender, EventArgs e)
{
FormAdmin fa = new FormAdmin();
fa.ShowDialog();
}
private void btnSetting_Click(object sender, EventArgs e)
{
FormSetting fst = new FormSetting();
fst.ShowDialog();
}
private void timer1_Tick(object sender, EventArgs e)
{
lbCurrentTime.Text = DateTime.Now.ToString("HH:mm:ss:ff");
}
private void btnMembershipCard_Click(object sender, EventArgs e)
{
FormMembershipCard fmc = new FormMembershipCard();
fmc.ShowDialog();
}
private void btnBackup_Click(object sender, EventArgs e)
{
if (MessageBox.Show("要开始备份数据吗?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
{
string strPath = Environment.CurrentDirectory + "\\Backup\\";
FormDataBackup fdb = new FormDataBackup(strPath);
if (fdb.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("备份成功!");
System.Diagnostics.Process.Start("Explorer.exe", strPath);
}
else
{
MessageBox.Show("备份失败!" + fdb.Rm.Message);
}
}
}
private void btnReLogin_Click(object sender, EventArgs e)
{
if (MessageBox.Show("要退出当前帐号并重新登录吗?", "重新登录", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
{
FormLogin fl = new FormLogin();
Hide();
if (fl.ShowDialog() == DialogResult.OK)
{
Show();
}
}
}
private void btnReportForm_Click(object sender, EventArgs e)
{
FormReport fr = new FormReport();
fr.ShowDialog();
}
private void btnShift_Click(object sender, EventArgs e)
{
FormShift fs = new FormShift(0);
fs.ShowDialog();
}
private void button1_Click(object sender, EventArgs e)
{
test ts = new test();
ts.ShowDialog();
}
[System.Runtime.InteropServices.DllImport("user32")]
private static extern bool AnimateWindow(IntPtr hwnd, int dwTime, int dwFlags);
}
}
<file_sep>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 Service.Common;
using Message.Model;
namespace WinApp.WinForm.Admin
{
public partial class FormAddDiscount : Form
{
public FormAddDiscount()
{
InitializeComponent();
}
private void tbxDiscountRate_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void btnSave_Click(object sender, EventArgs e)
{
if (tbxDisName.Text == "")
{
MessageBox.Show("请填写名称!");
tbxDisName.Focus();
return;
}
if (tbxDiscountRate.Text == "")
{
MessageBox.Show("请填写折扣!");
tbxDiscountRate.Focus();
return;
}
Discount dsc = new Discount();
dsc.DisName = tbxDisName.Text;
dsc.DiscountRate = Convert.ToDecimal(tbxDiscountRate.Text);
if (rbAvailable.Checked)
{
dsc.Available = true;
}
else
{
dsc.Available = false;
}
dsc.Remark = "";
dsc.Insert();
MessageBox.Show("保存成功!");
Close();
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Message.Model;
using System.Data;
namespace Service.Common
{
public static class ControlCommon
{
/// <summary>
/// 绑定折扣
/// </summary>
/// <param name="cb"></param>
public static void BindDiscount(ComboBox cb)
{
Discount dsc = new Discount();
List<string[]> liWhere = new List<string[]>();
List<string[]> liOrder = new List<string[]>();
liWhere.Add(new string[] { "Available = '{0}'", "True" });
liOrder.Add(new string[] { "DiscountRate", "DESC" });
DataTable dt = dsc.GetDataSet("SELECT DiscountRate, DisName FROM Discount", liWhere, liOrder);
cb.DisplayMember = "DisName";
cb.ValueMember = "DiscountRate";
cb.DataSource = dt;
cb.SelectedIndex = 0;
}
/// <summary>
/// 绑定会员卡类型
/// </summary>
/// <param name="cb"></param>
public static void BindCardType(ComboBox cb)
{
CardType ct = new CardType();
List<string[]> liWhere = new List<string[]>();
List<string[]> liOrder = new List<string[]>();
liWhere.Add(new string[] { "Available = '{0}'", "1" });
liOrder.Add(new string[] { "ID", "ASC" });
DataTable dt = ct.GetDataSet("SELECT ID, TypeName FROM CardType", liWhere, liOrder);
cb.DisplayMember = "TypeName";
cb.ValueMember = "ID";
cb.DataSource = dt;
cb.SelectedIndex = 0;
}
/// <summary>
/// 绑定人员
/// </summary>
/// <param name="cb"></param>
public static void BindEmployee(ComboBox cb)
{
Employee emp = new Employee();
List<string[]> liWhere = new List<string[]>();
List<string[]> liOrder = new List<string[]>();
liWhere.Add(new string[] { "1 = '{0}'", "1" });
liOrder.Add(new string[] { "Employee_ID", "DESC" });
DataTable dt = emp.GetDataSet("SELECT Employee_ID, Name FROM Employee", liWhere, liOrder);
cb.DisplayMember = "Name";
cb.ValueMember = "Employee_ID";
cb.DataSource = dt;
}
/// <summary>
/// 绑定商品名
/// </summary>
/// <param name="cb"></param>
public static void BindProduct(ComboBox cb)
{
Product emp = new Product();
List<string[]> liWhere = new List<string[]>();
List<string[]> liOrder = new List<string[]>();
liWhere.Add(new string[] { "1 = '{0}'", "1" });
liOrder.Add(new string[] { "Product_ID", "DESC" });
DataTable dt = emp.GetDataSet("SELECT Product_ID, Name FROM Product", liWhere, liOrder);
cb.DisplayMember = "Name";
cb.ValueMember = "Product_ID";
cb.DataSource = dt;
}
/// <summary>
/// 正整数和负整数
/// </summary>
/// <param name="tb"></param>
/// <param name="e"></param>
public static void VerDigitalHL(object sender, KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8 && e.KeyChar != (char)45)
{
e.Handled = true;
}
else
{
if (e.KeyChar == (char)45)
{
if (((TextBox)sender).Text.StartsWith("-"))
{
e.Handled = true;
}
}
}
}
/// <summary>
/// 只能输入正整数
/// </summary>
/// <param name="e"></param>
public static void VerDigital(KeyPressEventArgs e)
{
if (!(Char.IsNumber(e.KeyChar)) && e.KeyChar != (char)13 && e.KeyChar != (char)8)
{
e.Handled = true;
}
}
/// <summary>
/// 只能输入两位小数的数字
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
public static void VerDecimal(object sender, KeyPressEventArgs e)
{
//判断按键是不是要输入的类型。
if (((int)e.KeyChar < 48 || (int)e.KeyChar > 57) && (int)e.KeyChar != 8 && (int)e.KeyChar != 46)
{
e.Handled = true; //小数点的处理。
}
//else
//{
// if ((int)e.KeyChar != 8)
// {
// if (((TextBox)sender).Text.Contains("."))
// {
// string[] SectionText = ((TextBox)sender).Text.Split(new char[] { '.' });
// if (SectionText[1].Length > 1)
// {
// e.Handled = true;
// }
// }
// }
//}
if ((int)e.KeyChar == 46) //小数点
{
if (((TextBox)sender).Text.Length <= 0)
{ e.Handled = true; } //小数点不能在第一位
else
{
float f;
float oldf;
bool b1 = false, b2 = false;
b1 = float.TryParse(((TextBox)sender).Text, out oldf);
b2 = float.TryParse(((TextBox)sender).Text + e.KeyChar.ToString(), out f);
if (b2 == false)
{
if (b1 == true)
{ e.Handled = true; }
else
{ e.Handled = false; }
}
}
}
}
}
}
<file_sep>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 Service.Common.Data;
using Message.Model;
using Service.Common;
using System.Threading;
namespace WinApp.WinForm
{
public partial class FormSelect : Form
{
Product emp = new Product();
SaleDtlInfo saleInfo = new SaleDtlInfo();
public SaleDtlInfo SaleInfo
{
get { return saleInfo; }
set { saleInfo = value; }
}
public FormSelect()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
ControlCommon.BindDiscount(cbDiscount);
BindProData();
ControlCommon.BindEmployee(cbServer);
DataTable dt = (DataTable)cbServer.DataSource;
DataRow dr = dt.NewRow();
dr["Employee_ID"] = 0;
dr["Name"] = "<—请选择—>";
dt.Rows.InsertAt(dr, 0);
cbServer.SelectedIndex = 0;
}
private void BindProData()
{
List<string[]> where = new List<string[]>();
if (!string.IsNullOrEmpty(tbxCode.Text.Trim()))
{
where.Add(new string[] { "Code LIKE '%' + {0} + '%'", tbxCode.Text.Trim() });
}
if (!string.IsNullOrEmpty(tbxPinYin.Text.Trim()))
{
where.Add(new string[] { "(spell LIKE '%' + {0} + '%' OR s_spell LIKE '%' + {0} + '%')", tbxPinYin.Text.Trim() });
}
DataTable dt = emp.GetDataSet("SELECT * FROM Product", where);
dataGridView1.DataSource = dt;
}
private void tbxNo_TextChanged(object sender, EventArgs e)
{
BindProData();
CalcAmount();
}
private void tbxPinYin_TextChanged(object sender, EventArgs e)
{
BindProData();
CalcAmount();
}
private void cbDiscount_SelectionChangeCommitted(object sender, EventArgs e)
{
CalcAmount();
}
private void dataGridView1_SelectionChanged(object sender, EventArgs e)
{
CalcAmount();
}
private void CalcAmount()
{
if (((DataTable)(dataGridView1.DataSource)).Rows.Count > 0 && tbxQty.Text.Length > 0 && tbxQty.Text != "-")
{
decimal Price = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Price"].Value);
decimal Amount = Price * Convert.ToDecimal(cbDiscount.SelectedValue) * Convert.ToInt32(tbxQty.Text);
lbAmount.Text = Math.Round(Amount, 2).ToString();
//lbAmount.Text = ((Int32)((double)Amount + 0.5)).ToString();
}
else
{
lbAmount.Text = "--";
}
}
private void tbxQty_TextChanged(object sender, EventArgs e)
{
CalcAmount();
}
private void tbxQty_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDigitalHL(sender, e);
}
private void btnCancel_Click(object sender, EventArgs e)
{
this.DialogResult = DialogResult.Cancel;
this.Close();
}
private void btnDetermine_Click(object sender, EventArgs e)
{
if (cbServer.SelectedValue.ToString() != "0")
{
if (dataGridView1.Rows.Count > 0 && lbAmount.Text != "--")
{
if (Convert.ToDecimal(lbAmount.Text) >= 0)
{
SetSaleInfo();
}
else
{
if (new FormBackPassword().ShowDialog() == DialogResult.OK)
{
SetSaleInfo();
}
}
}
}
else
{
MessageBox.Show("请选择服务人员!");
}
}
private void SetSaleInfo()
{
SaleInfo.ProID = Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["ProID"].Value);
SaleInfo.ProCode = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Code"].Value.ToString();
SaleInfo.ProName = dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["ProName"].Value.ToString();
SaleInfo.Price = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Price"].Value);
SaleInfo.PaidIn = Convert.ToDecimal(lbAmount.Text);
SaleInfo.Quanity = Convert.ToDecimal(tbxQty.Text);
SaleInfo.Discount = Convert.ToDecimal(cbDiscount.SelectedValue);
SaleInfo.Total = Convert.ToDecimal(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Price"].Value) * Convert.ToDecimal(cbDiscount.SelectedValue);
SaleInfo.ServerID = Convert.ToInt32(cbServer.SelectedValue);
saleInfo.Sale_Dtl_Time = DateTime.Now;
saleInfo.Server = cbServer.Text;
this.DialogResult = DialogResult.OK;
}
private void tbxServicePerson_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDigital(e);
}
}
}
<file_sep>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 Message.Model;
using Service.Common;
using System.Threading;
namespace WinApp.WinForm.Report
{
public partial class FormReport : Form
{
Sale SaleInfo = new Sale();
public FormReport()
{
InitializeComponent();
dgvSummary.AutoGenerateColumns = false;
dgvDetail.AutoGenerateColumns = false;
}
private void FormReport_Load(object sender, EventArgs e)
{
updgvSummary.DataSetSql = "SELECT * FROM v_SaleList";
updgvSummary.LiWhere.Add(new string[] { "State = {0}", "0" });
updgvSummary.LiOrder.Add(new string[] { "Sale_ID", "DESC" });
dgvSummary.DataSource = updgvSummary.GetDataTable();
updgvSummary.PageEvent += new WinApp.Controls.PageEntrust(updgvSummary_PageEvent);
updgvDetail.PageEvent += new WinApp.Controls.PageEntrust(updgvDetail_PageEvent);
GetTotalAmount();
ControlCommon.BindEmployee(cbServer);
DataTable dt = (DataTable)cbServer.DataSource;
DataRow dr = dt.NewRow();
dr["Employee_ID"] = 0;
dr["Name"] = "<—全部—>";
dt.Rows.InsertAt(dr, 0);
cbServer.SelectedIndex = 0;
ControlCommon.BindProduct(cbProName);
DataTable dt1 = (DataTable)cbProName.DataSource;
DataRow dr1 = dt1.NewRow();
dr1["Product_ID"] = 0;
dr1["Name"] = "<—全部—>";
dt1.Rows.InsertAt(dr1, 0);
cbProName.SelectedIndex = 0;
}
void updgvSummary_PageEvent()
{
dgvSummary.DataSource = updgvSummary.GetDataTable();
}
private void btnSearch_Click(object sender, EventArgs e)
{
updgvSummary.LiWhere.Clear();
updgvSummary.LiWhere.Add(new string[] { "State = {0}", "0" });
if (dtpFrom.Checked)
{
updgvSummary.LiWhere.Add(new string[] { "CheckoutTime > {0}", dtpFrom.Value.ToShortDateString() });
}
if (dtpTo.Checked)
{
updgvSummary.LiWhere.Add(new string[] { "CheckoutTime < {0}", dtpTo.Value.AddDays(1).ToShortDateString() });
}
if (tbxTradCode.Text.Trim() != "")
{
updgvSummary.LiWhere.Add(new string[] { "TradeNo LIKE '%' + {0} + '%'", tbxTradCode.Text.Trim() });
}
if (tbxOrderNo.Text.Trim() != "")
{
updgvSummary.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNo.Text.Trim() });
}
updgvSummary.CurPage = 1;
dgvSummary.DataSource = updgvSummary.GetDataTable();
GetTotalAmount();
}
private void GetTotalAmount()
{
DataTable dt = SaleInfo.GetDataSet("SELECT SUM(TotalAmount) FROM v_SaleList", updgvSummary.LiWhere);
if (dt.Rows[0][0] != System.DBNull.Value)
{
lbTotalAmount.Text = (Convert.ToDecimal(dt.Rows[0][0])).ToString("f2") + " 元";
}
else
{
lbTotalAmount.Text = "0 元";
}
}
private void btnExport_Click(object sender, EventArgs e)
{
FormExport fe = new FormExport(updgvSummary);
fe.ShowDialog();
}
private void tabPage2_Enter(object sender, EventArgs e)
{
updgvDetail.LiOrder.Clear();
updgvDetail.LiWhere.Clear();
updgvDetail.LiOrder.Add(new string[] { "Sale_Detail_ID", "DESC" });
updgvDetail.LiWhere.Add(new string[] { "State = {0}", "0" });
updgvDetail.DataSetSql = "SELECT * FROM v_SaleDetailList";
dgvDetail.DataSource = updgvDetail.GetDataTable();
GetDtlTotalAmount();
}
void updgvDetail_PageEvent()
{
dgvDetail.DataSource = updgvDetail.GetDataTable();
}
private void GetDtlTotalAmount()
{
DataTable dt = SaleInfo.GetDataSet("SELECT SUM(Total),SUM(Commission) FROM v_SaleDetailList", updgvDetail.LiWhere);
if (dt.Rows[0][0] != System.DBNull.Value)
{
lbDtlTotalAmount.Text = (Convert.ToDecimal(dt.Rows[0][0])).ToString("f2") + " 元";
lbCommission.Text = (Convert.ToDecimal(dt.Rows[0][1])).ToString("f2") + " 元";
}
else
{
lbDtlTotalAmount.Text = "0 元";
lbCommission.Text = "0 元";
}
}
private void btnDtlSearch_Click(object sender, EventArgs e)
{
updgvDetail.LiWhere.Clear();
updgvDetail.LiWhere.Add(new string[] { "State = {0}", "0" });
if (dtpDtlFrom.Checked)
{
updgvDetail.LiWhere.Add(new string[] { "CheckoutTime > {0}", dtpDtlFrom.Value.ToShortDateString() });
}
if (dtpDtlTo.Checked)
{
updgvDetail.LiWhere.Add(new string[] { "CheckoutTime < {0}", dtpDtlTo.Value.AddDays(1).ToShortDateString() });
}
if (tbxDtlTradCode.Text != "")
{
updgvDetail.LiWhere.Add(new string[] { "TradeNo LIKE '%' + {0} + '%'", tbxDtlTradCode.Text.Trim() });
}
if (cbProName.SelectedValue.ToString() != "0")
{
updgvDetail.LiWhere.Add(new string[] { "Product_ID ={0}", cbProName.SelectedValue.ToString() });
}
if (cbServer.SelectedValue.ToString() != "0")
{
updgvDetail.LiWhere.Add(new string[] { "Employee_ID = {0}", cbServer.SelectedValue.ToString() });
}
if (tbxOrderNoDtl.Text.Trim() != "")
{
updgvDetail.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNoDtl.Text.Trim() });
}
updgvDetail.CurPage = 1;
dgvDetail.DataSource = updgvDetail.GetDataTable();
GetDtlTotalAmount();
}
private void btnDtlExport_Click(object sender, EventArgs e)
{
FormExport fe = new FormExport(updgvDetail);
fe.ShowDialog();
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// CardType:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("CardType")]
public partial class CardType : EntityBase<CardType>
{
public CardType()
{}
#region Model
private int _id;
private int _vailable;
private string _typename;
private decimal _discount;
/// <summary>
///
/// </summary>
[PrimaryKey("ID", IsAuto = true)]
public int ID
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
[Property]
public int Available
{
set { _vailable = value; }
get { return _vailable; }
}
/// <summary>
/// 类型名称
/// </summary>
[Property]
public string TypeName
{
set{ _typename=value;}
get{return _typename;}
}
/// <summary>
/// 折扣
/// </summary>
[Property]
public decimal Discount
{
set{ _discount=value;}
get{return _discount;}
}
#endregion Model
}
}
<file_sep>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 Message.Model;
using Service.Common;
namespace WinApp.WinForm.Admin
{
public partial class FormRecharge : Form
{
MemberCard mc = new MemberCard();
public FormRecharge(Int32 cardId)
{
InitializeComponent();
mc.FindbyPK(cardId.ToString());
}
private void btnDetermine_Click(object sender, EventArgs e)
{
if (tbxRechargeAmount.Text.Trim() != "")
{
if (new FormBackPassword().ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show("您确定要向卡号:" + mc.CardNO + " 姓名:" + mc.MemberName + " 的用户充值 " + tbxRechargeAmount.Text + " 元吗?", "充值确认", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
mc.Balance += Convert.ToInt32(tbxRechargeAmount.Text);
mc.Update();
ConsumptionRecords cr = new ConsumptionRecords();
cr.CardID = mc.ID;
cr.RecType = 1;
cr.TradeNo = "-----------";
cr.OpeTime = DateTime.Now;
cr.Amount = Convert.ToInt32(tbxRechargeAmount.Text);
cr.Insert();
MessageBox.Show("充值成功!");
DialogResult = DialogResult.OK;
}
}
}
else
{
MessageBox.Show("请填写充值金额!");
}
}
private void tbxRechargeAmount_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDigitalHL(sender, e);
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// ProductSpec:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("ProductSpec")]
public partial class ProductSpec : EntityBase<ProductSpec>
{
public ProductSpec()
{}
#region Model
private int _productspec_id;
private string _name;
private int _employee_id;
private DateTime _createdate= DateTime.Now;
private string _remark;
/// <summary>
///
/// </summary>
[PrimaryKey("ProductSpec_ID", IsAuto = true)]
public int ProductSpec_ID
{
set{ _productspec_id=value;}
get{return _productspec_id;}
}
/// <summary>
///
/// </summary>
[Property]
public string Name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
///
/// </summary>
[Property]
public int Employee_ID
{
set{ _employee_id=value;}
get{return _employee_id;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime CreateDate
{
set{ _createdate=value;}
get{return _createdate;}
}
/// <summary>
///
/// </summary>
[Property]
public string Remark
{
set{ _remark=value;}
get{return _remark;}
}
#endregion Model
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// Employee:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("Employee")]
public partial class Employee : EntityBase<Employee>
{
public Employee()
{}
#region Model
private Int32 _employee_id;
private string _username;
private string _password;
private int _dept_id;
private string _name;
private string _duty;
private string _gender;
private DateTime _birthdate;
private DateTime _hiredate;
private DateTime _lastlogin;
private string _identitycard;
private string _address;
private string _phone;
private string _email;
private string _remark;
/// <summary>
///
/// </summary>
[PrimaryKey("Employee_ID", IsAuto = true)]
public Int32 Employee_ID
{
set{ _employee_id=value;}
get{return _employee_id;}
}
/// <summary>
///
/// </summary>
[Property]
public string UserName
{
set{ _username=value;}
get{return _username;}
}
/// <summary>
///
/// </summary>
[Property]
public string PassWord
{
set{ _password=value;}
get{return _password;}
}
/// <summary>
///
/// </summary>
[Property]
public int Dept_ID
{
set{ _dept_id=value;}
get{return _dept_id;}
}
/// <summary>
///
/// </summary>
[Property]
public string Name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
///
/// </summary>
[Property]
public string Duty
{
set{ _duty=value;}
get{return _duty;}
}
/// <summary>
///
/// </summary>
[Property]
public string Gender
{
set{ _gender=value;}
get{return _gender;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime BirthDate
{
set{ _birthdate=value;}
get{return _birthdate;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime HireDate
{
set{ _hiredate=value;}
get{return _hiredate;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime LastLogin
{
set { _lastlogin = value; }
get { return _lastlogin; }
}
/// <summary>
///
/// </summary>
[Property]
public string IdentityCard
{
set{ _identitycard=value;}
get{return _identitycard;}
}
/// <summary>
///
/// </summary>
[Property]
public string Address
{
set{ _address=value;}
get{return _address;}
}
/// <summary>
///
/// </summary>
[Property]
public string Phone
{
set{ _phone=value;}
get{return _phone;}
}
/// <summary>
///
/// </summary>
[Property]
public string Email
{
set{ _email=value;}
get{return _email;}
}
/// <summary>
///
/// </summary>
[Property]
public string Remark
{
set { _remark = value; }
get { return _remark; }
}
#endregion Model
}
}
<file_sep>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.Threading;
using Message.Model;
using Service.Common;
using WinApp.Controls;
namespace WinApp.WinForm.Report
{
public partial class FormExport : Form
{
Sale SaleInfo = new Sale();
Sale_Detail sdInfo = new Sale_Detail();
UCPage ucpage = new UCPage();
public FormExport(UCPage UCPage)
{
Control.CheckForIllegalCrossThreadCalls = false;
InitializeComponent();
ee.ExportEvent += new ExcelExportEntrust(ee_ExportEvent);
ExportSummary(UCPage);
}
ExcelExport ee = new ExcelExport();
private void ExportSummary(UCPage ucPage)
{
ucpage = ucPage;
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
backgroundWorker1.RunWorkerAsync();
}
else
{
Close();
}
}
void ee_ExportEvent(int Schedule)
{
backgroundWorker1.ReportProgress(Schedule);
progressBar1.Value = Schedule;
lbSchedule.Text = "正在导出,已完成 " + Schedule + "%。。。。。。";
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt = SaleInfo.GetDataSet(ucpage.DataSetSql, ucpage.LiWhere, ucpage.LiOrder);
if (dt.Rows.Count > 65000)
{
MessageBox.Show("汇总统计表的行数已经超过Excel文件的容量(65536行),不能导出,请缩小统计范围!");
return;
}
ds.Tables.Add(dt.Copy());
Employee emp = new Employee();
emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
string PeriodTime = "";
List<string[]> liWhere = ucpage.LiWhere;
for (int i = 0; i < liWhere.Count; i++)
{
if (liWhere[i][0] == "CheckoutTime > {0}")
{
PeriodTime += Convert.ToDateTime(liWhere[i][1]).ToString("yyyy-M-d") + "~";
}
if (liWhere[i][0] == "CheckoutTime < {0}")
{
PeriodTime += Convert.ToDateTime(liWhere[i][1]).AddDays(-1).ToString("yyyy-M-d");
}
}
DataTable dtInfo = new DataTable();
dtInfo.Columns.Add("name", typeof(string));
ds.Tables.Add(dtInfo);
DataRow row = ds.Tables[1].NewRow();
row[0] = emp.Name;
dtInfo.Rows.InsertAt(row, 0);
DataRow row1 = ds.Tables[1].NewRow();
row1["name"] = DateTime.Now.ToString("yyyy-M-d HH:mm:ss");
dtInfo.Rows.InsertAt(row1, 0);
DataRow row2 = ds.Tables[1].NewRow();
row2["name"] = PeriodTime;
dtInfo.Rows.InsertAt(row2, 0);
if (ucpage.Name == "updgvSummary")
{
ee.Export(ds, "kqzdhz", folderBrowserDialog1.SelectedPath + "\\销售汇总表");
}
else
{
ee.Export(ds, "kqzdmx", folderBrowserDialog1.SelectedPath + "\\销售明细表");
}
System.Diagnostics.Process.Start("Explorer.exe", folderBrowserDialog1.SelectedPath);
DialogResult = DialogResult.OK;
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// Sale_Detail:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("Sale_Detail")]
public partial class Sale_Detail : EntityBase<Sale_Detail>
{
public Sale_Detail()
{}
#region Model
private int _sale_detail_ID_id;
private int _product_id;
private int _saleorder_id;
private decimal _quantity;
private decimal _price;
private decimal _discount;
private int _employee_id;
private DateTime sale_Dtl_Time;
/// <summary>
///
/// </summary>
[PrimaryKey("Sale_Detail_ID", IsAuto = true)]
public int Sale_Detail_ID
{
set { _sale_detail_ID_id = value; }
get { return _sale_detail_ID_id; }
}
/// <summary>
///
/// </summary>
[Property]
public int Product_ID
{
set{ _product_id=value;}
get{return _product_id;}
}
/// <summary>
///
/// </summary>
[Property]
public int SaleOrder_ID
{
set{ _saleorder_id=value;}
get{return _saleorder_id;}
}
/// <summary>
///
/// </summary>
[Property]
public decimal Quantity
{
set{ _quantity=value;}
get{return _quantity;}
}
/// <summary>
///
/// </summary>
[Property]
public decimal Price
{
set{ _price=value;}
get{return _price;}
}
/// <summary>
///
/// </summary>
[Property]
public decimal Discount
{
set{ _discount=value;}
get{return _discount;}
}
/// <summary>
///
/// </summary>
[Property]
public int Employee_ID
{
set { _employee_id = value; }
get { return _employee_id; }
}
/// <summary>
///
/// </summary>
[Property]
public DateTime Sale_Dtl_Time
{
get { return sale_Dtl_Time; }
set { sale_Dtl_Time = value; }
}
#endregion Model
}
public class SaleDtlInfo
{
public SaleDtlInfo()
{}
Int32 proID;
string proCode;
string proName;
decimal paidIn;
decimal price;
decimal quanity;
decimal discount;
decimal total;
Int32 serverID;
string server;
DateTime sale_Dtl_Time;
/// <summary>
/// 商品ID
/// </summary>
public Int32 ProID
{
get { return proID; }
set { proID = value; }
}
/// <summary>
/// 商品编号
/// </summary>
public string ProCode
{
get { return proCode; }
set { proCode = value; }
}
/// <summary>
/// 商品名称
/// </summary>
public string ProName
{
get { return proName; }
set { proName = value; }
}
/// <summary>
/// 实际单价
/// </summary>
public decimal PaidIn
{
get { return paidIn; }
set { paidIn = value; }
}
/// <summary>
/// 商品原价
/// </summary>
public decimal Price
{
get { return price; }
set { price = value; }
}
/// <summary>
/// 数量
/// </summary>
public decimal Quanity
{
get { return quanity; }
set { quanity = value; }
}
/// <summary>
/// 折扣幅度
/// </summary>
public decimal Discount
{
get { return discount; }
set { discount = value; }
}
/// <summary>
/// 共计金额
/// </summary>
public decimal Total
{
get { return total; }
set { total = value; }
}
/// <summary>
/// 服务人员ID
/// </summary>
public Int32 ServerID
{
get { return serverID; }
set { serverID = value; }
}
/// <summary>
/// 服务人员姓名
/// </summary>
public string Server
{
get { return server; }
set { server = value; }
}
/// <summary>
/// 添加时间
/// </summary>
public DateTime Sale_Dtl_Time
{
get { return sale_Dtl_Time; }
set { sale_Dtl_Time = value; }
}
}
}
<file_sep>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 Message.Model;
using Service.Common;
namespace WinApp.WinForm
{
public partial class FormMemCard : Form
{
MemberCard mc = new MemberCard();
CardType ct = new CardType();
string cardNo;
decimal paymentCard;
public decimal PaymentCard
{
get { return paymentCard; }
set { paymentCard = value; }
}
public string CardNo
{
get { return cardNo; }
set { cardNo = value; }
}
public FormMemCard(decimal TotalAmount)
{
InitializeComponent();
lbAmount.Text = TotalAmount.ToString("f2");
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (tbxCardNo.Text.Trim()!="")
{
List<string[]> where = new List<string[]>();
where.Add(new string[] { "CardNO = {0}", tbxCardNo.Text.Trim() });
DataTable dt = mc.GetDataSet("SELECT TOP 1 ID FROM MemberCard", where);
if (dt.Rows.Count > 0)
{
string CardID = dt.Rows[0][0].ToString();
mc.FindbyPK(CardID);
ct.FindbyPK(mc.CardType.ToString());
this.lbCardType.Text = ct.TypeName;
lbCardNo.Text = mc.CardNO;
lbMemberName.Text = mc.MemberName;
lbUserTel.Text = mc.UserTel;
lbHandleTime.Text = mc.HandleTime.ToString("yyyy-MM-dd HH:mm:ss");
lbLastUse.Text = mc.LastUse.ToString("yyyy-MM-dd HH:mm:ss");
lbBalance.Text = mc.Balance.ToString("f2");
if (tbxConsumption.Text == "")
{
if (Convert.ToDecimal(lbBalance.Text) >= Convert.ToDecimal(lbAmount.Text))
{
tbxConsumption.Text = lbAmount.Text;
}
else
{
tbxConsumption.Text = lbBalance.Text;
}
}
lbCannotFind.Visible = false;
}
else
{
lbMemberName.Text = "";
lbCardType.Text = "";
lbMemberName.Text = "";
lbUserTel.Text = "";
lbHandleTime.Text = "";
lbLastUse.Text = "";
lbBalance.Text = "";
lbCannotFind.Visible = true;
tbxConsumption.Text = "";
lbCardNo.Text = "";
}
}
}
private void tbxlbConsumption_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void btnDetermine_Click(object sender, EventArgs e)
{
if (lbCardNo.Text!="")
{
if (Convert.ToDecimal(tbxConsumption.Text) >= 0 && Convert.ToDecimal(tbxConsumption.Text) <= Convert.ToDecimal(lbBalance.Text) && Convert.ToDecimal(tbxConsumption.Text) <= Convert.ToDecimal(lbAmount.Text))
{
paymentCard = Convert.ToDecimal(tbxConsumption.Text);
cardNo = lbCardNo.Text;
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("消费金额输入有误!");
}
}
}
}
}
<file_sep>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 Message.Model;
using Service.Common;
namespace WinApp.WinForm.Admin
{
public partial class FormEmpDtl : Form
{
Employee emp = new Employee();
public FormEmpDtl(Int32 Employee_ID)
{
InitializeComponent();
if (Employee_ID!=0)
{
LoadInfo(Employee_ID);
}
}
private void LoadInfo(Int32 EmpID)
{
emp.FindbyPK(EmpID.ToString());
tbxUserName.Text = emp.UserName;
tbxName.Text = emp.Name;
tbxDuty.Text = emp.Duty;
tbxIdentityCard.Text = emp.IdentityCard;
tbxAddress.Text = emp.Address;
tbxPhone.Text = emp.Phone;
tbxEmail.Text = emp.Email;
tbxRemark.Text = emp.Remark;
dtpBirthDate.Value = emp.BirthDate;
if (emp.Gender == "男")
{
rbMale.Checked = true;
}
else
{
rbFemale.Checked = true;
}
}
private void btnSave_Click(object sender, EventArgs e)
{
SaveUserInfo();
}
private void SaveUserInfo()
{
if (tbxUserName.Text.Trim()=="")
{
MessageBox.Show("请填写登录名!");
return;
}
if (tbxName.Text.Trim() == "")
{
MessageBox.Show("请填写姓名!");
return;
}
List<string[]> liWhere = new List<string[]>();
liWhere.Add(new string[] { "UserName = {0}", tbxUserName.Text });
if (emp.GetDataSetCount("SELECT ID FROM Employee", liWhere) > 0)
{
MessageBox.Show("该登录名已经存在!");
return;
}
emp.UserName = tbxUserName.Text;
emp.Name = tbxName.Text;
emp.Duty = tbxDuty.Text;
emp.IdentityCard = tbxIdentityCard.Text;
emp.Address = tbxAddress.Text;
emp.Phone = tbxPhone.Text;
emp.Email = tbxEmail.Text;
emp.Remark = tbxRemark.Text;
emp.BirthDate = dtpBirthDate.Value;
if (rbMale.Checked)
{
emp.Gender = "男";
}
else
{
emp.Gender = "女";
}
if (emp.Employee_ID == 0)
{
emp.PassWord = <PASSWORD>Encrypt.EncryptText("<PASSWORD>");
emp.Dept_ID = 1;
emp.LastLogin = DateTime.Now;
emp.HireDate = DateTime.Now;
emp.Insert();
}
else
{
emp.Update();
}
DialogResult = DialogResult.OK;
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
}
}
<file_sep>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 Message.Model;
using System.Threading;
using Service.Common.Log;
using Service.Common;
using Service.Common.Data;
namespace WinApp.WinForm
{
public partial class FormSale : Form
{
Form ParentForm1;
Sale SaleInfo = new Sale();
Sale_Detail SaleDtl = new Sale_Detail();
bool IsChanged = false;
Int32 FrmSaleID;
public FormSale(Form parentForm, Int32 SaleID)
{
InitializeComponent();
FrmSaleID = SaleID;
dataGridView1.AutoGenerateColumns = false;
ParentForm1 = parentForm;
LoadInfo(SaleID);
}
private void FormSale_FormClosing(object sender, FormClosingEventArgs e)
{
if (IsChanged)
{
DialogResult confirm = MessageBox.Show("是否保存对此单信息的更改?", "表单内容已更改", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation);
if (confirm == DialogResult.Yes)
{
if (CustIsExists())
{
e.Cancel = true;
return;
}
SaveInfo();
ParentForm1.Show();
}
else if (confirm == DialogResult.No)
{
ParentForm1.Show();
}
else
{
e.Cancel = true;
}
}
else
{
ParentForm1.Show();
}
}
private void btnReturn_Click(object sender, EventArgs e)
{
this.Close();
}
private void btnAdd_Click(object sender, EventArgs e)
{
FormSelect fs1 = new FormSelect();
if (fs1.ShowDialog() == DialogResult.OK)
{
DataTable dt = (DataTable)(dataGridView1.DataSource);
DataRow dr = dt.NewRow();
dr["Product_ID"] = fs1.SaleInfo.ProID;
dr["Code"] = fs1.SaleInfo.ProCode;
dr["ProductName"] = fs1.SaleInfo.ProName;
dr["Price"] = fs1.SaleInfo.Price;
dr["Quantity"] = fs1.SaleInfo.Quanity;
dr["Discount"] = fs1.SaleInfo.Discount;
dr["PaidIn1"] = fs1.SaleInfo.PaidIn;
dr["PaidInAmount"] = fs1.SaleInfo.PaidIn;
dr["Name"] = fs1.SaleInfo.Server;
dr["Employee_ID"] = fs1.SaleInfo.ServerID;
dr["Sale_Dtl_Time"] = fs1.SaleInfo.Sale_Dtl_Time;
dt.Rows.Add(dr);//显示的内容
IsChanged = true;
}
}
private void LoadInfo(Int32 SaleID)
{
//DataGridViewComboBoxColumn dgvComboBoxColumn = dataGridView1.Columns["Discount"] as DataGridViewComboBoxColumn;
DataGridViewComboBoxColumn dgvComboBoxColumn = (DataGridViewComboBoxColumn)dataGridView1.Columns["Discount"];
dgvComboBoxColumn.DataPropertyName = "Discount";
dgvComboBoxColumn.DataSource = ExecuteSql.ExeComSqlForDataSet("SELECT DiscountRate,DisName FROM Discount WHERE Available = 1").Tables[0];
dgvComboBoxColumn.DisplayMember = "DisName";
dgvComboBoxColumn.ValueMember = "DiscountRate";
string strSql = "SELECT Sale_Detail_ID,Product_ID,Code,ProductName,Price,Quantity,Discount,0.0 AS PaidIn1,0.0 AS PaidInAmount,Total,Name,Employee_ID,Sale_Dtl_Time FROM v_SaleDetailList";
if (SaleID != 0)
{
this.Text = SaleID.ToString();
SaleInfo.FindbyPK(SaleID.ToString());
lbTradeNo.Text = SaleInfo.TradeNo;
tbxOrderNo.Text = SaleInfo.OrderNo;
tbxCustomer.Text = SaleInfo.Customer.ToString();
tbxCustomer.ReadOnly = true;
tbxStoreHouse_ID.Text = SaleInfo.StoreHouse_ID.ToString();
lbSaleDate.Text = SaleInfo.SaleDate.ToString("yyyy-MM-dd HH:mm:ss");
List<string[]> where = new List<string[]>();
List<string[]> order = new List<string[]>();
where.Add(new string[] { "SaleOrder_ID = {0}", SaleID.ToString() });
order.Add(new string[] { "Sale_Detail_ID", "ASC" });
DataTable dt = SaleInfo.GetDataSet(strSql, where, order);
dataGridView1.DataSource = dt;
}
else
{
List<string[]> where = new List<string[]>();
where.Add(new string[] { "SaleOrder_ID = {0}", SaleID.ToString() });
DataTable dt = SaleInfo.GetDataSet(strSql, where);
dataGridView1.DataSource = dt;
}
((DataTable)dataGridView1.DataSource).Columns["PaidInAmount"].Expression = "Convert(Price*Quantity*Discount, 'System.Decimal')";
((DataTable)dataGridView1.DataSource).Columns["PaidIn1"].Expression = "Convert(Price*Discount, 'System.Decimal')";
}
private void btnSave_Click(object sender, EventArgs e)
{
if (CustIsExists())
{
return;
}
SaveInfo();
Close();
ParentForm1.Show();
}
private void SaveInfo()
{
if (FrmSaleID == 0)
{
SaleInfo.SaleDate = DateTime.Now;
SaleInfo.TradeNo = SaleInfo.getTradCode();
SaleInfo.OrderNo = tbxOrderNo.Text.Trim();
SaleInfo.Dept_ID = 1;
SaleInfo.Employee_ID = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
SaleInfo.StoreHouse_ID = Convert.ToInt32(tbxStoreHouse_ID.Text);
SaleInfo.Address = "沈阳市皇姑区歧山中路49号";
SaleInfo.Account = "0000";
SaleInfo.GatheringWay = "";
SaleInfo.Customer = Convert.ToInt32(tbxCustomer.Text);
SaleInfo.TotalAmount = Convert.ToDecimal(lbTotal.Text);
SaleInfo.CheckoutTime = DateTime.Now;
ReturnMessage rm = SaleInfo.Insert();
lbTradeNo.Text = SaleInfo.TradeNo;
if (rm.IsSucessed)
{
FrmSaleID = Convert.ToInt32(rm.Message);
SaleInfo.FindbyPK(FrmSaleID.ToString());
}
else
{
MessageBox.Show("保存失败," + rm.Message);
return;
}
}
else
{
SaleInfo.StoreHouse_ID = Convert.ToInt32(tbxStoreHouse_ID.Text);
SaleInfo.Customer = Convert.ToInt32(tbxCustomer.Text);
SaleInfo.TotalAmount = Convert.ToDecimal(lbTotal.Text);
SaleInfo.Update();
}
DataTable gvTable = (DataTable)dataGridView1.DataSource;
for (int i = 0; i < gvTable.Rows.Count; i++)
{
SaleDtl = new Sale_Detail();
SaleDtl.Product_ID = Convert.ToInt32(gvTable.Rows[i]["Product_ID"]);
SaleDtl.SaleOrder_ID = FrmSaleID;
SaleDtl.Quantity = Convert.ToDecimal(gvTable.Rows[i]["Quantity"]);
SaleDtl.Price = Convert.ToDecimal(gvTable.Rows[i]["PaidIn1"]);
SaleDtl.Discount = Convert.ToDecimal(gvTable.Rows[i]["Discount"]);
SaleDtl.Employee_ID = Convert.ToInt32(gvTable.Rows[i]["Employee_ID"]);
SaleDtl.Sale_Dtl_Time = Convert.ToDateTime(gvTable.Rows[i]["Sale_Dtl_Time"]);
if (gvTable.Rows[i]["Sale_Detail_ID"].ToString() == "")
{
SaleDtl.Insert();
}
else
{
SaleDtl.Sale_Detail_ID = Convert.ToInt32(gvTable.Rows[i]["Sale_Detail_ID"]);
SaleDtl.Update();
}
}
IsChanged = false;
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
StatisticsAmount();
}
private void StatisticsAmount()
{
decimal TotalAmount = 0;
DataTable dt = (DataTable)dataGridView1.DataSource;
for (int i = 0; i < dt.Rows.Count; i++)
{
TotalAmount += Convert.ToDecimal(dt.Rows[i]["PaidInAmount"]);
}
lbTotal.Text = Math.Floor(Convert.ToDouble(TotalAmount) + 0.5).ToString("f2");
}
private void tbxCustomer_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDigital(e);
}
private void tbxStoreHouse_ID_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDigital(e);
}
private void tbxCustomer_KeyUp(object sender, KeyEventArgs e)
{
IsChanged = true;
}
private void tbxStoreHouse_ID_KeyUp(object sender, KeyEventArgs e)
{
IsChanged = true;
}
private void btnCashier_Click(object sender, EventArgs e)
{
if (CustIsExists())
{
return;
}
SaveInfo();
FormCashier frmCashier = new FormCashier(FrmSaleID);
ReturnMessage rm;
if (frmCashier.ShowDialog() == DialogResult.OK)
{
SaleInfo.TotalAmount = frmCashier.PaymentInfo.TotalAmount;
SaleInfo.Cash = frmCashier.PaymentInfo.Cash;
SaleInfo.UnionPay = frmCashier.PaymentInfo.UnionPay;
SaleInfo.OtherPayment = frmCashier.PaymentInfo.OtherPayment;
SaleInfo.Account = frmCashier.PaymentInfo.Account;
SaleInfo.MemCard = frmCashier.PaymentInfo.MemCard;
SaleInfo.CheckoutTime = DateTime.Now;
SaleInfo.State = 0;
rm = SaleInfo.Update();
if (rm.IsSucessed)
{
if (frmCashier.PaymentInfo.MemCard >= 0 && frmCashier.PaymentInfo.Account != "0000")
{
rm = MemCardOper.MemCardHandle(frmCashier.PaymentInfo.Account, frmCashier.PaymentInfo.MemCard, SaleInfo.TradeNo);
if (!rm.IsSucessed)
{
MessageBox.Show(rm.Message);
SaleInfo.State = 1;
SaleInfo.Update();//会员卡操作失败,回滚
return;
}
}
}
else
{
MessageBox.Show("结帐失败!" + rm.Message);
return;
}
string msg = "";
if (frmCashier.PaymentInfo.Cash > 0)
{
msg += "现金:" + frmCashier.PaymentInfo.Cash + "元\r";
}
if (frmCashier.PaymentInfo.UnionPay > 0)
{
msg += "银联卡支付:" + frmCashier.PaymentInfo.UnionPay + "元\r";
}
if (frmCashier.PaymentInfo.MemCard > 0)
{
msg += "会员卡支付:" + frmCashier.PaymentInfo.MemCard + "元\r";
}
if (frmCashier.PaymentInfo.OtherPayment > 0)
{
msg += "其他方式支付:" + frmCashier.PaymentInfo.OtherPayment + "元\r";
}
if (msg != "")
{
msg = ",其中\r" + msg;
}
/************************************************************************************/
//打印代码放这
PrintInfo();
/*************************************************************************************/
MessageBox.Show("结帐成功!\r 共消费" + frmCashier.PaymentInfo.TotalAmount + "元" + msg);
Close();
ParentForm1.Show();
}
}
private void btnMergeBill_Click(object sender, EventArgs e)
{
if (CustIsExists())
{
return;
}
SaveInfo();
FormMergeBill fmb = new FormMergeBill(FrmSaleID);
if (fmb.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("合并成功!");
LoadInfo(FrmSaleID);
StatisticsAmount();
}
}
private bool CustIsExists()
{
if (tbxCustomer.Text.Trim() == "")
{
MessageBox.Show("请填写客户号!");
tbxCustomer.Focus();
return true;
}
if (tbxStoreHouse_ID.Text.Trim() == "")
{
MessageBox.Show("请填写房间号!");
tbxStoreHouse_ID.Focus();
return true;
}
List<string[]> liWhere = new List<string[]>();
liWhere.Add(new string[] { "Customer = {0}", tbxCustomer.Text.Trim() });
liWhere.Add(new string[] { "State = {0}", "1" });
liWhere.Add(new string[] { "Sale_ID <> {0}", FrmSaleID.ToString() });
Int32 CusCount = SaleInfo.GetDataSetCount("SELECT Sale_ID FROM Sale", liWhere);
DataTable dt = SaleInfo.GetDataSet("SELECT Sale_ID FROM Sale", liWhere);
if (CusCount > 0)
{
MessageBox.Show("该顾客号码当前还未结帐!");
return true;
}
else
{
return false;
}
}
private void PrintInfo()
{
DataSet ds = new DataSet();
ds.Tables.Add(((DataTable)dataGridView1.DataSource).Copy());
PrintCommon pc = new PrintCommon();
pc.PrintDataSet(ds, SaleInfo);
}
private void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
{
if (this.dataGridView1.CurrentCell.OwningColumn.Name == "Discount")
{
((ComboBox)e.Control).SelectionChangeCommitted += new EventHandler(FormSale_SelectedIndexChanged);
}
}
void FormSale_SelectedIndexChanged(object sender, EventArgs e)
{
DataTable dt = dataGridView1.DataSource as DataTable;
dt.Rows[dataGridView1.CurrentCell.RowIndex]["Discount"] = ((ComboBox)sender).SelectedValue;
IsChanged = true;
}
}
}
<file_sep>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 Message.Model;
using System.Threading;
using Service.Common;
using Service.Common.IO;
namespace WinApp.WinForm.Admin
{
public partial class FormProdDtl : Form
{
Product pro = new Product();
public FormProdDtl(Int32 ProID)
{
InitializeComponent();
tbxName.Focus();
if (ProID != 0)
{
LoadInfo(ProID);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
if (tbxName.Text.Trim() == "")
{
MessageBox.Show("请填写名称!");
return;
}
if (tbxPrice.Text.Trim() == "")
{
MessageBox.Show("请填写价格!");
return;
}
if (tbxCommission.Text.Trim() == "")
{
MessageBox.Show("请填写提成!");
return;
}
pro.Code = tbxCode.Text;
pro.Name = tbxName.Text;
PinyinCommon pyc = new PinyinCommon();
pro.spell = pyc.GetQuanPing(tbxName.Text.Trim());
pro.s_spell = pyc.GetPYString(tbxName.Text.Trim());
pro.shortname = tbxName.Text;
pro.Price = Convert.ToDecimal(tbxPrice.Text);
pro.Offering_Price = Convert.ToDecimal(tbxPrice.Text);
pro.Commission = Convert.ToDecimal(tbxCommission.Text);
pro.Remark = tbxRemark.Text;
if (pro.Product_ID == 0)
{
List<string[]> LiWhere = new List<string[]>();
LiWhere.Add(new string[] { "Name = {0}", tbxName.Text });
DataTable dt = pro.GetDataSet("SELECT Product_ID FROM Product", LiWhere);
if (dt.Rows.Count > 0)
{
MessageBox.Show("该商品名已存在!");
return;
}
pro.ProductList_ID = 1;
pro.ProductSpec_ID = 1;
pro.ProductUnit_ID = 1;
pro.Employee_ID = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
pro.CreateDate = DateTime.Now;
string newProId = pro.Insert().Message;
pro.FindbyPK(newProId);
pro.Code = Convert.ToInt32(newProId).ToString("000");
pro.Update();
}
else
{
pro.Update();
}
MessageBox.Show("保存成功!");
DialogResult = DialogResult.OK;
}
private void LoadInfo(Int32 proID)
{
pro.FindbyPK(proID.ToString());
tbxCode.Text = pro.Code;
tbxName.Text = pro.Name;
tbxPrice.Text = pro.Price.ToString("f2");
tbxCommission.Text = pro.Commission.ToString("f2");
tbxCreateDate.Text = pro.CreateDate.ToString("yyyy-MM-dd HH:mm:ss");
Employee emp = new Employee();
emp.FindbyPK(pro.Employee_ID.ToString());
tbxEmployee_ID.Text = emp.Name;
tbxRemark.Text = pro.Remark;
tbxCreateDate.ReadOnly = true;
tbxEmployee_ID.ReadOnly = true;
}
private void tbxPrice_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void btnClose_Click(object sender, EventArgs e)
{
Close();
}
private void tbxCommission_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace Service.Common.IO
{
public class ExcelOperate
{
public static string connString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;HDR=YES;IMEX={1}';";
/// <summary>
/// 获取Excel中的表名
/// </summary>
/// <param name="stPath"></param>
/// <returns></returns>
public static String[] GetExcelSheetNames(string stPath)
{
OleDbConnection objConn = null;
System.Data.DataTable dt = null;
try
{
objConn = new OleDbConnection(string.Format(connString, stPath, "1"));
objConn.Open();
dt = objConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (dt == null)
{
return null;
}
for (int n = 0; n < dt.Rows.Count; n++)
{
string[] strTableName = dt.Rows[n]["TABLE_NAME"].ToString().Split('$');
if (strTableName.Length < 3 && strTableName[1].ToString() == "")
{
}
else
{
dt.Rows.RemoveAt(n);
}
}
int m = dt.Rows.Count;
String[] excelSheets = new String[dt.Rows.Count];
int i = 0;
foreach (DataRow row in dt.Rows)
{
excelSheets[i] = row["TABLE_NAME"].ToString();
i++;
}
return excelSheets;
}
catch (Exception ex)
{
return null;
}
finally
{
if (objConn != null)
{
objConn.Close();
objConn.Dispose();
}
if (dt != null)
{
dt.Dispose();
}
}
}
/// <summary>
/// 获取源数据标题
/// </summary>
/// <param name="Spath">源文件路径</param>
/// <param name="sheetName">Sheet页名称</param>
/// <returns></returns>
public static DataTable GetTitle(string Spath, string sheetName)
{
DataTable dtData = new DataTable();
OleDbDataReader datareader = null;
OleDbConnection Conn = null;
try
{
dtData.Columns.Add("CNC");
dtData.Columns.Add("CNE");
dtData.Columns.Add("CK");
dtData.Columns.Add("CJ");
Conn = new OleDbConnection(string.Format(connString, Spath, "0"));
Conn.Open();
string stSQL = "select * from [" + sheetName + "$]";
OleDbCommand dbCommand = new OleDbCommand(stSQL, Conn);
datareader = dbCommand.ExecuteReader();
bool IsChinese = false;
if (datareader.FieldCount != 0)
{
IsChinese = FileOperate.IsChineseChar(datareader.GetName(0));
}
else
{
return null;
}
List<string> myAL = new List<string>();
int j = 0;
for (int i = 0; i < datareader.FieldCount; i++)
{
string itemEn = StrToPinyin.GetChineseSpell(datareader.GetName(i)).ToString();
if (myAL.Count != 0)
{
if (myAL.Contains(itemEn) == false)
{
myAL.Add(itemEn);
}
else
{
itemEn = itemEn + j.ToString();
j++;
}
}
else
{
myAL.Add(itemEn);
}
DataRow dr = dtData.NewRow();
if (FileOperate.IsChineseChar(datareader.GetName(i)))
{
dr["CNC"] = datareader.GetName(i);
dr["CNE"] = itemEn;
}
else
{
dr["CNC"] = datareader.GetName(i);
dr["CNE"] = datareader.GetName(i);
}
dtData.Rows.Add(dr);
}
}
catch (Exception ex)
{
return null;
}
finally
{
Conn.Close();
datareader.Dispose();
}
return dtData;
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// Discount:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("Discount")]
public partial class Discount : EntityBase<Discount>
{
public Discount()
{}
#region Model
private int _id;
private decimal _discountrate;
private string _disname;
private bool _available;
private string _remark;
/// <summary>
///
/// </summary>
[PrimaryKey("ID", IsAuto = true)]
public int ID
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
[Property]
public decimal DiscountRate
{
set{ _discountrate=value;}
get{return _discountrate;}
}
/// <summary>
///
/// </summary>
[Property]
public string DisName
{
set{ _disname=value;}
get{return _disname;}
}
/// <summary>
///
/// </summary>
[Property]
public bool Available
{
set{ _available=value;}
get{return _available;}
}
/// <summary>
///
/// </summary>
[Property]
public string Remark
{
set{ _remark=value;}
get{return _remark;}
}
#endregion Model
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using Service.Common.Log;
namespace Service.Common.IO
{
public class XMLOperator
{
#region 变量
bool bValid = false;
string stErrMessage = string.Empty;
private long lXmlCount = 0;
/// <summary>
/// 文件路径
/// </summary>
private string stDataFile = null;
/// <summary>
/// 数据集
/// </summary>
private DataSet dsDataSet = null;
/// <summary>
/// 字符过滤数组 比如 "id='1' and userName='trace'"
/// </summary>
private string stFilter = null;
/// <summary>
/// 排序的字段 比如 "id desc,userName"
/// </summary>
private string stSort = null;
/// <summary>
/// 数据集合中的字段名集合
/// </summary>
private string[] stFields = null;
/// <summary>
/// 数据集合中的数据数组
/// </summary>
private string[] stData = null;
#endregion
#region 属性
/// <summary>
/// 数据文件路径
/// </summary>
public string DataFile
{
set { this.stDataFile = value; }
get { return this.stDataFile; }
}
/// <summary>
/// 字符过滤数组
/// </summary>
public string FilterString
{
set { this.stFilter = value; }
}
/// <summary>
/// 排序的字段
/// </summary>
public string SortString
{
set { this.stSort = value; }
}
/// <summary>
/// 数据集合中的字段名
/// </summary>
public string[] FieldsString
{
set { this.stFields = value; }
}
/// <summary>
/// 数据集合中的数据数组
/// </summary>
public string[] DataString
{
set { this.stData = value; }
}
/// <summary>
/// 数据集合,可以放在缓存供调用
/// </summary>
public DataSet DataSetData
{
set { this.dsDataSet = value; }
get { return this.dsDataSet; }
}
#endregion
#region 构造函数
public XMLOperator()
{
//
// TODO: 提供将XML当作数据库处理的一些方法
//
}
#endregion
#region 事件
#endregion
#region 方法
/// <summary>
/// 取得XML文件的内容并填入DataSet
/// </summary>
public void Open()
{
this.dsDataSet = new DataSet();
FileStream fin;
fin = new FileStream(this.DataFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
this.dsDataSet.ReadXml(fin);
fin.Close();
}
/// <summary>
/// 将操作结果写入XML
/// </summary>
public void Save()
{
this.dsDataSet.WriteXml(this.DataFile);
this.Clear();
}
/// <summary>
/// 取得特定的数据视图
/// 一般在数据绑定的时候,我们可以很方便的生成供绑定的视图
/// </summary>
/// <returns>数据视图</returns>
public DataView SelectView()
{
if (this.dsDataSet == null) this.Open();
DataView myDv = new DataView(this.dsDataSet.Tables[0]);
if (stFilter != null) myDv.RowFilter = this.stFilter;
myDv.Sort = this.stSort;
return myDv;
}
/// <summary>
/// 取得特定的行
/// 使用行的方式是因为有些时候,我们仅仅只需要某一行或多行记录
/// 比如我们判断登陆的时候,只是需要某个ID的所在行,然后匹配它的密码项
/// </summary>
/// <returns>各行数据</returns>
public DataRow[] SelectRows()
{
if (this.dsDataSet == null) this.Open();
DataRow[] myRows = dsDataSet.Tables[0].Select(this.stFilter);
return myRows;
}
/// <summary>
/// 往XML当中插入一条数据
/// </summary>
/// <returns>操作是否成功</returns>
public bool InsertData()
{
if (this.dsDataSet == null) this.Open();
DataRow newRow = dsDataSet.Tables[0].NewRow();
for (int i = 0; i < this.stFields.Length; i++)
{
newRow[this.stFields[i]] = this.stData[i];
}
dsDataSet.Tables[0].Rows.Add(newRow);
this.Save();
return true;
}
/// <summary>
/// 更新数据,这个时候要确保strFields 与 strData 两个数组的维数一致
/// </summary>
/// <returns>是否更新成功</returns>
public bool UpdateData()
{
if (this.dsDataSet == null) this.Open();
DataRow[] editRow = dsDataSet.Tables[0].Select(this.stFilter);
for (int j = 0; j < editRow.Length; j++)
{
for (int i = 0; i < this.stFields.Length; i++)
{
editRow[j][this.stFields[i]] = this.stData[i];
}
}
this.Save();
return true;
}
/// <summary>
/// 删除数据
/// </summary>
/// <returns>是否删除成功</returns>
public bool DeleteData()
{
if (this.dsDataSet == null) this.Open();
DataRow[] editRow = dsDataSet.Tables[0].Select(this.stFilter);
for (int i = 0; i < editRow.Length; i++)
{
editRow[i].Delete();
}
this.Save();
return true;
}
/// <summary>
/// 释放资源
/// </summary>
public void Clear()
{
if (this.dsDataSet != null)
{
this.dsDataSet.Dispose();
}
}
/// <summary>
/// 获取源数据标题
/// </summary>
/// <param name="Spath">源文件路径</param>
/// <returns></returns>
public static DataTable GetTitle(string Spath)
{
DataTable dtData = new DataTable();
StreamReader sr = null;
StringReader stringReader = null;
try
{
dtData.Columns.Add("CNC");
dtData.Columns.Add("CNE");
dtData.Columns.Add("CK");
dtData.Columns.Add("CJ");
FileStream fs = new FileStream(Spath, FileMode.Open);
Encoding Code = FileOperate.GetEncoding(fs, Encoding.Default);
fs.Close();
fs.Dispose();
sr = new StreamReader(Spath, Code);
StringBuilder sbRow = new StringBuilder();
string NextRow = string.Empty;
string mappingTableName = string.Empty;
string stCell = string.Empty;
string RootName = ConfigurationManager.AppSettings.Get("RootName");
while ((stCell = sr.ReadLine()) != null || (NextRow.Length != 0))
{
stCell = NextRow + stCell;
//开头
if (stCell.Contains("<" + RootName))
{
sbRow.Append("<" + RootName + ">");
stCell = stCell.Substring(stCell.IndexOf("<" + RootName));
NextRow = stCell.Substring(stCell.IndexOf("<" + RootName) + RootName.Length + 1);
NextRow = NextRow.Substring(NextRow.IndexOf(">") + 1);
}
else if (sbRow.ToString() != string.Empty)
{
if (mappingTableName != string.Empty)
{
//结尾
if (stCell.Contains("</" + mappingTableName + ">"))
{
sbRow.Append(stCell.Substring(0, stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3));
sbRow.Append("</" + RootName + ">");
break;
}
else
{
NextRow = stCell;
}
}
if (stCell.Contains("<") && mappingTableName == string.Empty)
{
mappingTableName = stCell.Substring(stCell.IndexOf('<') + 1);
mappingTableName = mappingTableName.Substring(0, mappingTableName.IndexOf('>'));
dtData.TableName = mappingTableName;
sbRow.Append("<" + mappingTableName + ">");
NextRow = stCell.Substring(stCell.IndexOf(">") + 1);
}
}
}
if (sbRow.ToString() != string.Empty)
{
DataSet dsTemp = new DataSet();
stringReader = new StringReader(sbRow.ToString());
dsTemp.ReadXml(stringReader);
bool IsChinese = false;
if (dsTemp.Tables[0].Columns.Count != 0)
{
IsChinese = FileOperate.IsChineseChar(dsTemp.Tables[0].Columns[0].ColumnName);
}
else
{
return dtData;
}
ArrayList myAL = new ArrayList();
int j = 0;
for (int i = 0; i < dsTemp.Tables[0].Columns.Count; i++)
{
string itemEn = StrToPinyin.GetChineseSpell(dsTemp.Tables[0].Columns[i].ColumnName).ToString();
if (myAL.Count != 0)
{
if (myAL.Contains(itemEn) == false)
{
myAL.Add(itemEn);
}
else
{
itemEn = itemEn + j.ToString();
j++;
}
}
else
{
myAL.Add(itemEn);
}
DataRow dr = dtData.NewRow();
if (FileOperate.IsChineseChar(dsTemp.Tables[0].Columns[i].ColumnName))
{
dr["CNC"] = dsTemp.Tables[0].Columns[i].ColumnName;
dr["CNE"] = itemEn;
}
else
{
dr["CNE"] = dsTemp.Tables[0].Columns[i].ColumnName;
}
dtData.Rows.Add(dr);
}
}
}
catch (Exception ex)
{
return dtData;
}
finally
{
if (sr != null)
{
sr.Close();
sr.Dispose();
}
if (stringReader != null)
{
stringReader.Close();
stringReader.Dispose();
}
}
return dtData;
}
/// <summary>
/// 读取原始数据前十条
/// </summary>
/// <param name="Spath">源文件路径</param>
/// <returns></returns>
public static DataTable ReadTopTenBySource(string Spath, string mappingTableName, string[] mappingColumns, int count)
{
DataSet dsData = new DataSet();
StreamReader sr = null;
StringReader stringReader = null;
FileStream fs = null;
int iCount = 0;
try
{
fs = new FileStream(Spath, FileMode.Open);
Encoding Code = FileOperate.GetEncoding(fs, Encoding.Default);
fs.Close();
fs.Dispose();
sr = new StreamReader(Spath, Code);
StringBuilder sbRowAll = new StringBuilder();
bool IsRow = false;
string Begin = string.Empty;
string NextRow = string.Empty;
string stCell = string.Empty;
string RootName = ConfigurationManager.AppSettings.Get("RootName");
StringBuilder sbRow = new StringBuilder();
sbRowAll.Append("<" + RootName + ">");
while ((stCell = sr.ReadLine()) != null || (NextRow.Length != 0))
{
stCell = NextRow + stCell;
//开头
if (stCell.Contains("<" + mappingTableName + ">"))
{
stCell = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">"));
sbRow.Append("<" + mappingTableName + ">");
NextRow = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">") + mappingTableName.Length + 2);
}
else
{
//结尾
if (stCell.Contains("</" + mappingTableName + ">"))
{
IsRow = true;
sbRow.Append(stCell.Substring(0, stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3));
NextRow = stCell.Substring(stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3);
}
else if (sbRow.ToString() != string.Empty)
{
sbRow.Append(stCell);
}
if (IsRow)
{
//处理一行
sbRowAll.Append("<" + mappingTableName + ">");
for (int i = 0; i < mappingColumns.Length; i++)
{
string stTemp = sbRow.ToString();
if (stTemp.Contains("<" + mappingColumns[i] + ">") && stTemp.Contains("</" + mappingColumns[i] + ">"))
{
Begin = stTemp.Substring(stTemp.IndexOf("<" + mappingColumns[i] + ">") + mappingColumns[i].Length + 2);
sbRowAll.Append("<" + mappingColumns[i] + ">");
string stConten = Begin.Substring(0, Begin.IndexOf("</" + mappingColumns[i] + ">")).Trim();
if (stConten.Contains("<![CDATA[") && stConten.Contains("]]>"))
{
stConten = stConten.Replace("<![CDATA[", "").Replace("]]>", "");
}
sbRowAll.Append("<![CDATA[");
sbRowAll.Append(stConten);
sbRowAll.Append("]]>");
sbRowAll.Append("</" + mappingColumns[i] + ">");
}
else
{
sbRowAll.Append("<" + mappingColumns[i] + " />");
}
}
sbRowAll.Append("</" + mappingTableName + ">");
sbRow = new StringBuilder();
IsRow = false;
iCount++;
if (count != -1 && iCount == count)
{
break;
}
}
}
}
sbRowAll.Append("</" + RootName + ">");
if (sbRowAll.ToString() != string.Empty)
{
stringReader = new StringReader(sbRowAll.ToString());
dsData.ReadXml(stringReader);
}
}
catch (Exception ex)
{
return null;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (sr != null)
{
sr.Close();
sr.Dispose();
}
if (stringReader != null)
{
stringReader.Close();
stringReader.Dispose();
}
}
return dsData.Tables[0];
}
/// <summary>
/// 处理数据生成带特殊字符保护的XML文件
/// </summary>
/// <param name="fileName">目标文件名</param>
/// <param name="Spath">源文件路径</param>
/// <param name="tableName">原结构表英文名</param>
/// <param name="columns">原结构表英文列名</param>
/// <param name="tableName">表英文名</param>
/// <param name="columns">表英文列名</param>
/// <param name="Tpath">目标文件路径(不以"\"结尾)</param>
/// <returns></returns>
public static ReturnMessage HandleToXml(string fileName, string Spath, string mappingTableName, string[] mappingColumns, string tableName, string[] columns, string Tpath)
{
return HandleToXml(fileName, Spath, mappingTableName, mappingColumns, tableName, columns, Tpath, -1);
}
/// <summary>
/// 处理数据生成带特殊字符保护的XML文件
/// </summary>
/// <param name="fileName">目标文件名</param>
/// <param name="Spath">源文件路径</param>
/// <param name="tableName">原结构表英文名</param>
/// <param name="columns">原结构表英文列名</param>
/// <param name="tableName">表英文名</param>
/// <param name="columns">表英文列名</param>
/// <param name="Tpath">目标文件路径(不以"\"结尾)</param>
/// <param name="count">分包条数(条数>0)</param>
/// <returns></returns>
public static ReturnMessage HandleToXml(string fileName, string Spath, string mappingTableName, string[] mappingColumns, string tableName, string[] columns, string Tpath, int count)
{
ReturnMessage rm = new ReturnMessage();
StreamReader sr = null;
XmlWriter xwr = null;
int iCount = 0;//导出条数
int IErrorCount = 0;//筛选出去的条数
int iTableNum = 1;//表的第几部分
string stImport = string.Empty;
string[] EspChar = File.ReadAllLines(System.AppDomain.CurrentDomain.BaseDirectory + @"Data\EspecialChar.txt");
try
{
FileStream fs = new FileStream(Spath, FileMode.Open);
Encoding Code = FileOperate.GetEncoding(fs, Encoding.Default);
fs.Close();
fs.Dispose();
sr = new StreamReader(Spath, Code);
string RootName = "NewDataSet";
xwr = new XmlTextWriter(Tpath + "\\" + fileName + "_" + iTableNum.ToString() + ".xml", new System.Text.UTF8Encoding());
xwr.WriteStartDocument(true);
xwr.WriteWhitespace("\r\n");
xwr.WriteStartElement(RootName);
bool IsRow = false;
string Begin = string.Empty;
string NextRow = string.Empty;
string stCell = string.Empty;
StringBuilder sbRow = new StringBuilder();
while ((stCell = sr.ReadLine()) != null || (NextRow.Length != 0))
{
stCell = NextRow + stCell;
//开头
if (stCell.Contains("<" + mappingTableName + ">"))
{
stCell = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">"));
sbRow.Append("<" + mappingTableName + ">");
NextRow = stCell.Substring(stCell.IndexOf("<" + mappingTableName + ">") + mappingTableName.Length + 2);
}
else
{
//结尾
if (stCell.Contains("</" + mappingTableName + ">"))
{
IsRow = true;
sbRow.Append(stCell.Substring(0, stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3));
NextRow = stCell.Substring(stCell.IndexOf("</" + mappingTableName + ">") + mappingTableName.Length + 3);
}
else if (sbRow.ToString() != string.Empty)
{
sbRow.Append(stCell);
}
if (IsRow)
{
//获取该行的值
string[] stcolumn = new string[mappingColumns.Length];
for (int i = 0; i < stcolumn.Length; i++)
{
string stTemp = sbRow.ToString();
if (stTemp.Contains("<" + mappingColumns[i] + ">") && stTemp.Contains("</" + mappingColumns[i] + ">"))
{
Begin = stTemp.Substring(stTemp.IndexOf("<" + mappingColumns[i] + ">") + mappingColumns[i].Length + 2);
string stConten = Begin.Substring(0, Begin.IndexOf("</" + mappingColumns[i] + ">")).Trim();
if (stConten.Contains("<![CDATA[") && stConten.Contains("]]>"))
{
stConten = stConten.Replace("<![CDATA[", "").Replace("]]>", "");
}
stcolumn[i] = stConten;
}
else
{
stcolumn[i] = String.Empty;
}
}
//验证非法字符
bool lContainsEspChar = false;
//若存在特殊字符,将其保存到筛选文件里边。
for (int q = 0; q < stcolumn.Length; q++)
{
foreach (string stTemp in EspChar)
{
if (stcolumn[q].ToString().Contains(stTemp))
{
stImport = string.Empty;
for (int p = 0; p < stcolumn.Length; p++)
{
stImport += stcolumn[p].ToString() + "\t";
}
stImport += Environment.NewLine;
File.AppendAllText(Tpath + @"特殊字符筛选\EspecialCharExport_" + tableName + ".txt", stImport);
IErrorCount++;
lContainsEspChar = true;
break;
}
}
if (lContainsEspChar) break;
}
if (lContainsEspChar) continue;
//若不包含特殊字符则进行导出
//判断是否写入新文件
if (count > 0 && (iCount + 1) / count > 0 && iCount % count == 0)
{
//结束文件
xwr.WriteWhitespace("\r\n");
xwr.WriteEndElement();
xwr.WriteEndDocument();
xwr.Flush();
xwr.Close();
//开始新文件
iTableNum++;
xwr = new XmlTextWriter(Tpath + "\\" + fileName + "_" + iTableNum.ToString() + ".xml", new System.Text.UTF8Encoding());
xwr.WriteStartDocument(true);
xwr.WriteWhitespace("\r\n");
xwr.WriteStartElement(RootName);
}
//处理一行
xwr.WriteWhitespace("\r\n\t");
xwr.WriteStartElement(tableName);
for (int i = 0; i < mappingColumns.Length; i++)
{
if (stcolumn[i] != string.Empty)
{
xwr.WriteWhitespace("\r\n\t\t");
xwr.WriteStartElement(columns[i]);
xwr.WriteCData(stcolumn[i]);
xwr.WriteEndElement();
}
else
{
xwr.WriteWhitespace("\r\n\t\t");
xwr.WriteElementString(columns[i], String.Empty);
}
}
xwr.WriteWhitespace("\r\n\t");
xwr.WriteFullEndElement();
IsRow = false;
sbRow = new StringBuilder();
//if (count != -1 && iCount == count)
//{
// break;
//}
iCount++;
}
}
}
xwr.WriteWhitespace("\r\n");
xwr.WriteEndElement();
xwr.WriteEndDocument();
rm.IsSucessed = true;
rm.Message = "导出数据" + iCount.ToString() + "行";
}
catch (Exception ex)
{
rm.IsSucessed = false;
rm.Message = ex.Message;
}
finally
{
if (xwr != null)
{
xwr.Flush();
xwr.Close();
}
if (sr != null)
{
sr.Close();
sr.Dispose();
}
}
return rm;
}
/// <summary>
/// 用流读取XML转换后的前10条,并套用新的结构
/// </summary>
/// <param name="tableName">英文表名</param>
/// <param name="Tpath">目标文件路径</param>
/// <param name="schemaPath">结构文件路径</param>
/// <returns></returns>
public static DataTable ReadTopTenByTarget(string tableName, string Spath, string schemaPath)
{
DataSet dsData = new DataSet();
dsData.ReadXmlSchema(schemaPath);
dsData.ReadXml(Spath);
for (int j = 0; j < dsData.Tables[tableName].Columns.Count; j++)
{
dsData.Tables[tableName].Columns[j].ColumnName = dsData.Tables[tableName].Columns[j].Caption;
}
return dsData.Tables[tableName];
}
void XmlReaderValidationEventHandler(object sender, ValidationEventArgs e)
{
//搜集e.Message中的错误信息,并填充到stErrMessage中
//将bValid设置成false
stErrMessage = e.Message.ToString();
this.bValid = false;
ReturnMessage message = new ReturnMessage();
message.Message = stErrMessage;
message.IsSucessed = bValid;
}
/// <summary>
/// 验证数据文件
/// </summary>
/// <param name="xmlSchemaPath">架构文件路径</param>
/// <param name="xmlPath">数据文件路径</param>
private void ValidData(string xmlSchemaPath, string xmlPath)
{
bValid = true;
XmlReaderSettings xrsValid = new XmlReaderSettings();
xrsValid.CloseInput = true;
xrsValid.IgnoreComments = true;
xrsValid.IgnoreWhitespace = true;
xrsValid.ValidationType = ValidationType.Schema;
xrsValid.Schemas.Add(null, xmlSchemaPath);
xrsValid.CheckCharacters = false;
xrsValid.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlReaderValidationEventHandler);
XmlReader xrdValid = XmlReader.Create(xmlPath, xrsValid);
while (xrdValid.Read())
{
}
xrdValid.Close();
//return false;
//构建一个XmlReaderSettings用于验证要导入的XML信息
//设置XmlReaderSettings
//构建XmlReader用以读取数据,附加前面设置好的XmlReaderSettings
//循环读取XmlReader
}
public ReturnMessage XmlSplit(string xmlPath, string xmlSchemaPath)
{
int iRowCounter = 20000;
ArrayList alsSplitXmlName = new ArrayList();
int iCounters = 0;
string stSplitXmlName = String.Empty;
ReturnMessage returnMessage = new ReturnMessage(true);
try
{
//验证数据文件
ValidData(xmlSchemaPath, xmlPath);
//拆分文件路径
string stSystemp = xmlPath.Substring(0, xmlPath.LastIndexOf('\\')) + "\\Systemp";
if (!Directory.Exists(stSystemp))
{
Directory.CreateDirectory(stSystemp);
}
else
{
DirectoryOperate.ClearDirectory(stSystemp);
}
//string stProjectName = "";
int iks = 0;
if (bValid)
{
#region 拆分XML
string stCurrentTableName = String.Empty;
ArrayList alsSplitIndex = new ArrayList();
XmlTextReader xrdSplit = new XmlTextReader(xmlPath);
XmlTextWriter xwrSplit = null;
XmlWriterSettings xwsSplitValue = new XmlWriterSettings();
xwsSplitValue.Encoding = Encoding.UTF8;
while (xrdSplit.Read())
{
iks = iks + 1;
//aa[iks] = ((System.Xml.XmlReader)(xrdSplit)).Value;
//深度大于1时,直接向分隔XML里赋值
if (xrdSplit.Depth > 1)
{
xwrSplit.WriteNode(xrdSplit, false);
}
//深度等于1时,依条件判断处理
else if (object.Equals(xrdSplit.Depth, 1))
{
//当节点为起始节点,并且不是空行节点时
if (xrdSplit.IsStartElement() && !xrdSplit.IsEmptyElement)
{
//当缓存列表为空时,添加新的表名到缓存列表中
if (Object.Equals(alsSplitXmlName.Count, 0))
{
alsSplitXmlName.Add(xrdSplit.Name.ToString());
}
//当节点与缓存列表中的最后一位相等时,计数器累加
if (Object.Equals((alsSplitXmlName[alsSplitXmlName.Count - 1]).ToString(), xrdSplit.Name.ToString()))
{
iCounters++;
//如果当前节点为第一个节点,生成新的Xml头
if (Object.Equals(iCounters, 1))
{
stSplitXmlName = String.Format(stSystemp + "\\{0}.xml", Guid.NewGuid().ToString());
alsSplitIndex.Add(stSplitXmlName);
xwrSplit = new XmlTextWriter(stSplitXmlName, Encoding.UTF8);
xwrSplit.WriteStartDocument();
xwrSplit.WriteWhitespace("\r\n");
xwrSplit.WriteStartElement("NewDataSet");
xwrSplit.WriteWhitespace("\r\n");
}
//读取当前XML节点,到新的XML文件中
xwrSplit.WriteNode(xrdSplit, false);
//如果计数器已达到每页数据最大数据量时,计数器置零,关闭XML文件,并新建XML头
if (Object.Equals(iCounters, iRowCounter))
{
lXmlCount += iCounters;
iCounters = 0;
lXmlCount = 0;
xwrSplit.WriteEndElement();
xwrSplit.WriteWhitespace("\r\n");
xwrSplit.WriteEndDocument();
xwrSplit.Flush();
xwrSplit.Close();
}
}
//当节点与缓存列表中的最后一位不等时,计数器置零,关闭XML文件,新建XML文件
else if (!Object.Equals((alsSplitXmlName[alsSplitXmlName.Count - 1]).ToString(), xrdSplit.Name.ToString()))
{
alsSplitXmlName.Add(xrdSplit.Name.ToString());
if (!Object.Equals(iCounters, 0))
{
lXmlCount += iCounters;
xwrSplit.WriteEndElement();
xwrSplit.WriteWhitespace("\r\n");
xwrSplit.WriteEndDocument();
xwrSplit.Flush();
xwrSplit.Close();
}
iCounters = 0;
lXmlCount = 0;
iCounters++;
stSplitXmlName = String.Format(stSystemp + "\\{0}.xml", Guid.NewGuid().ToString());
alsSplitIndex.Add(stSplitXmlName);
xwrSplit = new XmlTextWriter(stSplitXmlName, Encoding.UTF8);
xwrSplit.WriteStartDocument();
xwrSplit.WriteWhitespace("\r\n");
xwrSplit.WriteStartElement("NewDataSet");
xwrSplit.WriteWhitespace("\r\n\t");
xwrSplit.WriteNode(xrdSplit, false);
}
}
}
}
if (!Object.Equals(iCounters, 0))
{
lXmlCount += iCounters;
xwrSplit.WriteEndElement();
xwrSplit.WriteWhitespace("\r\n");
xwrSplit.WriteEndDocument();
xwrSplit.Flush();
xwrSplit.Close();
}
xrdSplit.Close();
#endregion
}
else
{
returnMessage.Message = "XML文件不正确,详细信息为:" + stErrMessage;
returnMessage.IsSucessed = bValid;
}
//删除原文件
//File.Delete(xmlPath);
//调用ValidData(string xmlSchemaPath)方法验证导入XML是否合法
//判断bValid是否为false,若为false,则构造新的ReturnMessage,返回错误信息
//若bValid为true,则开始对数据以XmlReader读取并进行插入。
return returnMessage;
}
catch (Exception ex)
{
returnMessage.IsSucessed = false;
returnMessage.Message = "拆分失败,失败原恩:" + ex.Message.ToString();
return returnMessage;
}
}
/// <summary>
/// XML导入数据库
/// </summary>
/// <returns></returns>
public ReturnMessage XmlInput(string stPath, string stXmlSchemaPath, string taskname)
{
ReturnMessage rm = new ReturnMessage(true);
try
{
#region 导入数据库
FileInfo[] files = DirectoryOperate.getAllFile(stPath, "*.xml");
string str = ConfigurationManager.ConnectionStrings["APPDBSTRING"].ConnectionString.ToString();
DataSet ds = new DataSet();
ds.ReadXmlSchema(stXmlSchemaPath);
foreach (FileInfo fileinfo in files)
{
ds.ReadXml(fileinfo.FullName);
//声明数据库连接
SqlConnection conn = new SqlConnection(str);
conn.Open();
//声明SqlBulkCopy ,using释放非托管资源
using (SqlBulkCopy sqlBC = new SqlBulkCopy(conn))
{
//一次批量的插入的数据量
sqlBC.BatchSize = 1000;
//超时之前操作完成所允许的秒数,如果超时则事务不会提交 ,数据将回滚,所有已复制的行都会从目标表中移除
sqlBC.BulkCopyTimeout = 60;
//設定 NotifyAfter 属性,以便在每插入10000 条数据时,呼叫相应事件。
sqlBC.NotifyAfter = 10000;
//sqlBC.SqlRowsCopied += new SqlRowsCopiedEventHandler(OnSqlRowsCopied);
foreach (DataTable dt in ds.Tables)
{
//设置要批量写入的表
sqlBC.DestinationTableName = "dbo.T_" + taskname + "_" + dt.TableName + "_Temp";
//自定义的datatable和数据库的字段进行对应
//sqlBC.ColumnMappings.Add("id", "tel");
//sqlBC.ColumnMappings.Add("name", "neirong");
//批量写入
sqlBC.WriteToServer(dt);
}
}
conn.Dispose();
ds.Clear();
}
#endregion
return rm;
}
catch(Exception ex)
{
rm.IsSucessed = false;
rm.Message = ex.Message;
return rm;
}
}
#endregion
}
}
<file_sep>using System;
using Service.Common.Entity;
using Service.Common.Log;
using System.Collections.Generic;
using System.Data;
namespace Message.Model
{
/// <summary>
/// MemberCard:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("MemberCard")]
public partial class MemberCard : EntityBase<MemberCard>
{
public MemberCard()
{}
#region Model
private int _id;
private string _cardno;
private int _cardtype;
private string _membername;
private string _password;
private string _usertel;
private string _userpic;
private decimal _balance;
private DateTime _handletime= DateTime.Now;
private DateTime _lastuse= DateTime.Now;
private int _state;
private string _remarks;
/// <summary>
/// ID
/// </summary>
[PrimaryKey("ID", IsAuto = true)]
public int ID
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
/// 会员卡号
/// </summary>
[Property]
public string CardNO
{
set{ _cardno=value;}
get{return _cardno;}
}
/// <summary>
/// 会员卡类型
/// </summary>
[Property]
public int CardType
{
set{ _cardtype=value;}
get{return _cardtype;}
}
/// <summary>
/// 用户姓名
/// </summary>
[Property]
public string MemberName
{
set{ _membername=value;}
get{return _membername;}
}
/// <summary>
/// 密码
/// </summary>
[Property]
public string PassWord
{
set{ _password=value;}
get{return _password;}
}
/// <summary>
/// 联系电话
/// </summary>
[Property]
public string UserTel
{
set{ _usertel=value;}
get{return _usertel;}
}
/// <summary>
/// 照片
/// </summary>
[Property]
public string UserPic
{
set{ _userpic=value;}
get{return _userpic;}
}
/// <summary>
/// 余额
/// </summary>
[Property]
public decimal Balance
{
set{ _balance=value;}
get{return _balance;}
}
/// <summary>
/// 办理时间
/// </summary>
[Property]
public DateTime HandleTime
{
set{ _handletime=value;}
get{return _handletime;}
}
/// <summary>
/// 最后一次使用
/// </summary>
[Property]
public DateTime LastUse
{
set{ _lastuse=value;}
get{return _lastuse;}
}
/// <summary>
/// 状态 1:可用,0:不可用
/// </summary>
[Property]
public int State
{
set{ _state=value;}
get{return _state;}
}
/// <summary>
/// 备注
/// </summary>
[Property]
public string Remarks
{
set{ _remarks=value;}
get{return _remarks;}
}
#endregion Model
}
public static class MemCardOper
{
/// <summary>
///
/// </summary>
/// <param name="CardNumber">会员卡号</param>
/// <param name="ConsumptionAmount">消费金额</param>
/// <param name="TradeNo">交易号</param>
/// <returns></returns>
public static ReturnMessage MemCardHandle(string CardNumber, decimal ConsumptionAmount, string TradeNo)
{
ReturnMessage rm = new ReturnMessage();
List<string[]> liWhere = new List<string[]>();
liWhere.Add(new string[] { "CardNO = {0}", CardNumber });
MemberCard mc = new MemberCard();
DataTable dt = mc.GetDataSet("SELECT TOP 1 ID FROM MemberCard", liWhere);
string MbID;
if (dt.Rows.Count > 0)
{
MbID = dt.Rows[0][0].ToString();
mc.FindbyPK(MbID);
mc.Balance -= ConsumptionAmount;
mc.LastUse = DateTime.Now;
rm = mc.Update();
if (!rm.IsSucessed)
{
rm.Message += "更新会员卡信息出错!";
return rm;
}
else
{
ConsumptionRecords cr = new ConsumptionRecords();
cr.CardID = mc.ID;
cr.RecType = 0;
cr.Amount = ConsumptionAmount;
cr.TradeNo = TradeNo;
cr.OpeTime = DateTime.Now;
cr.Insert();
return rm;
}
}
else
{
rm.IsSucessed = false;
rm.Message = "读取会员卡信息出错!";
return rm;
}
}
}
}
<file_sep>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 WinApp.WinForm.Report;
using Service.Common.Data;
using Message.Model;
using System.Threading;
using Service.Common;
namespace WinApp.WinForm
{
public partial class FormShift : Form
{
Sale_Detail sd = new Sale_Detail();
Int32 ShiftID = 0;
public FormShift(Int32 shiftid)
{
ShiftID = shiftid;
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
dgvDetail.AutoGenerateColumns = false;
ucPage1.DataSetSql = "SELECT * FROM v_SaleList";
ucPage1.LiWhere.Add(new string[] { "State = {0}", "0" });
ucPage2.DataSetSql = "SELECT * FROM v_SaleDetailList";
ucPage2.LiWhere.Add(new string[] { "State = {0}", "0" });
GetLiWhere(ShiftID);
ucPage1.LiOrder.Add(new string[] { "Sale_ID", "DESC" });
dataGridView1.DataSource = ucPage1.GetDataTable();
ucPage2.LiOrder.Add(new string[] { "Sale_Detail_ID", "DESC" });
dgvDetail.DataSource = ucPage2.GetDataTable();
ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
ucPage2.PageEvent += new WinApp.Controls.PageEntrust(ucPage2_PageEvent);
Sale SaleInfo = new Sale();
DataTable dt = SaleInfo.GetDataSet("SELECT SUM(TotalAmount) AS Total,SUM(Cash) AS Cash,SUM(MemCard) AS MemCard,SUM(UnionPay) AS UnionPay,SUM(OtherPayment) AS OtherPayment FROM Sale", ucPage1.LiWhere);
lbTotalAmount.Text = dt.Rows[0]["Total"].ToString();
lbCash.Text = dt.Rows[0]["Cash"].ToString();
lbMembershipCard.Text = dt.Rows[0]["MemCard"].ToString();
lbUnionPay.Text = dt.Rows[0]["UnionPay"].ToString();
lbOther.Text = dt.Rows[0]["OtherPayment"].ToString();
DataTable dt1 = SaleInfo.GetDataSet("SELECT SUM(Commission) AS Commission FROM v_SaleDetailList", ucPage1.LiWhere);
lbCommission.Text = dt1.Rows[0][0].ToString();
ControlCommon.BindEmployee(cbServer);
DataTable dt2 = (DataTable)cbServer.DataSource;
DataRow dr = dt2.NewRow();
dr["Employee_ID"] = 0;
dr["Name"] = "<—全部—>";
dt2.Rows.InsertAt(dr, 0);
cbServer.SelectedIndex = 0;
ControlCommon.BindProduct(cbProName);
DataTable dt3 = (DataTable)cbProName.DataSource;
DataRow dr1 = dt3.NewRow();
dr1["Product_ID"] = 0;
dr1["Name"] = "<—全部—>";
dt3.Rows.InsertAt(dr1, 0);
cbProName.SelectedIndex = 0;
GetDtlTotalAmount();
}
void ucPage1_PageEvent()
{
dataGridView1.DataSource = ucPage1.GetDataTable();
}
void ucPage2_PageEvent()
{
dgvDetail.DataSource = ucPage2.GetDataTable();
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
FormSaleDetail fsd = new FormSaleDetail(Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Sale_ID"].Value));
fsd.ShowDialog(this);
}
private void btnShift_Click(object sender, EventArgs e)
{
if (((DataTable)(dataGridView1.DataSource)).Rows.Count > 0)
{
if (MessageBox.Show("确定要清帐交接吗?", "确定", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == DialogResult.Yes)
{
ShiftInfo si = new ShiftInfo();
DataSet ds = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 StartID,EndID,StartTime,EndTime FROM ShiftInfo ORDER BY ID DESC");
DataSet ds1 = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 Sale_ID,CheckoutTime FROM Sale WHERE Sale_ID > " + ds.Tables[0].Rows[0]["EndID"].ToString() + " AND State = 0 ORDER BY Sale_ID ASC");
DataSet ds2 = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 Sale_ID,CheckoutTime FROM Sale WHERE Sale_ID > " + ds.Tables[0].Rows[0]["EndID"].ToString() + " AND State = 0 ORDER BY Sale_ID DESC");
si.StartID = Convert.ToInt32(ds1.Tables[0].Rows[0]["Sale_ID"]);
si.StartTime = Convert.ToDateTime(ds1.Tables[0].Rows[0]["CheckoutTime"]);
si.EndID = Convert.ToInt32(ds2.Tables[0].Rows[0]["Sale_ID"]);
si.EndTime = Convert.ToDateTime(ds2.Tables[0].Rows[0]["CheckoutTime"]);
si.ShiftTime = DateTime.Now;
si.ShiftUser = Convert.ToInt32(Thread.CurrentPrincipal.Identity.Name);
si.Insert();
MessageBox.Show("操作成功!");
DialogResult = DialogResult.OK;
}
}
else
{
MessageBox.Show("没有销售记录不能交班!");
}
}
private void btnDtlSearch_Click(object sender, EventArgs e)
{
ucPage2.LiWhere.Clear();
ucPage2.LiWhere.Add(new string[] { "State = {0}", "0" });
GetLiWhere(ShiftID);
if (cbProName.SelectedValue.ToString() != "0")
{
ucPage2.LiWhere.Add(new string[] { "Product_ID ={0}", cbProName.SelectedValue.ToString() });
}
if (cbServer.SelectedValue.ToString() != "0")
{
ucPage2.LiWhere.Add(new string[] { "Employee_ID = {0}", cbServer.SelectedValue.ToString() });
}
if (tbxOrderNoDtl.Text.Trim() != "")
{
ucPage2.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNoDtl.Text.Trim() });
}
ucPage2.CurPage = 1;
dgvDetail.DataSource = ucPage2.GetDataTable();
GetDtlTotalAmount();
}
private void GetDtlTotalAmount()
{
DataTable dt = sd.GetDataSet("SELECT SUM(Total),SUM(Commission) FROM v_SaleDetailList", ucPage2.LiWhere);
if (dt.Rows[0][0] != System.DBNull.Value)
{
lbTotalAmountDtl.Text = (Convert.ToDecimal(dt.Rows[0][0])).ToString("f2") + " 元";
lbCommissionDtl.Text = (Convert.ToDecimal(dt.Rows[0][1])).ToString("f2") + " 元";
}
else
{
lbTotalAmountDtl.Text = "0 元";
lbCommissionDtl.Text = "0 元";
}
}
private void GetLiWhere(Int32 ShiftID)
{
if (ShiftID == 0)
{
DataSet ds = ExecuteSql.ExeComSqlForDataSet("SELECT TOP 1 StartID,EndID,StartTime,EndTime FROM ShiftInfo ORDER BY ID DESC");
ucPage1.LiWhere.Add(new string[] { "Sale_ID > {0}", ds.Tables[0].Rows[0]["EndID"].ToString() });
ucPage2.LiWhere.Add(new string[] { "Sale_ID > {0}", ds.Tables[0].Rows[0]["EndID"].ToString() });
}
else
{
ShiftInfo si = new ShiftInfo();
si.FindbyPK(ShiftID.ToString());
ucPage1.LiWhere.Add(new string[] { "Sale_ID >= {0}", si.StartID.ToString() });
ucPage1.LiWhere.Add(new string[] { "Sale_ID <= {0}", si.EndID.ToString() });
ucPage2.LiWhere.Add(new string[] { "Sale_ID >= {0}", si.StartID.ToString() });
ucPage2.LiWhere.Add(new string[] { "Sale_ID <= {0}", si.EndID.ToString() });
btnShift.Visible = false;
}
}
}
}
<file_sep>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 Message.Model;
using Service.Common;
namespace WinApp.WinForm.Admin
{
public partial class FormCreateCard : Form
{
MemberCard mc = new MemberCard();
public FormCreateCard()
{
InitializeComponent();
ControlCommon.BindCardType(cbCardType);
}
private void btnDetermine_Click(object sender, EventArgs e)
{
if (tbxCardNO.Text.Trim() == "")
{
MessageBox.Show("请填写卡号!");
tbxCardNO.Focus();
return;
}
if (this.tbxMemberName.Text.Trim() == "")
{
MessageBox.Show("请填写用户姓名!");
tbxMemberName.Focus();
return;
}
if (this.tbxUserTel.Text.Trim() == "")
{
MessageBox.Show("请填写电话!");
tbxUserTel.Focus();
return;
}
List<string[]> liWhere = new List<string[]>();
liWhere.Add(new string[] { "CardNO = {0}", tbxCardNO.Text });
if (mc.GetDataSetCount("SELECT ID FROM MemberCard", liWhere) > 0)
{
MessageBox.Show("该卡号已经存在!");
return;
}
mc.CardNO = tbxCardNO.Text;
mc.CardType = Convert.ToInt32(cbCardType.SelectedValue);
mc.MemberName = tbxMemberName.Text;
mc.UserTel = tbxUserTel.Text;
mc.PassWord = "";
mc.UserPic = "";
mc.Balance = 0;
mc.HandleTime = DateTime.Now;
mc.LastUse = DateTime.Now;
mc.State = 1;
mc.Remarks = tbxRemarks.Text;
if (mc.Insert().IsSucessed)
{
MessageBox.Show("办卡成功!");
DialogResult = DialogResult.OK;
}
}
private void btnCancle_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}
<file_sep>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;
namespace WinApp.WinForm.Report
{
public partial class FormSaleList : Form
{
public FormSaleList()
{
InitializeComponent();
dataGridView1.AutoGenerateColumns = false;
dataGridView2.AutoGenerateColumns = false;
}
private void FormSaleList_Load(object sender, EventArgs e)
{
ucPage1.DataSetSql = "SELECT * FROM v_SaleList";
ucPage1.LiWhere.Add(new string[] { "State = {0}", "0" });
ucPage1.LiOrder.Add(new string[] { "Sale_ID", "DESC" });
dataGridView1.DataSource = ucPage1.GetDataTable();
ucPage2.DataSetSql = "SELECT ID,StartTime,EndTime,ShiftUser,Name,ShiftTime,'~' AS WaveLine FROM ShiftInfo LEFT JOIN Employee ON ShiftUser = Employee_ID";
//ucPage2.LiWhere.Add(new string[] { "1={0}", "1" });
ucPage2.LiOrder.Add(new string[] { "y.ID", "DESC" });
dataGridView2.DataSource = ucPage2.GetDataTable();
ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
ucPage2.PageEvent += new WinApp.Controls.PageEntrust(ucPage2_PageEvent);
}
void ucPage1_PageEvent()
{
dataGridView1.DataSource = ucPage1.GetDataTable();
}
void ucPage2_PageEvent()
{
dataGridView2.DataSource = ucPage2.GetDataTable();
}
private void btnSearch_Click(object sender, EventArgs e)
{
ucPage1.LiWhere.Clear();
ucPage1.LiWhere.Add(new string[] { "State = {0}", "0" });
if (dtpFrom.Checked)
{
ucPage1.LiWhere.Add(new string[] { "CheckoutTime > {0}", dtpFrom.Value.ToShortDateString() });
}
if (dtpTo.Checked)
{
ucPage1.LiWhere.Add(new string[] { "CheckoutTime < {0}", dtpTo.Value.AddDays(1).ToShortDateString() });
}
if (tbxTradCode.Text.Trim() != "")
{
ucPage1.LiWhere.Add(new string[] { "TradeNo LIKE '%' + {0} + '%'", tbxTradCode.Text.Trim() });
}
if (tbxOrderNo.Text.Trim() != "")
{
ucPage1.LiWhere.Add(new string[] { "OrderNo LIKE '%' + {0} + '%'", tbxOrderNo.Text.Trim() });
}
ucPage1.CurPage = 1;
dataGridView1.DataSource = ucPage1.GetDataTable();
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
FormSaleDetail fsd = new FormSaleDetail(Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["Sale_ID"].Value));
fsd.ShowDialog(this);
}
private void dataGridView2_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
FormShift fs = new FormShift(Convert.ToInt32(dataGridView2.Rows[dataGridView2.CurrentCell.RowIndex].Cells["ShiftID"].Value));
fs.ShowDialog();
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// Product:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("Product")]
public partial class Product : EntityBase<Product>
{
public Product()
{}
#region Model
private int _product_id;
private string _code;
private int _productlist_id;
private string _name;
private string _shortname;
private string _spell;
private string _s_spell;
private int _productspec_id;
private int _productunit_id;
private decimal _price;
private decimal _offering_price;
private decimal _commission;
private int _employee_id;
private DateTime _createdate= DateTime.Now;
private string _remark;
/// <summary>
/// ID
/// </summary>
[PrimaryKey("Product_ID", IsAuto = true)]
public int Product_ID
{
set{ _product_id=value;}
get{return _product_id;}
}
/// <summary>
/// 商品编号
/// </summary>
[Property]
public string Code
{
set{ _code=value;}
get{return _code;}
}
/// <summary>
///
/// </summary>
[Property]
public int ProductList_ID
{
set{ _productlist_id=value;}
get{return _productlist_id;}
}
/// <summary>
/// 商品名称
/// </summary>
[Property]
public string Name
{
set{ _name=value;}
get{return _name;}
}
/// <summary>
/// 名称简写
/// </summary>
[Property]
public string shortname
{
set{ _shortname=value;}
get{return _shortname;}
}
/// <summary>
/// 拼音全拼
/// </summary>
[Property]
public string spell
{
set{ _spell=value;}
get{return _spell;}
}
/// <summary>
/// 拼音简写
/// </summary>
[Property]
public string s_spell
{
set{ _s_spell=value;}
get{return _s_spell;}
}
/// <summary>
/// 部门ID
/// </summary>
[Property]
public int ProductSpec_ID
{
set{ _productspec_id=value;}
get{return _productspec_id;}
}
/// <summary>
/// 类型ID
/// </summary>
[Property]
public int ProductUnit_ID
{
set{ _productunit_id=value;}
get{return _productunit_id;}
}
/// <summary>
/// 价格
/// </summary>
[Property]
public decimal Price
{
set{ _price=value;}
get{return _price;}
}
/// <summary>
/// 折扣价格
/// </summary>
[Property]
public decimal Offering_Price
{
set{ _offering_price=value;}
get{return _offering_price;}
}
/// <summary>
/// 提成
/// </summary>
[Property]
public decimal Commission
{
get { return _commission; }
set { _commission = value; }
}
/// <summary>
/// 操作员
/// </summary>
[Property]
public int Employee_ID
{
set{ _employee_id=value;}
get{return _employee_id;}
}
/// <summary>
/// 创建日期
/// </summary>
[Property]
public DateTime CreateDate
{
set{ _createdate=value;}
get{return _createdate;}
}
/// <summary>
/// 备注
/// </summary>
[Property]
public string Remark
{
set{ _remark=value;}
get{return _remark;}
}
#endregion Model
}
}
<file_sep>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 Service.Common.Data;
namespace WinApp
{
public partial class test : Form
{
public test()
{
InitializeComponent();
}
private void test_Load(object sender, EventArgs e)
{
dataGridView1.AutoGenerateColumns = false;
DataGridViewComboBoxColumn dgvComboBoxColumn = (DataGridViewComboBoxColumn)this.dataGridView1.Columns["Discount"];
dgvComboBoxColumn.DataPropertyName = "Discount";
dgvComboBoxColumn.DataSource = ExecuteSql.ExeComSqlForDataSet("SELECT DiscountRate,DisName FROM Discount WHERE Available = 1").Tables[0];
dgvComboBoxColumn.DisplayMember = "DisName";
dgvComboBoxColumn.ValueMember = "DiscountRate";
DataTable dt = ExecuteSql.ExeComSqlForDataSet("SELECT * FROM dbo.v_SaleDetailList WHERE SaleOrder_ID = 88").Tables[0];
dataGridView1.DataSource = dt;
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
decimal TotalAmount = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
TotalAmount += Convert.ToDecimal(dataGridView1.Rows[i].Cells["PaidIn"].Value);
}
//lbTotal.Text = TotalAmount.ToString();
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
}
}
<file_sep>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 Service.Common.Data;
using Message.Model;
using Service.Common;
namespace WinApp.WinForm.Admin
{
public partial class FormAdmin : Form
{
Discount dct = new Discount();
CardType ct = new CardType();
public FormAdmin()
{
InitializeComponent();
}
private void tabPage1_Enter(object sender, EventArgs e)
{
dgvEmployee.AutoGenerateColumns = false;
ucPage1.DataSetSql = "SELECT * FROM Employee";
ucPage1.LiOrder.Add(new string[] { "Employee_ID", "ASC" });
ucPage2.LiOrder.Add(new string[] { "Product_ID", "DESC" });
dgvEmployee.DataSource = ucPage1.GetDataTable();
ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
}
void ucPage1_PageEvent()
{
dgvEmployee.DataSource = ucPage1.GetDataTable();
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
FormEmpDtl fed = new FormEmpDtl(Convert.ToInt32(dgvEmployee.Rows[dgvEmployee.CurrentCell.RowIndex].Cells["Employee_ID"].Value));
if (fed.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("修改成功!");
dgvEmployee.DataSource = ucPage1.GetDataTable();
}
}
private void btnNewUser_Click(object sender, EventArgs e)
{
FormEmpDtl fed = new FormEmpDtl(0);
if (fed.ShowDialog() == DialogResult.OK)
{
MessageBox.Show("保存成功!");
dgvEmployee.DataSource = ucPage1.GetDataTable();
}
}
private void tabPage2_Enter(object sender, EventArgs e)
{
dgvProduct.AutoGenerateColumns = false;
ucPage2.DataSetSql = "SELECT * FROM Product";
dgvProduct.DataSource = ucPage2.GetDataTable();
ucPage2.PageEvent += new WinApp.Controls.PageEntrust(ucPage2_PageEvent);
}
void ucPage2_PageEvent()
{
dgvProduct.DataSource = ucPage2.GetDataTable();
}
private void dgvProduct_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
FormProdDtl fpd = new FormProdDtl(Convert.ToInt32(dgvProduct.Rows[dgvProduct.CurrentCell.RowIndex].Cells["Product_ID"].Value));
if (fpd.ShowDialog() == DialogResult.OK)
{
dgvProduct.DataSource = ucPage2.GetDataTable();
}
}
private void button1_Click(object sender, EventArgs e)
{
FormProdDtl fpd = new FormProdDtl(0);
if (fpd.ShowDialog() == DialogResult.OK)
{
dgvProduct.DataSource = ucPage2.GetDataTable();
}
}
private void tabPage3_Enter(object sender, EventArgs e)
{
BindDiscount();
}
private void BindDiscount()
{
dgvDiscount.AutoGenerateColumns = false;
DataSet dsDiscount = ExecuteSql.ExeComSqlForDataSet("SELECT * FROM Discount");
dgvDiscount.DataSource = dsDiscount.Tables[0];
}
private void dgvDiscount_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (e.RowIndex >= dgvDiscount.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dgvDiscount.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
private void dgvDiscount_SelectionChanged(object sender, EventArgs e)
{
getDiscountDtl();
}
private void getDiscountDtl()
{
dct.FindbyPK(dgvDiscount.Rows[dgvDiscount.CurrentCell.RowIndex].Cells["DiscountID"].Value.ToString());
tbxDisName.Text = dct.DisName;
tbxDiscountRate.Text = dct.DiscountRate.ToString("f2");
if (dct.Available)
{
rbAvailable.Checked = true;
}
else
{
rbNotAvailable.Checked = true;
}
}
private void btnSaveDiscount_Click(object sender, EventArgs e)
{
Int32 selectRow = 0;
if (dgvDiscount.CurrentCell.RowIndex >= 0)
{
selectRow = dgvDiscount.CurrentCell.RowIndex;
}
dct.FindbyPK(dgvDiscount.Rows[dgvDiscount.CurrentCell.RowIndex].Cells["DiscountID"].Value.ToString());
dct.DisName = tbxDisName.Text;
dct.DiscountRate = Convert.ToDecimal(tbxDiscountRate.Text);
if (rbAvailable.Checked)
{
dct.Available = true;
}
else
{
dct.Available = false;
}
dct.Update();
BindDiscount();
dgvDiscount.CurrentCell = dgvDiscount[0, selectRow];
getDiscountDtl();
}
private void tbxDiscountRate_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void btnAddDiscount_Click(object sender, EventArgs e)
{
FormAddDiscount fad = new FormAddDiscount();
fad.ShowDialog();
BindDiscount();
}
private void tabPage4_Enter(object sender, EventArgs e)
{
BindCardType();
}
private void BindCardType()
{
dgvCardType.AutoGenerateColumns = false;
DataSet dsCardType = ExecuteSql.ExeComSqlForDataSet("SELECT ID, TypeName, Discount, CASE Available WHEN 1 THEN '可用' WHEN 0 THEN '不可用' END AS Available FROM CardType");
dgvCardType.DataSource = dsCardType.Tables[0];
ControlCommon.BindDiscount(cbDiscount);
}
private void dgvCardType_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (e.RowIndex >= dgvCardType.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dgvCardType.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
private void dgvCardType_SelectionChanged(object sender, EventArgs e)
{
getCardTypeDtl();
}
private void getCardTypeDtl()
{
ct.FindbyPK(dgvCardType.Rows[dgvCardType.CurrentCell.RowIndex].Cells["CardTypeID"].Value.ToString());
tbxCardTypeName.Text = ct.TypeName;
cbDiscount.SelectedValue = ct.Discount;
if (ct.Available == 1)
{
rbctAvailable.Checked = true;
}
else
{
rbctNotAvailable.Checked = true;
}
}
private void btnCreateType_Click(object sender, EventArgs e)
{
FormCreateCardType fcct = new FormCreateCardType();
if (fcct.ShowDialog() == DialogResult.OK)
{
BindCardType();
}
}
private void btnSaveCardType_Click(object sender, EventArgs e)
{
Int32 selectRow = 0;
if (dgvCardType.CurrentCell.RowIndex >= 0)
{
selectRow = dgvCardType.CurrentCell.RowIndex;
}
ct.FindbyPK(dgvCardType.Rows[dgvCardType.CurrentCell.RowIndex].Cells["CardTypeID"].Value.ToString());
ct.TypeName = tbxCardTypeName.Text;
ct.Discount = Convert.ToDecimal(cbDiscount.SelectedValue);
if (rbctAvailable.Checked)
{
ct.Available = 1;
}
else
{
ct.Available = 0;
}
ct.Update();
BindCardType();
dgvCardType.CurrentCell = dgvCardType[0, selectRow];
getCardTypeDtl();
}
private void btnSearch_Click(object sender, EventArgs e)
{
ucPage2.LiWhere.Clear();
if (!string.IsNullOrEmpty(tbxProCode.Text.Trim()))
{
ucPage2.LiWhere.Add(new string[] { "Code LIKE '%' + {0} + '%'", tbxProCode.Text.Trim() });
}
if (!string.IsNullOrEmpty(tbxProName.Text.Trim()))
{
ucPage2.LiWhere.Add(new string[] { "Name LIKE '%' + {0} + '%'", tbxProName.Text.Trim() });
}
if (!string.IsNullOrEmpty(tbxPinYin.Text.Trim()))
{
ucPage2.LiWhere.Add(new string[] { "(spell LIKE '%' + {0} + '%' OR s_spell LIKE '%' + {0} + '%')", tbxPinYin.Text.Trim() });
}
dgvProduct.DataSource = ucPage2.GetDataTable();
}
private void tbxProCode_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDigital(e);
}
}
}
<file_sep>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 Message.Model;
using Service.Common;
namespace WinApp.WinForm
{
public partial class FormCashier : Form
{
Sale SaleInfo = new Sale();
PaymentInfo paymentInfo = new PaymentInfo();
public PaymentInfo PaymentInfo
{
get { return paymentInfo; }
set { paymentInfo = value; }
}
public FormCashier(Int32 Sale_ID)
{
InitializeComponent();
SaleInfo.FindbyPK(Sale_ID.ToString());
tbxAmount.Text = SaleInfo.TotalAmount.ToString("f2");
tbxCash.Text = SaleInfo.TotalAmount.ToString("f2");
}
private void btnEnter_Click(object sender, EventArgs e)
{
if (tbxAmount.Text.Trim()!="")
{
if (Convert.ToDecimal(tbxAmount.Text) == Convert.ToDecimal(tbxCash.Text) + Convert.ToDecimal(tbxUnionPay.Text) + Convert.ToDecimal(tbxOtherPayment.Text) + Convert.ToDecimal(tbxCardPayment.Text))
{
paymentInfo.TotalAmount = Convert.ToDecimal(tbxAmount.Text);
paymentInfo.Cash = Convert.ToDecimal(tbxCash.Text);
paymentInfo.UnionPay = Convert.ToDecimal(tbxUnionPay.Text);
paymentInfo.OtherPayment = Convert.ToDecimal(tbxOtherPayment.Text);
paymentInfo.MemCard = Convert.ToDecimal(tbxCardPayment.Text);
this.DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("消费数额填写有误!");
}
}
else
{
MessageBox.Show("请填写消费金额!");
}
}
private void btnChooseCard_Click(object sender, EventArgs e)
{
if (tbxAmount.Text.Trim()!="")
{
FormMemCard fmc = new FormMemCard(Convert.ToDecimal(tbxAmount.Text));
if (fmc.ShowDialog() == DialogResult.OK)
{
tbxCardPayment.Text = fmc.PaymentCard.ToString("f2");
ClearAllText();
tbxCash.Text = (Convert.ToDecimal(tbxAmount.Text) - Convert.ToDecimal(tbxCardPayment.Text)).ToString("f2");
lbCardNo.Text = "No:" + fmc.CardNo;
paymentInfo.Account = fmc.CardNo;
lbCardNo.Visible = true;
}
}
else
{
MessageBox.Show("请填写消费金额!");
}
}
private void ClearAllText()
{
tbxCash.Text = "0.00";
tbxUnionPay.Text = "0.00";
tbxOtherPayment.Text = "0.00";
}
private void tbxAmount_KeyUp(object sender, KeyEventArgs e)
{
if (tbxAmount.Text.Trim()!="")
{
ClearAllText();
decimal cash = Convert.ToDecimal(tbxAmount.Text) - Convert.ToDecimal(tbxCardPayment.Text);
if (cash >= 0)
{
tbxCash.Text = cash.ToString("f2");
}
tbxAmount.Focus();
}
else
{
ClearAllText();
tbxAmount.Focus();
}
}
private void tbxAmount_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void tbxCash_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void tbxUnionPay_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
private void tbxOtherPayment_KeyPress(object sender, KeyPressEventArgs e)
{
ControlCommon.VerDecimal(sender, e);
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// UserRole:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("UserRole")]
public partial class UserRole : EntityBase<UserRole>
{
public UserRole()
{}
#region Model
private int _roleid;
private int _rights;
/// <summary>
///
/// </summary>
[Property]
public int RoleId
{
set { _roleid = value; }
get { return _roleid; }
}
/// <summary>
///
/// </summary>
[Property]
public int Rights
{
set{ _rights=value;}
get{return _rights;}
}
#endregion Model
}
}
<file_sep>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.Configuration;
namespace WinApp.WinForm
{
public partial class FormBackPassword : Form
{
public FormBackPassword()
{
InitializeComponent();
}
private void btnDetermine_Click(object sender, EventArgs e)
{
if (tbxBackPwd.Text != "")
{
if (ConfigurationManager.AppSettings.Get("BackPwd") == tbxBackPwd.Text.Trim())
{
DialogResult = DialogResult.OK;
}
else
{
lbWrongPwd.Visible = true;
}
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.Cancel;
}
}
}<file_sep>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 Message.Model;
using System.Threading;
using Service.Common;
namespace WinApp.WinForm.Admin
{
public partial class FormSetting : Form
{
public FormSetting()
{
InitializeComponent();
}
private void btnDetermine_Click(object sender, EventArgs e)
{
Employee emp = new Employee();
emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
if (tbxOriginalPwd.Text.Trim() != "")
{
if (DecryptEncrypt.EncryptText(tbxOriginalPwd.Text) == emp.PassWord)
{
if (tbxNewPwd.Text.Trim() != "")
{
if (tbxNewPwdConfirm.Text.Trim() != "")
{
if (tbxNewPwd.Text.Trim() == tbxNewPwdConfirm.Text.Trim())
{
emp.PassWord = DecryptEncrypt.EncryptText(tbxNewPwd.Text.Trim());
emp.Update();
MessageBox.Show("密码修改成功!");
Close();
}
else
{
MessageBox.Show("两次新密码不一样!");
}
}
else
{
MessageBox.Show("请填写确认新密码!");
tbxNewPwdConfirm.Focus();
}
}
else
{
MessageBox.Show("请填写新密码!");
tbxNewPwd.Focus();
}
}
else
{
MessageBox.Show("原密码不正确!");
tbxOriginalPwd.Focus();
}
}
else
{
MessageBox.Show("请填写原密码!");
tbxOriginalPwd.Focus();
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
Close();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WinApp.Controls
{
public delegate void EventEntrust(object sender, Int32 e);
public partial class UCCustomer : UserControl
{
public event EventEntrust MyEvent;
private Int32 saleID;
private string custemerNo;
private string storeHouse_ID;
private string employee_ID;
private DateTime saleDate;
public Int32 SaleID
{
get { return saleID; }
set { saleID = value; }
}
public string CustemerNo
{
get { return custemerNo; }
set { custemerNo = value; }
}
public string StoreHouse_ID
{
get { return storeHouse_ID; }
set { storeHouse_ID = value; }
}
public string Employee_ID
{
get { return employee_ID; }
set { employee_ID = value; }
}
public DateTime SaleDate
{
get { return saleDate; }
set { saleDate = value; }
}
public UCCustomer()
{
InitializeComponent();
}
private void UCCustomer_Load(object sender, EventArgs e)
{
this.lbCustomer.Text = custemerNo;
this.lbRoom.Text = storeHouse_ID;
this.lbOperater.Text = employee_ID;
this.lbSaleTime.Text = saleDate.ToString("yyyy-MM-dd HH:mm:ss");
}
private void UCCustomer_MouseEnter(object sender, EventArgs e)
{
this.BackColor = Color.AliceBlue;
this.BorderStyle = BorderStyle.Fixed3D;
}
private void UCCustomer_MouseLeave(object sender, EventArgs e)
{
this.BackColor = Color.WhiteSmoke;
this.BorderStyle = BorderStyle.FixedSingle;
}
private void UCCustomer_Click(object sender, EventArgs e)
{
MyEvent(this, SaleID);
}
private void lbCustomer_Click(object sender, EventArgs e)
{
MyEvent(this, SaleID);
}
private void lbCustomer_MouseMove(object sender, MouseEventArgs e)
{
this.BackColor = Color.AliceBlue;
this.BorderStyle = BorderStyle.Fixed3D;
}
private void lbCustomer_MouseLeave(object sender, EventArgs e)
{
this.BackColor = Color.WhiteSmoke;
this.BorderStyle = BorderStyle.FixedSingle;
}
}
}
<file_sep>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 Service.Common.Data;
using Service.Common.Log;
namespace WinApp.WinForm
{
public partial class FormDataBackup : Form
{
ReturnMessage rm = new ReturnMessage();
string BackPath;
public ReturnMessage Rm
{
get { return rm; }
set { rm = value; }
}
public FormDataBackup(string backPath)
{
InitializeComponent();
BackPath = backPath;
}
private void FormDataBackup_Load(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
string strTime = string.Format("{0:yyyy-MM-dd@HH:mm:ss}", DateTime.Now);
StringBuilder strSql = new StringBuilder();
strSql.Append("backup database Message to disk = '" + BackPath + strTime + ".bak" + "'");
Int32 BackupNum = 0;
try
{
BackupNum = ExecuteSql.ExeComSqlForNonQuery(strSql.ToString());
rm.Message = "备份成功!";
rm.IsSucessed = true;
}
catch (Exception ex)
{
rm.Message = "备份失败!" + ex.Message;
rm.IsSucessed = false;
}
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
if (rm.IsSucessed)
{
DialogResult = DialogResult.OK;
}
else
{
DialogResult = DialogResult.No;
}
}
}
}
<file_sep>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 Service.Common;
using Message.Model;
namespace WinApp.WinForm.Admin
{
public partial class FormCreateCardType : Form
{
CardType ct = new CardType();
public FormCreateCardType()
{
InitializeComponent();
ControlCommon.BindDiscount(cbDiscount);
}
private void btnSave_Click(object sender, EventArgs e)
{
if (tbxctName.Text.Trim() == "")
{
MessageBox.Show("请填写名称!");
tbxctName.Focus();
return;
}
ct.TypeName = tbxctName.Text;
ct.Discount = Convert.ToDecimal(cbDiscount.SelectedValue);
ct.Available = 1;
if (ct.Insert().IsSucessed)
{
MessageBox.Show("添加成功!");
DialogResult = DialogResult.OK;
}
else
{
MessageBox.Show("添加失败!");
DialogResult = DialogResult.No;
}
}
private void btnCancel_Click(object sender, EventArgs e)
{
DialogResult = DialogResult.No;
}
}
}
<file_sep>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 Message.Model;
using Service.Common.Data;
namespace WinApp.WinForm
{
public partial class FormMergeBill : Form
{
Sale SaleInfo = new Sale();
Int32 OriginalID;
Int32 MergerID;
public FormMergeBill(Int32 originalID)
{
InitializeComponent();
OriginalID = originalID;
dataGridView1.AutoGenerateColumns = false;
}
private void btnSearch_Click(object sender, EventArgs e)
{
if (tbxCustemerNo.Text.Trim() != "")
{
if (tbxCustemerNo.Text.Trim() != OriginalID.ToString())
{
LoadInfo(Convert.ToInt32(tbxCustemerNo.Text));
}
else
{
MessageBox.Show("不能和自己合并!");
}
}
}
private void LoadInfo(Int32 CustomerNo)
{
List<string[]> liWhere = new List<string[]>();
liWhere.Add(new string[] { "Customer = {0}", CustomerNo.ToString() });
liWhere.Add(new string[] { "State = {0}", "1" });
DataTable CusDt = SaleInfo.GetDataSet("SELECT TOP 1 Sale_ID FROM Sale", liWhere);
if (CusDt.Rows.Count > 0)
{
MergerID = Convert.ToInt32(CusDt.Rows[0][0]);
SaleInfo.FindbyPK(MergerID.ToString());
lbCanNotFind.Visible = false;
}
else
{
lbCanNotFind.Visible = true;
return;
}
List<string[]> where = new List<string[]>();
List<string[]> order = new List<string[]>();
where.Add(new string[] { "SaleOrder_ID = {0}", MergerID.ToString() });
order.Add(new string[] { "a.Sale_Dtl_Time", "ASC" });
DataTable dt = SaleInfo.GetDataSet("SELECT b.Product_ID,b.Code,b.Name,convert(numeric(18,2),a.Price) AS PaidIn,convert(numeric(18,2),b.Price) AS Price,convert(numeric(18,2),a.Quantity) AS Quantity,convert(numeric(18,2),a.Price/b.Price) AS Discount, convert(numeric(18,2),a.Price*a.Quantity) AS Total,a.Employee_ID FROM Sale_Detail a LEFT JOIN Product b ON b.Product_ID = a.Product_ID", where, order);
dataGridView1.DataSource = dt;
}
private void btnDetermine_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count > 0)
{
if (MessageBox.Show("确认合并吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
{
Int32 result = ExecuteSql.ExeComSqlForNonQuery("UPDATE Sale_Detail SET SaleOrder_ID = " + OriginalID + " WHERE SaleOrder_ID = " + MergerID);
if (result == dataGridView1.Rows.Count)
{
DialogResult = DialogResult.OK;
List<string> strDel = new List<string>();
strDel.Add(SaleInfo.Sale_ID.ToString());
SaleInfo.Delete(strDel);
}
else
{
MessageBox.Show("合并失败!");
DialogResult = DialogResult.No;
}
}
}
}
private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
if (e.RowIndex >= dataGridView1.FirstDisplayedScrollingRowIndex)
{
using (SolidBrush b = new SolidBrush(dataGridView1.RowHeadersDefaultCellStyle.ForeColor))
{
int linen = 0;
linen = e.RowIndex + 1;
string line = linen.ToString();
e.Graphics.DrawString(line, e.InheritedRowStyle.Font, b, e.RowBounds.Location.X, e.RowBounds.Location.Y + 5);
SolidBrush B = new SolidBrush(Color.Red);
}
}
}
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
decimal TotalAmount = 0;
for (int i = 0; i < dataGridView1.Rows.Count; i++)
{
TotalAmount += Convert.ToDecimal(dataGridView1.Rows[i].Cells["Total"].Value);
}
lbTotal.Text = TotalAmount.ToString();
}
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// ConsumptionRecords:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("ConsumptionRecords")]
public partial class ConsumptionRecords : EntityBase<ConsumptionRecords>
{
public ConsumptionRecords()
{}
#region Model
private int _id;
private int _cardid;
private int _rectype;
private decimal _amount;
private DateTime _opetime;
private string _tradeno;
/// <summary>
///
/// </summary>
[PrimaryKey("ID", IsAuto = true)]
public int ID
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
[Property]
public int CardID
{
set{ _cardid=value;}
get{return _cardid;}
}
/// <summary>
/// 消费类型 0:消费,1:充值
/// </summary>
[Property]
public int RecType
{
set{ _rectype=value;}
get{return _rectype;}
}
/// <summary>
///
/// </summary>
[Property]
public decimal Amount
{
set{ _amount=value;}
get{return _amount;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime OpeTime
{
set{ _opetime=value;}
get{return _opetime;}
}
/// <summary>
///
/// </summary>
[Property]
public string TradeNo
{
set{ _tradeno=value;}
get{return _tradeno;}
}
#endregion Model
}
}
<file_sep>using System;
using Service.Common.Entity;
namespace Message.Model
{
/// <summary>
/// ShiftInfo:实体类(属性说明自动提取数据库字段的描述信息)
/// </summary>
[TableAttribute("ShiftInfo")]
public partial class ShiftInfo : EntityBase<ShiftInfo>
{
public ShiftInfo()
{}
#region Model
private int _id;
private int _startid;
private int _endid;
private DateTime _starttime;
private DateTime _endtime;
private int _shiftuser;
private DateTime _shiftTime;
/// <summary>
///
/// </summary>
[PrimaryKey("ID", IsAuto = true)]
public int ID
{
set{ _id=value;}
get{return _id;}
}
/// <summary>
///
/// </summary>
[Property]
public int StartID
{
set{ _startid=value;}
get{return _startid;}
}
/// <summary>
///
/// </summary>
[Property]
public int EndID
{
set{ _endid=value;}
get{return _endid;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime StartTime
{
set{ _starttime=value;}
get{return _starttime;}
}
/// <summary>
///
/// </summary>
[Property]
public DateTime EndTime
{
set{ _endtime=value;}
get{return _endtime;}
}
/// <summary>
///
/// </summary>
[Property]
public int ShiftUser
{
set{ _shiftuser=value;}
get{return _shiftuser;}
}
/// <summary>
/// 交班时间
/// </summary>
[Property]
public DateTime ShiftTime
{
get { return _shiftTime; }
set { _shiftTime = value; }
}
#endregion Model
}
}
<file_sep>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 Message.Model;
using System.Threading;
namespace WinApp.WinForm.Admin
{
public partial class FormMembershipCard : Form
{
public FormMembershipCard()
{
InitializeComponent();
}
private void btnSearch_Click(object sender, EventArgs e)
{
ucPage1.LiWhere.Clear();
if (tbxCardNo.Text.Trim()!="")
{
ucPage1.LiWhere.Add(new string[] { "CardNO = {0}", tbxCardNo.Text.Trim() });
}
if (tbxMemName.Text.Trim()!="")
{
ucPage1.LiWhere.Add(new string[] { "MemberName = {0}", tbxMemName.Text.Trim() });
}
if (tbxMemTel.Text.Trim() != "")
{
ucPage1.LiWhere.Add(new string[] { "UserTel = {0}", tbxMemTel.Text.Trim() });
}
dataGridView1.DataSource = ucPage1.GetDataTable();
}
private void FormMembershipCard_Load(object sender, EventArgs e)
{
ucPage1.DataSetSql = "SELECT CardType.TypeName, MemberCard.ID, MemberCard.CardNO, MemberCard.MemberName, MemberCard.UserTel, MemberCard.Balance, MemberCard.HandleTime FROM MemberCard LEFT OUTER JOIN CardType ON MemberCard.CardType = CardType.ID";
ucPage1.LiOrder.Add(new string[] { "HandleTime", "DESC" });
dataGridView1.DataSource = ucPage1.GetDataTable();
ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
Employee emp = new Employee();
emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
if (emp.Dept_ID != 0)
{
btnHandleCard.Enabled = false;
}
}
void ucPage1_PageEvent()
{
dataGridView1.DataSource = ucPage1.GetDataTable();
}
private void dataGridView1_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
{
FormMemCardDtl fmc = new FormMemCardDtl(Convert.ToInt32(dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Cells["ID"].Value));
if (fmc.ShowDialog()==DialogResult.OK)
{
dataGridView1.DataSource = ucPage1.GetDataTable();
}
}
private void btnCancle_Click(object sender, EventArgs e)
{
Close();
}
private void btnHandleCard_Click(object sender, EventArgs e)
{
FormCreateCard fcc = new FormCreateCard();
if (fcc.ShowDialog() == DialogResult.OK)
{
ucPage1.LiWhere.Clear();
dataGridView1.DataSource = ucPage1.GetDataTable();
}
}
}
}
<file_sep>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 Message.Model;
using Service.Common;
using System.Threading;
namespace WinApp.WinForm.Admin
{
public partial class FormMemCardDtl : Form
{
MemberCard CardInfo = new MemberCard();
Int32 CardID;
public FormMemCardDtl(Int32 cardId)
{
InitializeComponent();
CardID = cardId;
GetMemberInfo();
Employee emp = new Employee();
emp.FindbyPK(Thread.CurrentPrincipal.Identity.Name);
if (emp.Dept_ID != 0)
{
btnRecharge.Enabled = false;
btnSave.Enabled = false;
}
}
private void GetMemberInfo()
{
CardInfo.FindbyPK(CardID.ToString());
tbxCardNo.Text = CardInfo.CardNO;
tbxMemberName.Text = CardInfo.MemberName;
ControlCommon.BindCardType(cbCardType);
cbCardType.SelectedValue = CardInfo.CardType.ToString();
tbxUserTel.Text = CardInfo.UserTel;
tbxHandleTime.Text = CardInfo.HandleTime.ToString("yyyy-M-d HH:mm:ss");
tbxLastUse.Text = CardInfo.LastUse.ToString("yyyy-M-d HH:mm:ss");
tbxBalance.Text = CardInfo.Balance.ToString("f2");
tbxRemarks.Text = CardInfo.Remarks;
dataGridView1.AutoGenerateColumns = false;
ucPage1.DataSetSql = "SELECT ID, CardID, CASE RecType WHEN 0 THEN '消费' WHEN 1 THEN '充值' END AS RecType, Amount, OpeTime, TradeNo FROM ConsumptionRecords";
ucPage1.LiWhere.Add(new string[] { "CardID = {0}", CardID.ToString() });
ucPage1.LiOrder.Add(new string[] { "OpeTime", "DESC" });
dataGridView1.DataSource = ucPage1.GetDataTable();
ucPage1.PageEvent += new WinApp.Controls.PageEntrust(ucPage1_PageEvent);
}
void ucPage1_PageEvent()
{
dataGridView1.DataSource = ucPage1.GetDataTable();
}
private void btnSave_Click(object sender, EventArgs e)
{
if (tbxMemberName.Text.Trim() == "")
{
MessageBox.Show("请填写用户名!");
tbxMemberName.Focus();
return;
}
if (tbxUserTel.Text.Trim() == "")
{
MessageBox.Show("请填写联系电话!");
tbxUserTel.Focus();
return;
}
CardInfo.MemberName = tbxMemberName.Text;
CardInfo.UserTel = tbxUserTel.Text;
CardInfo.CardType = Convert.ToInt32(cbCardType.SelectedValue);
CardInfo.Remarks = tbxRemarks.Text;
CardInfo.Update();
MessageBox.Show("保存成功!");
DialogResult = DialogResult.OK;
}
private void btnRecharge_Click(object sender, EventArgs e)
{
FormRecharge fr = new FormRecharge(CardInfo.ID);
if (fr.ShowDialog()==DialogResult.OK)
{
GetMemberInfo();
}
}
private void btnReturn_Click(object sender, EventArgs e)
{
Close();
}
}
}
| 22c93941da36acd0c45f512d524d4ba574a0c487 | [
"C#"
] | 41 | C# | dmulxw/Message | d04365aaa958acc381d1ec9849e86b255a51aa7b | 501d87c54796792bdcf2598e655ba040959a6ad8 | |
refs/heads/master | <file_sep>jee-angular-todo
A very light-weight introductory project to Angular 1.x that utilizes Material Design.
Keywords: Angular, Angular 1.x, REST, Maven, Material
If you'd like to read more about this project, please see my blog: http://blog.danwatling.com<file_sep>angular.module('todo').controller('HomeController',
function($scope, $log, TodoService) {
$scope.data = [];
$scope.refreshState = function() {
TodoService.get().then(function(data) {
$scope.data = data;
});
};
$scope.doAddItem = function() {
TodoService.add($scope.text).then(function() {
$scope.refreshState();
$scope.text = '';
});
};
$scope.doUpdateItem = function(item) {
TodoService.update(item.id, item.text).then(function() {
$scope.refreshState();
});
};
$scope.clickSave = function() {
$scope.doAddItem();
};
$scope.clickUpdate = function(item) {
$scope.doUpdateItem(item);
};
$scope.clickEdit = function(item) {
item.isEditing = true;
};
$scope.clickDelete = function(item) {
TodoService.remove(item.id).then(function() {
$scope.refreshState();
});
};
$scope.refreshState();
}
);<file_sep>angular.module('todo').service('TodoService',
function TodoService($http, $q) {
var API_ROOT = '/todo/api/todo';
this.get = function() {
return $http({
method: 'GET',
url: API_ROOT
}).then(function(response) {
return response.data;
});
};
this.add = function(text) {
return $http({
method: 'POST',
url: API_ROOT,
data: text
});
};
this.update = function(id, text) {
return $http({
method: 'PUT',
url: API_ROOT + '/' + id,
data: text
});
};
this.remove = function(id) {
return $http({
method: 'DELETE',
url: API_ROOT + '/' + id
});
};
}
); | 2716223a13377a17b1416716aaf2a969cebf0edb | [
"Markdown",
"JavaScript"
] | 3 | Markdown | dwatling/jee-angular-todo | 5ffb7cfd3d5419e802fcb87fb054284e88e32398 | fd524f40989a8433f991c674f62ecc06db92cf99 | |
refs/heads/master | <repo_name>suhasshrinivasan/music-genre-classification<file_sep>/README.md
# Welcome to the music-genre-classification wiki!
**Language used for development**: Python 2.7.6
This repository consists of development code that classifies music according to the following genres:
1. Classical (Western)
2. Country (Western)
3. Jazz
4. Pop
5. Rock
6. Metal
**Dataset used for training**: http://opihi.cs.uvic.ca/sound/genres.tar.gz.
### Features used:
1. Frequencies (Classification accuracy: ~45%)
2. MFCC (Classification accuracy: ~70%)
### Choice of classifier:
Logistic Regression classifier.
### Consists of Python scripts that do the following:
1. Batch conversion of .au to .wav files.
2. Plotting spectrogram of a .wav file.
3. Extraction of frequencies from the dataset and making frequency "prints" of all .wav files.
4. Extraction of MFCC from the dataset and making MFCC "prints" of all .wav files.
5. Reading of FFT and MFCC prints, separately, and training suitable classifiers.
(Refer to individual files for detailed instructions)
## How to use project for testing:
1. Download dataset from: http://opihi.cs.uvic.ca/sound/genres.tar.gz.
2. Extract into suitable directory: BASE_DIR
3. Run convert-to-wav.py on each subdir of BASE_DIR.
4. Run extract-features-FFT.py on each subdir of BASE_DIR.
5. Run extract-features-MFCC.py on each subdir of BASE_DIR.
6. Run train-classify.py according to run instruction provided in the code file.
Reference guide: Building Machine Learning Systems with Python. ISBN 978-1-78216-140-0.
<file_sep>/train-classify.py
"""Script reads from fft and mfcc files and trains using logistic regression and knn
IN: Paths to directories consisting of FFT files, and MFCC files.
OUT: Splits dataset as per code into train and test sets, performs training and tests. Displays classification accuracy along with confusion matrix.
Run instructions:
python train-classify.py path_dir1 path_dir2
Where path_dir1 is the base_dir that consists of subdirs consisting of fft files.
path_dir2 is the base-dir that consists of subdirs consisting of mfcc files.
NOTE:
1. Use ONLY absolute paths.
"""
import sklearn
from sklearn import linear_model
from sklearn.neighbors import KNeighborsClassifier
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
import scipy
import os
import sys
import glob
import numpy as np
"""reads FFT-files and prepares X_train and y_train.
genre_list must consist of names of folders/genres consisting of the required FFT-files
base_dir must contain genre_list of directories
"""
def read_fft(genre_list, base_dir):
X = []
y = []
for label, genre in enumerate(genre_list):
# create UNIX pathnames to id FFT-files.
genre_dir = os.path.join(base_dir, genre, "*.fft.npy")
# get path names that math genre-dir
file_list = glob.glob(genre_dir)
for file in file_list:
fft_features = np.load(file)
X.append(fft_features)
y.append(label)
# print(X)
# print(y)
# print(len(X))
# print(len(y))
return np.array(X), np.array(y)
"""reads MFCC-files and prepares X_train and y_train.
genre_list must consist of names of folders/genres consisting of the required MFCC-files
base_dir must contain genre_list of directories
"""
def read_ceps(genre_list, base_dir):
X, y = [], []
for label, genre in enumerate(genre_list):
for fn in glob.glob(os.path.join(base_dir, genre, "*.ceps.npy")):
ceps = np.load(fn)
num_ceps = len(ceps)
X.append(np.mean(ceps[int(num_ceps*1/10):int(num_ceps*9/10)], axis=0))
y.append(label)
return np.array(X), np.array(y)
def learn_and_classify(X_train, y_train, X_test, y_test, genre_list):
# print("X_train = " + str(len(X_train)), "y_train = " + str(len(y_train)), "X_test = " + str(len(X_test)), "y_test = " + str(len(y_test)))
logistic_classifier = linear_model.LogisticRegression()
logistic_classifier.fit(X_train, y_train)
logistic_predictions = logistic_classifier.predict(X_test)
logistic_accuracy = accuracy_score(y_test, logistic_predictions)
logistic_cm = confusion_matrix(y_test, logistic_predictions)
print("logistic accuracy = " + str(logistic_accuracy))
print("logistic_cm:")
print(logistic_cm)
# knn_classifier = KNeighborsClassifier()
# knn_classifier.fit(X_train, y_train)
# knn_predictions = knn_classifier.predict(X_test)
# knn_accuracy = accuracy_score(y_test, knn_predictions)
# knn_cm = confusion_matrix(y_test, knn_predictions)
# print("knn accuracy = " + str(knn_accuracy))
# print("knn_cm:")
# print(knn_cm)
plot_confusion_matrix(logistic_cm, "Confusion matrix", genre_list)
# plot_confusion_matrix(knn_cm, "Confusion matrix for FFT classification", genre_list)
def plot_confusion_matrix(cm, title, genre_list, cmap=plt.cm.Blues):
plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(genre_list))
plt.xticks(tick_marks, genre_list, rotation=45)
plt.yticks(tick_marks, genre_list)
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.show()
def main():
# first command line argument is the base folder that consists of the fft files for each genre
base_dir_fft = sys.argv[1]
# second command line argument is the base folder that consists of the mfcc files for each genre
base_dir_mfcc = sys.argv[2]
"""list of genres (these must be folder names consisting .wav of respective genre in the base_dir)
Change list if needed.
"""
genre_list = ["classical", "jazz", "country", "pop", "rock", "metal"]
#genre_list = ["classical", "jazz"] IF YOU WANT TO CLASSIFY ONLY CLASSICAL AND JAZZ
# use FFT
X, y = read_fft(genre_list, base_dir_fft)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = .25)
# print("X_train = " + str(len(X_train)), "y_train = " + str(len(y_train)), "X_test = " + str(len(X_test)), "y_test = " + str(len(y_test)))
print('\n******USING FFT******')
learn_and_classify(X_train, y_train, X_test, y_test, genre_list)
print('*********************\n')
# use MFCC
X, y = read_ceps(genre_list, base_dir_mfcc)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
print('******USING MFCC******')
learn_and_classify(X_train, y_train, X_test, y_test, genre_list)
print('*********************')
if __name__ == "__main__":
main() | 6f22c6c303694edf3b1bf1f225232791daab9876 | [
"Markdown",
"Python"
] | 2 | Markdown | suhasshrinivasan/music-genre-classification | 474fb4663972fad0e588409e10303ee5036a7a86 | 96eb700aae5b94641d1aff41320e0b16344b45f3 | |
refs/heads/master | <file_sep>module Itamae
VERSION = "1.12.1"
end
| d511332035b68ca1604a4613c00e91d5548e6902 | [
"Ruby"
] | 1 | Ruby | virgo-liu/itamae | fd48cb50fd63777139c2f62cb809fb16812c945a | b9a6f347fba5dbb83eb077f0b3d37ead8d114589 | |
refs/heads/development | <repo_name>kleap/iTechArt.Labs.iTechArtSurvey<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/reducers/surveyReducer.js
import * as types from './../actions/actionTypes';
import { questions } from './questionReducer';
export const surveyReducer = (state = {}, action) => {
switch (action.type) {
case types.SET_ITEMS_DESCRIPTION:
return { ...state, itemDescriptions: action.items, fetching: false };
case types.SET_FILTER_STRING:
return { ...state, filter: action.input };
case types.DELETE_ITEM:
let index = state.itemDescriptions.findIndex(i => i.id === action.id);
return {
...state,
itemDescriptions: [
...state.itemDescriptions.slice(0, index),
...state.itemDescriptions.slice(index + 1)
]
};
case types.SET_ITEM:
return { ...state, currentItem: action.item, fetching: false };
case types.SET_MANAGE_MODE:
return { ...state, manageMode: action.payload, fetching: true };
case types.CLEAR_CURRENT_ITEM:
return { ...state, currentItem: undefined };
case types.SAVE_SURVEY_TITLE:
return { ...state, currentItem: { ...state.currentItem, title: action.title } };
case types.DELETE_QUESTION:
case types.SAVE_QUESTION:
case types.ADD_QUESTION:
return {
...state,
currentItem: {
...state.currentItem,
questions: questions(state.currentItem.questions, action)
}
};
default:
return state;
}
}
export default surveyReducer;
<file_sep>/iTechArt.Labs.iTechArtSurvey.BusinessLayer/Utils/SurveyDTOConverter.cs
using System;
using System.Linq;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel;
using iTechArt.Labs.iTechArtSurvey.Web.Library.DTO;
namespace iTechArt.Labs.iTechArtSurvey.BusinessLayer.Utils
{
internal static class SurveyDTOConverter
{
internal static SurveyDTO ConvertToDTO(this Survey survey)
{
var questions = survey.SurveyQuestions.Select(q => q.ConvertToDTO());
var surveyDTO = new SurveyDTO()
{
Id = survey.Id,
Title = survey.Title,
Author = survey.Author == null ? "none" : survey.Author.Name,
Questions = questions
};
return surveyDTO;
}
internal static Survey ConvertFromDTO(this SurveyDTO surveyDTO, User author)
{
var id = Guid.NewGuid();
var survey = new Survey()
{
Id = id,
Version = 0,
Title = surveyDTO.Title,
Author = author,
Created = DateTime.Now,
SurveyQuestions = surveyDTO
.Questions
.Select(q => q.ConvertFromDTO(id)).ToList()
};
return survey;
}
internal static Survey ConvertFromDTO(this SurveyDTO surveyDTO, User editor, Survey storedSurvey)
{
var survey = new Survey()
{
Id = storedSurvey.Id,
Version = storedSurvey.Version + 1,
Title = surveyDTO.Title,
Author = storedSurvey.Author,
Created = storedSurvey.Created,
Edited = DateTime.Now,
Editor = editor,
SurveyQuestions = surveyDTO.Questions.Select(q => q.ConvertFromDTO(storedSurvey.Id)).ToList()
};
return survey;
}
internal static SurveyDescriptionDTO ConvertToDescriptionDTO(this Survey survey)
{
var surveyDescriptionDTO = new SurveyDescriptionDTO()
{
Id = survey.Id,
Title = survey.Title,
Author = survey.Author == null ? "none" : survey.Author.Name,
QuestionsCount = survey.SurveyQuestions.Count,
Description = $"Created at: {survey.Created.ToShortDateString()}"
};
return surveyDescriptionDTO;
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/Repository/IRepository.cs
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.Repository
{
public interface IRepository<TEntity> : IDisposable where TEntity : class
{
Task<IEnumerable<TEntity>> GetAllAsync();
Task<TEntity> CreateAsync(TEntity entity);
Task<TEntity> FindAsync(Guid id);
Task<TEntity> FindAsync(Guid id, int version);
Task<IEnumerable<TEntity>> FindAsync(Func<TEntity, bool> predicate);
Task UpdateAsync(TEntity entity);
Task DeleteAsync(TEntity entity);
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/App.js
import React, { Component } from 'react';
import { Switch, Route } from 'react-router-dom';
import Navigation from './components/navigation/Navigation';
import SurveyConstructorContainer from './scenes/newsurvey/SurveyConstructorContainer';
import SurveyManagerContainer from './scenes/mysurvey/SurveyManagerContainer';
class App extends Component {
render() {
return (
<div className='row mt-5'>
<Navigation />
<main className='col-9 h-100'>
<Switch>
<Route path='/newsurvey' component={SurveyConstructorContainer} />
<Route path='/mysurvey' component={SurveyManagerContainer} />
</Switch>
</main>
</div>
);
}
}
export default App;
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/mysurvey/components/item-description/ItemDescription.js
import React, { Component } from 'react';
import { Button, Card, CardText, CardTitle, FormGroup } from 'reactstrap';
import ItemDescriptionSummary from './components/ItemDescriptionSummary';
class ItemDescription extends Component {
deleteItem = () => {
this.props.handleDeleteItem(this.props.item.id);
};
editItem = () => {
this.props.handleEditItem(this.props.item.id);
};
render() {
const { title, description, author, questionsCount } = this.props.item;
return (
<div className='col-md-6 col-lg-4 p-3'>
<Card block >
<CardTitle className='text-truncate'>{title}</CardTitle>
<CardText className='text-justify'>
{description}
</CardText>
<ItemDescriptionSummary author={author} count={questionsCount} />
<FormGroup className='mt-3 d-flex justify-content-end'>
<Button onClick={this.editItem}>Edit</Button>
<Button onClick={this.deleteItem}>Delete</Button>
</FormGroup>
</Card>
</div>
);
}
}
export default ItemDescription;<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/newsurvey/components/question-editor/QuestionEditor.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Card, FormGroup, Label, Input, Form } from 'reactstrap';
import DeleteEditToolbar from './../delete-edit-toolbar/DeleteEditToolbar';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { deleteQuestion, saveQuestion } from './../../../../actions/actionCreators';
import { MultiQuestion, TextQuestion } from './../questions';
const mapStateToProps = (state) => ({
state
});
const mapDispatchToProps = (dispatch) => ({
deleteQuestion: bindActionCreators(deleteQuestion, dispatch),
saveQuestion: bindActionCreators(saveQuestion, dispatch),
});
class QuestionEditor extends Component {
constructor(props) {
super(props);
this.state = {
editMode: false,
question: props.question
};
}
changeQuestionOption = (index, option) => {
this.setState((prevState, props) => {
return {
question: {
...prevState.question,
options: [
...prevState.question.options.slice(0, index),
option,
...prevState.question.options.slice(index + 1)
]
}
};
});
}
deleteQuestionOption = (index) => {
this.setState((prevState, props) => {
return {
question: {
...prevState.question,
options: [
...prevState.question.options.slice(0, index),
...prevState.question.options.slice(index + 1)
]
}
};
});
}
addQuestionOption = () => {
this.setState((prevState, props) => {
return {
question: {
...prevState.question,
options: [...prevState.question.options, '']
}
};
});
}
getQuestionComponent(type) {
switch (type) {
case 'textarea':
return <TextQuestion editMode={this.state.editMode} question={this.state.question} />;
case 'checkbox':
case 'radio':
return <MultiQuestion type={type}
deleteOption={this.deleteQuestionOption}
changeOption={this.changeQuestionOption}
addOption={this.addQuestionOption}
editMode={this.state.editMode}
question={this.state.question} />
default:
break;
}
}
setEditMode = (value) => {
this.setState({
editMode: value
});
}
changeTitle = (e) => {
const newTitle = e.target.value;
this.setState((prevState, props) => {
return {
question: { ...prevState.question, title: newTitle }
};
});
}
saveQuestion = () => {
this.props.saveQuestion(this.state.question);
}
render() {
return (
<div className='pt-3'>
<Card block>
<div className='d-flex justify-content-end'>
<DeleteEditToolbar
id={this.props.question.id}
onSave={this.saveQuestion}
onDelete={this.props.deleteQuestion}
setEditMode={this.setEditMode}
editMode={this.state.editMode} />
</div>
<Form >
<FormGroup className='d-flex' >
<Label for='title' className='text-nowrap pr-2' >{this.props.index}{'.'}</Label>
<Input type='text'
disabled={!this.state.editMode}
value={this.state.question.title}
onChange={(e) => this.changeTitle(e)}
name='title' />
</FormGroup>
{this.getQuestionComponent(this.state.question.type)}
</Form>
</Card>
</div>
);
}
}
QuestionEditor.propTypes = {
question: PropTypes.object.isRequired,
index: PropTypes.number.isRequired
};
export default connect(mapStateToProps, mapDispatchToProps)(QuestionEditor);<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/components/loading/Loading.js
import React from 'react';
import PropTypes from 'prop-types';
const Loading = (props) => (
props.loading &&
<div className='d-flex justify-content-center m-5'>
<i className='fa fa-spinner fa-spin fa-4x'></i>
</div>
);
Loading.propTypes = {
loading: PropTypes.bool
};
Loading.defaultProps = {
loading: true
};
export default Loading;<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/newsurvey/components/question-manager/QuestionManager.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import QuestionEditor from './../question-editor/QuestionEditor';
class QuestionManager extends Component {
render() {
const questions = this.props.questions.map((q, index) => (
<QuestionEditor key={q.id}
question={q}
index={index + 1} />
));
return (
<div className='mt-3'>
{questions}
</div>
);
}
}
QuestionManager.propTypes = {
questions: PropTypes.array
};
export default QuestionManager;<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/mysurvey/components/item-description/components/ItemDescriptionSummary.js
import React from 'react';
import PropTypes from 'prop-types';
const ItemDescriptionSummary = (props) => (
<p className='card-text'>
<span className='font-italic'>{props.author}</span>
{', '}
<span><b>{props.count} </b>
{' questions.'}
</span>
</p>
);
ItemDescriptionSummary.propTypes = {
count: PropTypes.number,
author: PropTypes.string
};
ItemDescriptionSummary.defaultProps = {
count: 0,
author: 'none'
};
export default ItemDescriptionSummary;
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/newsurvey/SurveyConstructorContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { addQuestion, saveSurveyTitle } from './../../actions/actionCreators';
import { saveItem, editItem, cancelCreation } from './../../actions/middlewareActionCreators';
import SurveyConstructor from './components/survey-constructor/SurveyConstructor';
const mapStateToProps = (state) => ({
item: state.surveys.currentItem,
manageMode: state.surveys.manageMode,
fetching: state.surveys.fetching
});
const mapDispatchToProps = (dispatch) => ({
cancelCreation: bindActionCreators(cancelCreation, dispatch),
saveItem: bindActionCreators(saveItem, dispatch),
editSurvey: bindActionCreators(editItem, dispatch),
addQuestion: bindActionCreators(addQuestion, dispatch),
saveTitle: bindActionCreators(saveSurveyTitle, dispatch)
});
class SurveyConstructorContainer extends Component {
render() {
return (
<SurveyConstructor
info={{
title: this.props.item.title,
id: this.props.item.id,
author: this.props.item.author
}}
fetching={this.props.fetching}
questions={this.props.item.questions}
manageMode={this.props.manageMode}
cancelCreation={this.props.cancelCreation}
addQuestion={this.props.addQuestion}
saveTitle={this.props.saveTitle}
saveItem={this.props.saveItem}
/>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SurveyConstructorContainer);<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/Repository/GenericRepository.cs
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.Repository
{
public class GenericRepository<TEntity> : IRepository<TEntity> where TEntity : class
{
private readonly DbContext _context;
private readonly DbSet<TEntity> _dbSet;
private bool disposed = false;
public GenericRepository(DbContext context)
{
_context = context;
_dbSet = _context.Set<TEntity>();
}
public async Task<TEntity> CreateAsync(TEntity entity)
{
_dbSet.Add(entity);
await _context.SaveChangesAsync();
return entity;
}
public async Task DeleteAsync(TEntity entity)
{
_dbSet.Remove(entity);
await _context.SaveChangesAsync();
}
public async Task<IEnumerable<TEntity>> FindAsync(Func<TEntity, bool> predicate)
{
var resultSet = await _dbSet.ToListAsync();
return resultSet.Where(predicate);
}
public Task<TEntity> FindAsync(Guid id)
{
return _dbSet.FindAsync(id);
}
public Task<TEntity> FindAsync(Guid id, int version)
{
return _dbSet.FindAsync(id, version);
}
public async Task<IEnumerable<TEntity>> GetAllAsync()
{
return await _dbSet.AsNoTracking().ToListAsync();
}
public async Task UpdateAsync(TEntity entity)
{
_dbSet.Attach(entity);
_context.Entry(entity).State = EntityState.Modified;
await _context.SaveChangesAsync();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
_context.Dispose();
}
disposed = true;
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/newsurvey/components/delete-edit-toolbar/DeleteEditToolbar.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
class DeleteEditToolbar extends Component {
onSave = () => {
if (this.props.editMode) {
this.props.onSave();
}
this.props.setEditMode(!this.props.editMode)
}
render() {
return (
<div className={classNames({
'invisible': this.props.hidden
})}>
<a role='button'
onClick={() => this.onSave()}
className={classNames({
'fa p-1': true,
'fa-pencil': !this.props.editMode,
'fa-save': this.props.editMode,
'invisible': this.props.deleteOnly
})}>{''}</a>
<a role='button'
className='fa fa-trash ml-3'
onClick={() => this.props.onDelete(this.props.id)} >{''}</a>
</div>
);
}
}
DeleteEditToolbar.propTypes = {
onDelete: PropTypes.func.isRequired,
hidden: PropTypes.bool,
editMode: PropTypes.bool
};
DeleteEditToolbar.defaultProps = {
editMode: false
}
export default DeleteEditToolbar;<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/reducers/questionReducer.js
import * as types from './../actions/actionTypes';
export const questions = (questions = [], action) => {
switch (action.type) {
case types.SAVE_QUESTION:
return questions.map(q => {
return q.id === action.question.id ?
action.question : q;
});
case types.DELETE_QUESTION:
let index = questions.findIndex(q => q.id === action.questionId);
return [
...questions.slice(0, index),
...questions.slice(index + 1),
];
case types.ADD_QUESTION:
return [...questions, action.question];
default:
return questions;
}
}<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/EF/EntityConfigurations/SurveyQuestionConfiguration.cs
using System.Data.Entity.ModelConfiguration;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.EF.EntityConfigurations
{
class SurveyQuestionConfiguration : EntityTypeConfiguration<SurveyQuestion>
{
public SurveyQuestionConfiguration()
{
HasKey(s => s.Id)
.Property(s => s.Id)
.HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);
HasRequired(s => s.Survey)
.WithMany(s => s.SurveyQuestions)
.HasForeignKey(q => new { q.SurveyId, q.SurveyVersion }).WillCascadeOnDelete(true);
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/mysurvey/components/item-manager/ItemManager.js
import React, { Component } from 'react';
import { Row } from 'reactstrap';
import PropTypes from 'prop-types';
import ItemDescription from './../item-description/ItemDescription';
import Loading from './../../../../components/loading/Loading';
import SearchToolbar from './../search-toolbar/SearchToolbar';
class ItemManager extends Component {
componentDidMount() {
this.props.getItemDescriptions()
}
render() {
const items = this.props.items.map((item) => (
<ItemDescription key={item.id}
item={item}
handleEditItem={this.props.handleEditItem}
handleDeleteItem={this.props.handleDeleteItem} />
));
if (this.props.fetching) {
return <Loading loading={this.props.fetching} />;
} else {
return (
<div className='h-100'>
<SearchToolbar
header="Surveys"
link="New"
linkValue="/newsurvey"
handleSearch={this.props.handleSearch}
filterString={this.props.filterString}/>
<Row>
{items}
</Row>
<h4>{'Count: ' + this.props.totalCount}</h4>
</div>
);
}
}
}
ItemManager.propTypes = {
items: PropTypes.array,
fetching: PropTypes.bool.isRequired,
totalCount: PropTypes.number,
filterString: PropTypes.string.isRequired,
getItemDescriptions: PropTypes.func.isRequired,
handleSearch: PropTypes.func.isRequired,
handleDeleteItem: PropTypes.func.isRequired,
handleEditItem: PropTypes.func.isRequired,
};
ItemManager.defaultProps = {
items: []
};
export default ItemManager;<file_sep>/iTechArt.Labs.iTechArtSurvey.BusinessLayer/Utils/ObjectWithMaxPropertyLinqExtension.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace iTechArt.Labs.iTechArtSurvey.BusinessLayer.Utils
{
internal static class ObjectWithMaxPropertyLinqExtension
{
internal static T GetByMax<T>(this IEnumerable<T> collection, Func<T, int> selector)
{
return collection.OrderByDescending(selector).FirstOrDefault();
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web.Library/DTO/SurveyDescriptionDTO.cs
using System;
namespace iTechArt.Labs.iTechArtSurvey.Web.Library.DTO
{
public class SurveyDescriptionDTO
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Description { get; set; }
public int QuestionsCount { get; set; }
}
}<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/actions/middlewareActionCreators.js
import { deleteItem, setItemDescriptions, setManageMode, setItem } from './actionCreators';
import * as api from './../api/apiCalls';
import { push, goBack } from 'react-router-redux';
export const deleteItemFromServer = (id) => (dispatch) => {
return api.deleteItem(id)
.then((response) => {
if (!response.data.isError) {
dispatch(deleteItem(id));
} else {
return "error";
}
})
.catch((error) => {
return "error";
});
}
export const getItemDescriptionsFromServer = () => (dispatch) => {
return api.getDescriptions()
.then((response) => {
dispatch(setItemDescriptions(response.data.data));
})
.catch((error) => {
return "error";
});
}
export const editItem = (id) => (dispatch) => {
return api.getItem(id)
.then((response) => {
dispatch(setManageMode(true));
dispatch(push('/newsurvey'));
dispatch(setItem(response.data.data));
})
.catch((error) => {
console.log(error);
});
}
export const saveItem = (item) => (dispatch) => {
console.log(item);
return api.saveItem(item)
.then((response) => {
dispatch(setManageMode(false));
dispatch(push('/mysurvey'));
dispatch(setItem({}));
});
}
export const cancelCreation = (item) => (dispatch) => {
dispatch(goBack());
return dispatch(setManageMode(false));
}<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/actions/actionTypes.js
export const SET_FILTER_STRING = 'SET_FILTER_STRING';
export const DELETE_ITEM = 'DELETE_ITEM';
export const SET_ITEM = 'SET_ITEM';
export const SAVE_SURVEY_TITLE = 'SAVE_SURVEY_TITLE';
export const SET_MANAGE_MODE = 'SET_MANAGE_MODE';
export const SET_ITEMS_DESCRIPTION = 'SET_ITEMS_DESCRIPTION';
export const CLEAR_CURRENT_ITEM = 'CLEAR_CURRENT_ITEM';
export const SAVE_QUESTION = 'SAVE_QUESTION';
export const DELETE_QUESTION = 'DELETE_QUESTION';
export const ADD_QUESTION = 'ADD_QUESTION';
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/actions/actionCreators.js
import * as types from './actionTypes';
export function deleteItem(id) {
return {
type: types.DELETE_ITEM,
id
};
}
export function setFilter(input) {
return {
type: types.SET_FILTER_STRING,
input
};
}
export function saveSurveyTitle(title) {
return {
type: types.SAVE_SURVEY_TITLE,
title
}
}
export function setItemDescriptions(items) {
return {
type: types.SET_ITEMS_DESCRIPTION,
items
};
}
export function setItem(item) {
return {
type: types.SET_ITEM,
item
};
}
export function setManageMode(payload) {
return {
type: types.SET_MANAGE_MODE,
payload
};
}
export function clearCurrentItem() {
return {
type: types.CLEAR_CURRENT_ITEM
};
}
export const addQuestion = (question) => {
return {
type: types.ADD_QUESTION,
question
}
}
export function saveQuestion(question) {
return {
type: types.SAVE_QUESTION,
question
}
}
export function deleteQuestion(questionId) {
return {
type: types.DELETE_QUESTION,
questionId
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/configStore.js
import rootReducer from './rootReducer';
import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
const initialState = {
surveys: {
fetching: true,
manageMode: false,
itemDescriptions: [],
filter: '',
currentItem: {}
}
};
const configStore = (middleware) => (createStore(
rootReducer,
initialState,
compose(
applyMiddleware(thunk, ...middleware),
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
))
);
export default configStore;<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/DomainModel/Survey.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel
{
public class Survey
{
public Guid Id { get; set; }
public int Version { get; set; }
[MinLength(1, ErrorMessage = "Survey title must be not empty")]
public string Title { get; set; }
public virtual User Author { get; set; }
public DateTime Created { get; set; }
public virtual User Editor { get; set; }
public DateTime? Edited { get; set; }
public virtual ICollection<SurveyQuestion> SurveyQuestions { get; set; }
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/Controllers/SurveysController.cs
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Http.Cors;
using iTechArt.Labs.iTechArtSurvey.BusinessLayer.SurveyManagement;
using iTechArt.Labs.iTechArtSurvey.Web.Library;
using iTechArt.Labs.iTechArtSurvey.Web.Library.DTO;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
namespace iTechArt.Labs.iTechArtSurvey.Web.Controllers
{
[RoutePrefix("surveys")]
[EnableCors(origins: "http://localhost:3000", headers: "*", methods: "*")]
public class SurveysController : ApiController
{
private SurveyManager _manager;
public SurveyManager Manager
{
get
{
return _manager ?? Request.GetOwinContext().Get<SurveyManager>();
}
}
// GET: api/surveys
[HttpGet]
public Task<ServerResponse> GetSurveyDescriptions()
{
return Manager.GetSurveyDescriptionsAsync();
}
//POST apt/surveys/
[HttpPost]
public Task<ServerResponse> SaveSurvey([FromBody]SurveyDTO survey)
{
var userId = User.Identity.GetUserId();
return Manager.Save(userId, survey);
}
// GET: api/surveys/5
public Task<ServerResponse> Get(Guid id)
{
return Manager.GetAsync(id);
}
// DELETE: api/Surveys/5
public Task<ServerResponse> Delete(Guid id)
{
return Manager.Delete(id);
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/mysurvey/SurveyManagerContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import ItemManager from './components/item-manager/ItemManager';
import { setFilter } from './../../actions/actionCreators';
import { getItemDescriptionsFromServer, deleteItemFromServer, editItem } from './../../actions/middlewareActionCreators';
import { getFilteredItems } from './selectors/selector';
const mapStateToProps = (state, props) => ({
surveys: getFilteredItems()(state, props),
fetching: state.surveys.fetching,
totalCount: state.surveys.itemDescriptions.length,
filterString: state.surveys.filter
});
const mapDispatchToProps = (dispatch) => ({
getItemDescriptions: bindActionCreators(getItemDescriptionsFromServer, dispatch),
search: bindActionCreators(setFilter, dispatch),
deleteItem: bindActionCreators(deleteItemFromServer, dispatch),
editItem: bindActionCreators(editItem, dispatch)
});
class SurveyManagerContainer extends Component {
render() {
return (
<ItemManager
filterString={this.props.filterString}
fetching={this.props.fetching}
totalCount={this.props.totalCount}
items={this.props.surveys}
getItemDescriptions={this.props.getItemDescriptions}
handleSearch={this.props.search}
handleDeleteItem={this.props.deleteItem}
handleEditItem={this.props.editItem}
/>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SurveyManagerContainer);<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/api/apiCalls.js
import axios from 'axios';
export const getDescriptions = () => {
return axios.get('http://localhost:3179/api/surveys/');
}
export const getItem = (id) => {
return axios.get('http://localhost:3179/api/surveys/' + id);
}
export const saveItem = (data) => {
return axios.post('http://localhost:3179/api/surveys/', data);
}
export const deleteItem = (id)=>{
return axios.delete('http://localhost:3179/api/surveys/' + id);
}<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/EF/EntityConfigurations/QuestionConfiguration.cs
using System.Data.Entity.ModelConfiguration;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.EF.EntityConfigurations
{
internal class QuestionConfiguration : EntityTypeConfiguration<Question>
{
public QuestionConfiguration()
{
HasKey(q => q.Id);
HasOptional(q => q.Replies);
HasRequired(q => q.SurveyQuestion)
.WithOptional(s => s.Question)
.WillCascadeOnDelete(true);
Property(q => q.Required).IsRequired();
Property(q => q.Title)
.IsRequired()
.HasMaxLength(256);
Property(q => q.Type).IsRequired();
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.BusinessLayer/SurveyManagement/SurveyManager.cs
using System;
using System.Collections.Generic;
using System.Data.Entity.Validation;
using System.Linq;
using System.Threading.Tasks;
using iTechArt.Labs.iTechArtSurvey.BusinessLayer.UserManagement;
using iTechArt.Labs.iTechArtSurvey.BusinessLayer.Utils;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.EF;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.Repository;
using iTechArt.Labs.iTechArtSurvey.Web.Library;
using iTechArt.Labs.iTechArtSurvey.Web.Library.DTO;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
namespace iTechArt.Labs.iTechArtSurvey.BusinessLayer.SurveyManagement
{
public class SurveyManager : IDisposable
{
private bool disposed = false;
private readonly IRepository<Survey> _repository;
private SurveyUserManager _userManager;
public SurveyManager(IRepository<Survey> repository, SurveyUserManager userManager)
{
_repository = repository;
_userManager = userManager;
}
public async Task<ServerResponse> GetSurveyDescriptionsAsync()
{
var storedSurveys = await _repository.GetAllAsync();
var latestSurveys = GetLatestVersionsOfSurveys(storedSurveys);
var surveysDTO = latestSurveys
.Select(s => s.ConvertToDescriptionDTO()).ToList();
return new ServerResponse()
{
IsError = false,
Message = "latest surveys",
Data = surveysDTO
};
}
public async Task<ServerResponse> Delete(Guid id)
{
bool isError = false;
try
{
var storedSurveys = await _repository.FindAsync(s => s.Id == id);
for (int i = 0; i < storedSurveys.Count(); i++)
{
await _repository.DeleteAsync(storedSurveys.ElementAt(i));
}
}
catch (Exception)
{
isError = true;
throw;
}
return new ServerResponse()
{
IsError = isError
};
}
private IEnumerable<Survey> GetLatestVersionsOfSurveys(IEnumerable<Survey> surveys)
{
return surveys
.GroupBy(s => s.Id)
.Select(g => g.Select(s => s).GetByMax(s => s.Version));
}
public async Task<ServerResponse> GetAsync(Guid id)
{
var surveys = (await _repository.FindAsync(s => s.Id == id));
var latestSurvey = surveys.GetByMax(s => s.Version);
var latestSurveyDTO = latestSurvey.ConvertToDTO();
return new ServerResponse()
{
IsError = false,
Message = "OK",
Data = latestSurveyDTO
};
}
public async Task<ServerResponse> Save(string userId, SurveyDTO survey)
{
var user = await _userManager.FindByIdAsync(userId);
ServerResponse response = null;
string message = string.Empty;
bool isError = false;
try
{
var alreadyInDatabaseSurvey = (await _repository
.FindAsync(s => s.Id == survey.Id)).GetByMax(s => s.Version);
if (alreadyInDatabaseSurvey != null)
{
var modifiedSurvey = survey.ConvertFromDTO(user, alreadyInDatabaseSurvey);
await _repository.CreateAsync(modifiedSurvey);
}
else
{
var newSurvey = survey.ConvertFromDTO(user);
await _repository.CreateAsync(newSurvey);
}
message = "Survey was successfully saved";
}
catch (ArgumentException)
{
isError = true;
message = "Error occured while saving survey, unknown type of question.";
}
catch (DbEntityValidationException e)
{
isError = true;
message = "Error occured while saving survey: " + GetErrorsMessages(e.EntityValidationErrors);
}
finally
{
response = new ServerResponse()
{
IsError = isError,
Message = message
};
}
return response;
}
private string GetErrorsMessages(IEnumerable<DbEntityValidationResult> results)
{
string message = "\n";
foreach (var result in results)
{
foreach (var error in result.ValidationErrors)
{
message += error.ErrorMessage + "\n";
}
}
return message;
}
public static SurveyManager Create(
IdentityFactoryOptions<SurveyManager> identityFactoryOptions,
IOwinContext context)
{
return new SurveyManager(
new GenericRepository<Survey>(context.Get<SurveyContext>()),
context.Get<SurveyUserManager>());
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
_repository.Dispose();
_userManager.Dispose();
}
disposed = true;
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web.Library/DTO/QuestionDTO.cs
using System;
using System.Collections.Generic;
namespace iTechArt.Labs.iTechArtSurvey.Web.Library.DTO
{
public class QuestionDTO
{
public Guid Id { get; set; }
public string Title { get; set; }
public int Order { get; set; }
public string Type { get; set; }
public IEnumerable<string> Options { get; set; }
}
}<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/mysurvey/components/search-toolbar/SearchToolbar.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Input, Button } from 'reactstrap';
class SearchToolbar extends Component {
handleSearch(e) {
this.props.handleSearch(e.target.value);
}
render() {
return (
<div className='d-flex justify-content-between'>
<div className='d-flex'>
<h3>{this.props.header}</h3>
<Link to={this.props.linkValue}>
<Button color='secondary' className='ml-4'>{this.props.link}</Button>
</Link>
</div>
<Input className='w-25'
type='search'
value={this.props.filterString}
placeholder='search...'
onChange={(e)=>this.handleSearch(e)} />
</div>
);
}
}
SearchToolbar.propTypes = {
header: PropTypes.string,
link: PropTypes.string.isRequired,
linkValue: PropTypes.string.isRequired,
handleSearch: PropTypes.func.isRequired,
filterString: PropTypes.string
};
SearchToolbar.defaultProps = {
filterString: ""
};
export default SearchToolbar;<file_sep>/iTechArt.Labs.iTechArtSurvey.BusinessLayer/Config/OwinConfiguration.cs
using iTechArt.Labs.iTechArtSurvey.BusinessLayer.SurveyManagement;
using iTechArt.Labs.iTechArtSurvey.BusinessLayer.UserManagement;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.EF;
using Owin;
namespace iTechArt.Labs.iTechArtSurvey.BusinessLayer.Config
{
public static class OwinConfiguration
{
public static void RegisterManagers(IAppBuilder app)
{
app.CreatePerOwinContext(SurveyContext.Create);
app.CreatePerOwinContext<SurveyUserManager>(SurveyUserManager.Create);
app.CreatePerOwinContext<SignInManager>(SignInManager.Create);
app.CreatePerOwinContext<SurveyRoleManager>(SurveyRoleManager.Create);
app.CreatePerOwinContext<SurveyManager>(SurveyManager.Create);
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web.Library/DTO/SurveyDTO.cs
using System;
using System.Collections.Generic;
namespace iTechArt.Labs.iTechArtSurvey.Web.Library.DTO
{
public class SurveyDTO
{
public Guid Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public IEnumerable<QuestionDTO> Questions { get; set; }
}
}<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/DomainModel/SurveyQuestion.cs
using System;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel
{
public class SurveyQuestion
{
public Guid Id { get; set; }
public int Order { get; set; }
public Guid SurveyId { get; set; }
public int SurveyVersion { get; set; }
public virtual Survey Survey { get; set; }
public virtual Question Question { get; set; }
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/newsurvey/components/survey-constructor/SurveyConstructor.js
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { ButtonGroup, ButtonToolbar, Col, Button, FormGroup, Label, Input, FormText } from 'reactstrap';
import QuestionPicker from './../question-picker/QuestionPicker';
import QuestionManager from './../question-manager/QuestionManager';
import * as api from './../../../../api/apiCalls';
import Loading from './../../../../components/loading/Loading';
class SurveyConstructor extends Component {
leaveWithoutSaving = () => {
this.props.cancelCreation();
}
setTitle = (e) => {
this.props.saveTitle(e.target.value);
}
saveItem = () => {
this.props.saveItem({
...this.props.info,
questions: [...this.props.questions]
});
}
render() {
if (this.props.manageMode && this.props.fetching) {
return <Loading loading={this.props.fetching} />;
} else {
return (
<div className='row mt-2'>
<Col>
<FormGroup row>
<Label for='title' className='text-nowrap' sm={2}>Title</Label>
<Col sm={10}>
<Input type='text'
defaultValue={this.props.info.title}
onBlur={this.setTitle}
name='title' />
</Col>
</FormGroup>
<FormText color='muted'>
Questions: {this.props.questions.length},<i className='pl-2'>Author</i> : {this.props.author}
</FormText>
<ButtonToolbar className='d-flex justify-content-end mt-4'>
<ButtonGroup>
<Button onClick={this.saveItem}>Save</Button>
<Button onClick={this.leaveWithoutSaving}>Cancel</Button>
</ButtonGroup>
</ButtonToolbar>
<QuestionManager
questions={this.props.questions}
/>
</Col>
<div>
<QuestionPicker
addQuestion={this.props.addQuestion} />
</div>
</div>
);
}
}
}
SurveyConstructor.propTypes = {
info: PropTypes.object,
questions: PropTypes.array.isRequired,
manageMode: PropTypes.bool,
fetching: PropTypes.bool,
addQuestion: PropTypes.func.isRequired,
saveItem: PropTypes.func.isRequired,
saveTitle: PropTypes.func.isRequired,
cancelCreation: PropTypes.func.isRequired,
};
SurveyConstructor.defaultProps = {
title: 'Default survey',
id: "0000000-0000-0000-0000-000000000000",
author: "new",
questions: [
{
"id": 0,
"title": "Вопрос с текстовым вариантом ответа",
"type": "textarea",
"required": true
},
{
"id": 1,
"title": "Вопрос с множеством вариантов ответа",
"type": "checkbox",
"required": true,
"options": [
"Первый вариант",
"Второй вариант",
"Третий вариант",
"Четвертый вариант"
]
},
{
"id": 2,
"title": "Вопрос с выбором одного варианта ответа",
"type": "radio",
"required": true,
"options": [
"Первый вариант",
"Второй вариант",
"Третий вариант",
"Четвертый вариант"
]
},
]
};
export default SurveyConstructor;<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/src/surveys/scenes/newsurvey/components/questions/TextQuestion.js
import React, { Component } from 'react';
import { FormGroup, Label, Input } from 'reactstrap';
class TextQuestion extends Component {
render() {
return (
<FormGroup>
<Label for="exampleText">Reply</Label>
<Input type="textarea" disabled name="text" id="exampleText" />
</FormGroup>
);
}
}
export default TextQuestion;<file_sep>/iTechArt.Labs.iTechArtSurvey.BusinessLayer/Utils/QuestionDTOConverter.cs
using System;
using System.Collections.Generic;
using iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel;
using iTechArt.Labs.iTechArtSurvey.Web.Library.DTO;
using Newtonsoft.Json;
namespace iTechArt.Labs.iTechArtSurvey.BusinessLayer.Utils
{
internal static class QuestionDTOConverter
{
internal static QuestionDTO ConvertToDTO(this SurveyQuestion surveyQuestion)
{
var questionDTO = new QuestionDTO()
{
Id = surveyQuestion.Question.Id,
Order = surveyQuestion.Order,
Title = surveyQuestion.Question.Title,
Type = surveyQuestion.Question.Type.ToString(),
Options = JsonConvert.DeserializeObject<List<string>>(surveyQuestion.Question.JsonMetaInformation)
};
return questionDTO;
}
internal static SurveyQuestion ConvertFromDTO(this QuestionDTO questionDTO, Guid surveyId)
{
var surveyQuestion = new SurveyQuestion()
{
Order = questionDTO.Order,
SurveyId = surveyId,
Question = new Question()
{
Title = questionDTO.Title,
Required = true,
Type = (QuestionType)Enum.Parse(typeof(QuestionType), questionDTO.Type),
JsonMetaInformation = JsonConvert.SerializeObject(questionDTO.Options),
}
};
return surveyQuestion;
}
}
}
<file_sep>/iTechArt.Labs.iTechArtSurvey.DataAccessLayer/DomainModel/Question.cs
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
namespace iTechArt.Labs.iTechArtSurvey.DataAccessLayer.DomainModel
{
public class Question
{
public Guid Id { get; set; }
[MinLength(1, ErrorMessage = "Question title must be not empty")]
public string Title { get; set; }
public QuestionType Type { get; set; }
public bool Required { get; set; }
public string JsonMetaInformation { get; set; }
public virtual SurveyQuestion SurveyQuestion { get; set; }
public virtual ICollection<Reply> Replies { get; set; }
}
}<file_sep>/iTechArt.Labs.iTechArtSurvey.Web/Startup.cs
using System.Web.Http;
using iTechArt.Labs.iTechArtSurvey.BusinessLayer.Config;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Newtonsoft.Json.Serialization;
using Owin;
[assembly: OwinStartup(typeof(iTechArt.Labs.iTechArtSurvey.Web.Startup))]
namespace iTechArt.Labs.iTechArtSurvey.Web
{
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
OwinConfiguration.RegisterManagers(app);
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login")
});
app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
var config = new HttpConfiguration();
config.EnableCors();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;
app.UseWebApi(config);
}
}
}
| 808c3b2933ea8ca33424a90a4accdc7166679ee3 | [
"JavaScript",
"C#"
] | 37 | JavaScript | kleap/iTechArt.Labs.iTechArtSurvey | 685b5396080a18d79c9cce299d6799ef70b6d61a | 63ef0d54ae72b124c5ebd7740f78d58a7e97a1dd | |
refs/heads/main | <repo_name>Volodymyr-Roiukk/rs-pet-shop-backend<file_sep>/product-service/constants.js
const PRODUCTS_API_PATH = 'http://products-test1.s3-website-eu-west-1.amazonaws.com/';
module.exports = {PRODUCTS_API_PATH};<file_sep>/product-service/tests/getProductsList.test.js
const {getProductsList} = require('../handlers/getProductsList');
const defaultProducts = [
{
id: 1,
title: "Royal Canin Sterilised",
description: "The best premium food for your cats",
price: 19.99
},
{
id: 2,
title: "Royal Canin British Shorthair",
description: "The best premium food for your cats",
price: 14.99
},
{
id: 3,
title: "Royal Canin Sensible 33",
description: "The best premium food for your cats",
price: 9.99
},
{
id: 4,
title: "Royal Canin Kitten",
description: "The best premium food for your cats",
price: 9.99
},
{
id: 5,
title: "Royal Canin Indoor 27",
description: "The best premium food for your cats",
price: 19.99
},
{
id: 6,
title: "Royal Canin Hair & Skin Care",
description: "The best premium food for your cats",
price: 19.99
},
{
id: 7,
title: "Royal Canin Urinary Care",
description: "The best premium food for your cats",
price: 14.99
},
{
id: 8,
title: "Royal Canin Babycat",
description: "The best premium food for your cats",
price: 14.99
},
{
id: 9,
title: "Royal Canin Hairball Care",
description: "The best premium food for your cats",
price: 19.99
},
{
id: 10,
title: "Royal Canin Exigent Savour Sensation",
description: "The best premium food for your cats",
price: 20.99
}
];
describe('getProductsList handler tests', () => {
test('getProductsList should return response with status code 200', async () => {
const {statusCode} = await getProductsList();
expect(statusCode).toBe(200);
});
test('getProductsList should return response with products list', async () => {
const {body} = await getProductsList();
const products = JSON.parse(body);
expect(products).toEqual(defaultProducts);
});
});<file_sep>/README.md
# rs-pet-shop-backend
## Task-3
### [getProductsList](https://7hirlqmvvi.execute-api.eu-west-1.amazonaws.com/dev/products) - Get all products.
### [getProductsById](https://7hirlqmvvi.execute-api.eu-west-1.amazonaws.com/dev/products/1) - Get products by ID.
### [Frontend App](https://d1k2kpbj5227x1.cloudfront.net) - Here you can see that my FE app is synchronized with my API.
### [Frontend PR](https://github.com/Volodymyr-Roiukk/rs-pet-shop-frontend/pull/2)
### [Backend PR](https://github.com/Volodymyr-Roiukk/rs-pet-shop-backend/pull/1)
#### Service was done and Frontend synchronized with my API
#### Optional scope: All done without SWAGGER
#### Product properties:
##### - Id
##### - title
##### - description
##### - price
<file_sep>/product-service/index.js
import {getProductsList} from './handlers/getProductsList'
import {getProductsById} from './handlers/getProductsById'
export {getProductsList, getProductsById};
<file_sep>/product-service/webpack.config.js
const slsw = require('serverless-webpack');
module.exports = {
entry: './index.js',
target: 'node',
entry: slsw.lib.entries
};
<file_sep>/product-service/handlers/getProductsList.js
import fetch from 'node-fetch';
import {PRODUCTS_API_PATH} from '../constants'
export const getProductsList = async () => {
try {
const response = await fetch(PRODUCTS_API_PATH);
const products = await response.json();
return {
statusCode: 200,
headers: {
"Access-Control-Allow-Origin" : "*", // Required for CORS support to work
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify(products),
}
} catch (e) {
console.error(`Error: ${e}`);
return {
statusCode: 404,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Credentials" : true
},
body: JSON.stringify({message: `Something went wrong: ${e.message}`}),
}
}
};<file_sep>/product-service/tests/getProductsById.test.js
const {getProductsById} = require('../handlers/getProductsById');
describe('getProductsById handler tests', () => {
test('getProductsById should return response with status code 200', async () => {
const event = {pathParameters: {productId: 2}};
const {statusCode} = await getProductsById(event);
expect(statusCode).toBe(200);
});
test('getProductsById should return response with only one product array', async () => {
const event = {pathParameters: {productId: 7}};
const {body} = await getProductsById(event);
const products = JSON.parse(body);
expect(products.length).toBe(1);
});
test('getProductsById should return response with status code 404 if product not found', async () => {
const event = {pathParameters: {productId: -1}};
const {statusCode} = await getProductsById(event);
expect(statusCode).toBe(404);
});
test('getProductsById should return response with error message "Product not found"', async () => {
const expError = {message: "Product is not found"};
const event = {pathParameters: {productId: -1}};
const {body} = await getProductsById(event);
const error = JSON.parse(body);
expect(error).toEqual(expError);
});
}); | 289fa4b24631da065645adbefb9209561943502b | [
"JavaScript",
"Markdown"
] | 7 | JavaScript | Volodymyr-Roiukk/rs-pet-shop-backend | 4e0309bc10c3c0463f3dba6a3790715af6512b50 | 358e096f31ae1b18994448d133d0b7ee390c601c | |
refs/heads/master | <repo_name>apastorini/SDAP-GUI<file_sep>/src/app/components/files/files.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import { Constants } from '../../utils/Constants';
import { FileService } from '../../services/file.service';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import { Session } from '../../auth/loginData';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
import 'rxjs/add/observable/interval';
import { Subscription } from 'rxjs';
import { Observable } from "rxjs";
@Component({
selector: 'app-files',
templateUrl: './files.component.html',
styleUrls: []
})
export class FilesComponent implements OnInit, OnDestroy {
fileList = [];
porcentaje = '';
public uploadFile = Constants.BASE_URL + 'documentController/addFileToUser';
selectedFile: File = null;
buttonDisabled: boolean = false;
fileID = null;
public sub:Subscription;
constructor(
private http: HttpClient,
private fileService: FileService,
private modalService: NgbModal
){
this.sub = Observable.interval(10000)
.subscribe((val) => {
this.getAllUserFiles();
console.log('TIMER FILES'); });
}
onFileSelected(event){
this.porcentaje='';
this.selectedFile = <File> event.target.files[0];
}
upload(){
this.buttonDisabled=true;
const fd = new FormData();
console.log("ULPLOAD()")
fd.append('file',this.selectedFile, this.selectedFile.name)
this.http.post(this.uploadFile + "?email=" + sessionStorage.email + "&token=" + sessionStorage.token ,fd,{
reportProgress: true,
observe:'events'
})
.subscribe(event => {
if(event.type === HttpEventType.UploadProgress){
this.porcentaje = Math.round(event.loaded / event.total * 100) + "%";
console.log('Upload Progress: '+ this.porcentaje)
}else if(event.type === HttpEventType.Response){
this.buttonDisabled = false;
this.getAllUserFiles();
console.log("EVENT " + JSON.stringify(event));
console.log("EVENT " + JSON.stringify(HttpEventType.Response));
console.log("EVENT CODE" + JSON.stringify(event['body']['code']));
if(JSON.stringify(event['body']['code']) == '1'){
this.openModal(JSON.stringify(event['body']['message']),'El archivo ya existe en el sistem o fue eliminado. Cambie el nombre del archivo y vuelva a intentarlo.',"error","error");
}
if(JSON.stringify(event['body']['code']) == '0'){
this.openModal(JSON.stringify(event['body']['message']),'' ,"success","success");
}
}
});
}
uploadFlow(){
console.log("hola "+ this.selectedFile)
if(this.selectedFile == null){
this.openModal("Archivo no seleccionado", "Seleccione archivo a subir e intentelo nuevamente","error","error");
}
else
this.openModal("Esta seguro de subir el documento?", "Haga click en 'Confirmar' para subir el documento o en 'Cerrar' para cancelar la accion","confirm",'upload');
}
ngOnInit() {
this.getAllUserFiles();
}
ngOnDestroy(){
this.sub.unsubscribe();
}
getAllUserFiles(){
this.fileService.userFilesList(sessionStorage.getItem('email'),sessionStorage.getItem('token'))
.subscribe(res => {
console.log("solucion: " + JSON.stringify(res['result']))
if(JSON.stringify(res['result'])!="[]"){
console.log("Entra");
this.fileList = res['result'];
console.log("fileList length: " + this.fileList.length );
}else
{
this.fileList = [];
}
});
}
deleteFileFlow(fileID: string){
this.fileID=fileID;
this.openModal("¿Esta seguro de eliminar el archivo?", "Haga click en 'Confirmar' para eliminar el archivo o en 'Cerrar' para cancelar la accion","confirm",'delete')
}
downloadFile(fileID: string ){
console.log("entro!!! " + fileID)
this.fileService.downloadFile(sessionStorage.getItem('email'),sessionStorage.getItem('token'), fileID)
.subscribe(res => {
console.log("entro!!! " + res);
console.log("entro string Importante !!! " + JSON.stringify(res));
var file = new Blob([res], {type: 'application/pdf'});
this.showFile(file)
});
}
deleteFile(fileID: string){
this.fileService.deleteFile(sessionStorage.getItem('email'),sessionStorage.getItem('token'), fileID)
.subscribe(res =>{
this.getAllUserFiles();
console.log("OT " + JSON.stringify(res));
//this.openModal("NO SE ELIMINO", "FUNCION NO IMPLEMENTADA,","assets/img/red.png");
});
}
showFile(blob){
console.log("size!!! " + blob.size);
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(blob);
console.log("data windows url !!! " + JSON.stringify(data));
var link = document.createElement('a');
link.href = data;
link.download="file.pdf";
console.log("data file url !!! " + JSON.stringify(link));
link.click();
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
if(result=='delete'){
this.deleteFile(this.fileID)
}
if(result=='upload'){
this.upload();
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/components/home/home.component.ts
import { Component, OnInit } from '@angular/core';
import {HomeService} from '../../services/home.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: []
})
export class HomeComponent implements OnInit {
role: string;
cantArchivos;
cantAnalisis;
cantAnalisisTerminados;
cantUsuariosDelSistema;
cantArchivosCarpetaCompartida;
cantArchivosEnElSistema;
constructor(
private homeService: HomeService
) { }
ngOnInit() {
console.log("role Nuevo " + this.role );
this.role = sessionStorage.getItem('role');
console.log("role Nuevo2 " + this.role );
this.getDashBoard();
}
private getDashBoard(){
this.homeService.getDashBoard(sessionStorage.getItem('email'),sessionStorage.getItem('token')).subscribe(res => {
console.log(" cantArchivos: " + JSON.stringify(res) );
console.log('%c getDashBoard', 'color: orange;');
this.cantArchivos = res['result'][0].cantArchivos;
this.cantAnalisis = res['result'][0].cantAnalisis;
this.cantAnalisisTerminados = res['result'][0].cantAnalisisTerminados;
this.cantUsuariosDelSistema = res['result'][0].cantUsuariosDelSistema;
this.cantArchivosCarpetaCompartida = res['result'][0].cantArchivosCarpetaCompartida;
this.cantArchivosEnElSistema = res['result'][0].cantArchivosEnElSistema;
});
}
}
<file_sep>/src/app/services/payload/PasswordPayload.ts
export class PasswordPayload{
userEmail: string;
}
<file_sep>/src/app/auth/loginData.ts
export interface Login {
mail: string;
password: string;
}
export interface Logout {
mail: string;
password: string;
token:string;
}
export interface Session {
email:string;
token:string;
role:string;
}
<file_sep>/src/app/components/password/password.component.ts
import { Component, OnInit, Inject } from '@angular/core';
import { Router,Routes, RouterModule} from '@angular/router';
import { PasswordPayload } from '../../services/payload/PasswordPayload';
import { LoginService } from '../../services/login.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
@Component({
selector: 'app-password',
templateUrl: './password.component.html',
styleUrls: []
})
export class PasswordComponent implements OnInit {
userEmail:string;
form: FormGroup;
constructor(
private router: Router,
private loginService: LoginService,
private fb: FormBuilder,
private modalService: NgbModal
) { }
ngOnInit() {
this.form = this.fb.group({
userEmail: ['', Validators.required]
});
}
onSubmitClicked() {
const payload = new PasswordPayload();
payload.userEmail = this.userEmail;
console.log("email." + this.form.get("userEmail").value);
if (this.form.valid) {
this.loginService.recuperarPassword(this.form.get("userEmail").value)
.subscribe(res => {
if(res['code']===1){
this.openModal(res["message"], "","error","error")
}else
this.openModal("Email enviado", "","success","success")
console.log("asdasdsa" + JSON.stringify(res))
//this.openModal("Email enviado", "","success","success")
});
}
}
goToLogin(){
this.router.navigate(['login']);
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.type = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
if(result=='edit'){
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/components/help/help.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-help',
templateUrl: './help.component.html',
styleUrls: []
})
export class HelpComponent implements OnInit {
role: string;
email: string;
constructor() { }
ngOnInit() {
this.role = sessionStorage.getItem('role');
this.email = sessionStorage.getItem('email');
}
}
<file_sep>/src/app/components/shared/navbar/navbar.component.ts
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../../../auth/auth.service';
import { StorageService } from '../../../auth/storageService';
import { Session } from '../../../auth/loginData';
import { Observable } from 'rxjs/Observable';
import {HttpClientModule} from '@angular/common/http';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: []
})
export class NavbarComponent implements OnInit {
isLoggedIn$: Observable<boolean>;
email: string;
role: string;
name: string;
constructor(
private authService: AuthService,
private storageService: StorageService
) { }
ngOnInit() {
this.isLoggedIn$ = this.authService.isLoggedIn; // {2}
console.log("si funciona bien "+ this.isLoggedIn$);
this.email = sessionStorage.getItem('email');
this.role = sessionStorage.getItem('role');
this.name = sessionStorage.getItem('name');
this.storageService.watchStorage().subscribe((data:string) => {
console.log("soy Data "+ data);
this.email = sessionStorage.getItem('email');
this.role = sessionStorage.getItem('role');
//this will call whenever your localStorage data changes
// use localStorage code here and set your data here for ngFor
})
}
onLogout(){
this.authService.logout(); // {3}
}
}
<file_sep>/src/app/components/login/login.component.ts
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Router,Routes, RouterModule} from '@angular/router';
import { Constants } from '../../utils/Constants';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: []
})
export class LoginComponent implements OnInit {
registerForm: FormGroup; // {1}
private formSubmitAttempt: boolean; // {2}
submitted = false;
emailExists:boolean; // {1}
constructor(
private http: HttpClient,
private fb: FormBuilder, // {3}
private authService: AuthService, // {4}
private router: Router,
private modalService: NgbModal
) {}
ngOnInit() {
this.authService.logout()
this.registerForm = this.fb.group({ // {5}
mail: ['', Validators.required],
password: ['', Validators.required]
});
}
isFieldInvalid(field: string) { // {6}
return (
(!this.registerForm.get(field).valid && this.registerForm.get(field).touched) ||
(this.registerForm.get(field).untouched && this.formSubmitAttempt)
);
}
onSubmit() {
if (this.registerForm.valid) {
this.authService.login(this.registerForm.value);
// {7}
}else{
this.openModal("Error en login","Los campos Email y Contraseña deben tener informacion.","error","error");
}
this.formSubmitAttempt = true; // {8}
}
goToPassword(){
this.router.navigate(['password']);
}
goToSignin(){
this.router.navigate(['signin']);
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
if(result=='edit'){
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/app.module.ts
//Modulos
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, APP_INITIALIZER } from '@angular/core';
import { FormsModule } from '@angular/forms';
// import { AppMaterialModule } from './app-material/app-material.module';
import { HttpClient } from 'selenium-webdriver/http';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ReactiveFormsModule } from '@angular/forms';
//import { FileSelectDirective } from 'ng2-file-upload';
// import { FileUploadModule} from 'ng2-file-upload';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
//Components
import { NavbarComponent } from './components/shared/navbar/navbar.component';
import { AppComponent } from './app.component';
import { LoginComponent } from './components/login/login.component';
import { FilesComponent } from './components/files/files.component';
import { PasswordComponent } from './components/password/password.component';
import { CreateUserComponent } from './components/create-user/create-user.component';
import { EditUserComponent } from './components/edit-user/edit-user.component';
import { HomeComponent } from './components/home/home.component';
//import { WebmasterValidationComponent } from './webmaster-validation/webmaster-validation.component';
//import { ConfirmationDialogComponent } from './components/shared/confirmation-dialog/confirmation-dialog.component';
//Servicios
import { LoginService } from './services/login.service';
import { AuthService } from './auth/auth.service';
import { AnalyzeService } from './services/analyze.service';
import { UserService } from './services/user.service';
import { FileService } from './services/file.service';
import { StorageService } from './auth/storageService';
import { HomeService } from './services/home.service';
//import { DriveResource } from './services/drive-resource.service';
//Routing
import { APP_ROUTING } from './app.routes'
import { AuthGuard } from './auth/auth.guard';
import { FooterComponent } from './components/shared/footer/footer.component';
import { AnalyzeComponent } from './components/analyze/analyze.component';
import { UniqueEmailValidatorDirective } from './validators/unique-email-validator.directive';
import { ReportsComponent } from './components/reports/reports.component';
import { GoogleDriveComponent } from './components/google-drive/google-drive.component';
import { EditProfileComponent } from './components/edit-profile/edit-profile.component';
import { ModalComponent } from './utils/modal/modal.component';
import { GapiSession } from '../infrastructure/sessions/gapi.session';
import { AppRepository } from '../infrastructure/repositories/app.repository';
import { FileRepository } from '../infrastructure/repositories/file.repository';
import { UserRepository } from '../infrastructure/repositories/user.repository';
import { AppContext } from '../infrastructure/app.context';
import { AppSession } from '../infrastructure/sessions/app.session';
import { UserSession } from '../infrastructure/sessions/user.session';
import { FileSession } from '../infrastructure/sessions/file.session';
import { BreadCrumbSession } from '../infrastructure/sessions/breadcrumb.session';
import { DialogOneInputComponent } from './components/dialogoneinput/dialogoneinput.component';
import { BreadCrumbComponent } from './components/breadcrumb/breadcrumb.component';
import { BreadCrumbItemComponent } from './components/breadcrumb/breadcrumbitem/breadcrumbitem.component';
import { MatButtonModule, MatIconModule, MatMenuModule, MatTableModule, MatBottomSheetModule, MatDialogModule, MatFormFieldModule, MatInputModule, MatSelectModule, MatToolbarModule, MatProgressSpinnerModule, MatListModule } from '@angular/material';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
import { HelpComponent } from './components/help/help.component';
import { NewPasswordComponent } from './components/new-password/new-password.component';
import { ChangePasswordComponent } from './components/change-password/change-password.component';
export function initGapi(gapiSession: GapiSession) {
return () => gapiSession.initClient();
}
@NgModule({
declarations: [
AppComponent,
LoginComponent,
NavbarComponent,
FilesComponent,
PasswordComponent,
CreateUserComponent,
EditUserComponent,
HomeComponent,
FooterComponent,
AnalyzeComponent,
UniqueEmailValidatorDirective,
ReportsComponent,
GoogleDriveComponent,
EditProfileComponent,
ModalComponent,
DialogOneInputComponent,
BreadCrumbComponent,
BreadCrumbItemComponent,
PageNotFoundComponent,
HelpComponent,
NewPasswordComponent,
ChangePasswordComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
BrowserAnimationsModule,
FormsModule,
APP_ROUTING,
HttpClientModule,
NgbModule.forRoot(),
MatBottomSheetModule,
MatButtonModule,
MatDialogModule,
MatFormFieldModule,
MatIconModule,
MatInputModule,
MatMenuModule,
MatProgressSpinnerModule,
MatSelectModule,
MatTableModule,
MatToolbarModule,
MatListModule,
],
providers: [
AuthService,
AuthGuard,
LoginService,
UserService,
FileService,
AnalyzeService,
StorageService,
HomeService,
{ provide: APP_INITIALIZER, useFactory: initGapi, deps: [GapiSession], multi: true },
AppContext,
AppSession,
FileSession,
GapiSession,
UserSession,
BreadCrumbSession,
AppRepository,
FileRepository,
UserRepository,
],
bootstrap: [AppComponent],
entryComponents: [
ModalComponent
]
})
export class AppModule { }
<file_sep>/src/app/components/reports/reports.component.ts
import { Component, OnInit, OnDestroy } from '@angular/core';
import {AnalyzeService} from '../../services/analyze.service';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import 'rxjs/add/observable/interval';
import { Subscription, Observable } from 'rxjs';
@Component({
selector: 'app-reports',
templateUrl: './reports.component.html',
styleUrls: []
})
export class ReportsComponent implements OnInit, OnDestroy {
reportsList = [];
public sub:Subscription;
constructor(
private analyzeService: AnalyzeService,
private http: HttpClient
) {
this.sub = Observable.interval(10000)
.subscribe((val) => {
this.getReportList()
console.log('TIMER!'); });
}
ngOnInit() {
this.getReportList()
}
ngOnDestroy(){
this.sub.unsubscribe();
}
getReportList(){
this.analyzeService.listarAnalisisPorUsuario().subscribe(res=>{
console.log("FLSG")
if(JSON.stringify(res['result']) != "[]"){
this.reportsList = res['result'];
console.log("entro11111!!! " + JSON.stringify(res['result']))
console.log("entro!!! " + JSON.stringify(res['result'][2]))
}
});
}
downloadReport(idAnalisis: string ){
console.log("idAnalisis!!! " + idAnalisis)
this.analyzeService.reporteAnalisis(sessionStorage.getItem('email'),sessionStorage.getItem('token'), idAnalisis)
.subscribe(res => {
console.log("entro!!! " + res);
console.log("entro string !!! " + JSON.stringify(res));
var file = new Blob([res], {type: 'application/pdf'});
this.showFile(file)
});
}
showFile(blob){
console.log("size!!! " + blob.size);
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(blob);
console.log("data windows url !!! " + JSON.stringify(data));
var link = document.createElement('a');
link.href = data;
link.download="file.pdf";
console.log("data file url !!! " + JSON.stringify(link));
link.click();
}
}
<file_sep>/src/app/services/user.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http';
import { LoginPayload } from './payload/LoginPayload';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import { URLSearchParams } from '@angular/http';
@Injectable()
export class UserService {
private isUsedId = Constants.BASE_URL + 'loginController/isUsedId';
private passwordByEmail = Constants.BASE_URL + 'loginController/sendPasswordByMail';
private checkUserUrl = Constants.BASE_URL + 'loginController/isUsedId';
private createUserUrl = Constants.BASE_URL + 'systemController/createUser';
private modifyUserUrl = Constants.BASE_URL + 'systemController/modifyUser';
private secureEchoUrl = Constants.BASE_URL + 'Sdp/api/secure/echo/andrei';
private allUsersUrl = Constants.BASE_URL + 'systemController/listarUsuarios';
private recuperarContraseniaUrl = Constants.BASE_URL + 'systemController/recuperarContrasenia';
private changePasswordURL = Constants.BASE_URL + 'systemController/changePassword';
constructor(private http: HttpClient, private router: Router) { }
public doLogin(payload: LoginPayload): Observable<any>{
return this.http.post(this.checkUserUrl, payload, {responseType: 'text'}).pipe(
catchError(new ErrorHandler().handleError('LoginService', null))
);
}
public createUser(user: User){
if (user.name !== '' && user.password !== '') { // {3}
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers.append('Access-Control-Allow-Origin','*');
console.log('headers' + headers.get('Content-Type'));
console.log('User los datos del usuairooooooooo ::::::::::::::: ' + JSON.stringify(user));
console.log('headers' + user.roles);
return this.http.post(this.createUserUrl+"?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token'), user, {headers: headers})
//this.http.post(this.createUserUrl, user, {headers: headers})
//.subscribe(respuesta =>JSON.stringify(console.log(respuesta)))
}
}
public getAllUsers(){
let skeleton = {
"mail": "string",
"password": "<PASSWORD>",
"roleDTOs": [
{
"desc": "string",
"id": 0,
"name": "string"
}
],
"token": "string"
}
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers.append('Access-Control-Allow-Origin','*');
console.log('headers' + headers.get('Content-Type'));
return this.http.post(this.allUsersUrl, skeleton, {headers: headers})
//this.http.post(this.createUserUrl, user, {headers: headers})
//.subscribe(respuesta =>JSON.stringify(console.log(respuesta))
}
public recuperarContrasenia(email:string , token :string , password :string){
console.log("EMAIL, TOKEN, PASSWORD: " + email + " " + token + " " + password)
let skeleton = {
"email": email,
"enable": true,
"name": "string",
"password": <PASSWORD>,
"passwordExpiredDate": "string",
"passwordToken": token,
"roles": [
{
"desc": "string",
"id": 0,
"name": "string"
}
],
"secondName": "string",
"token": "string"
}
console.log("IMPORTANTE TOKEN " + skeleton.token)
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers.append('Access-Control-Allow-Origin','*');
console.log('headers' + headers.get('Content-Type'));
return this.http.post(this.recuperarContraseniaUrl, skeleton, {headers: headers})
}
public modifyUser(user: User){
console.log('1');
if (user.name !== '' && user.password !== '') { // {3}
console.log('2');
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers.append('Access-Control-Allow-Origin','*');
console.log('headers' + headers.get('Content-Type'));
return this.http.post(this.modifyUserUrl+"?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token'), user, {headers: headers})
//this.http.post(this.createUserUrl, user, {headers: headers})
//.subscribe(respuesta =>JSON.stringify(console.log(respuesta)))
}
}
public changePassword(password){
if (password !== '') { // {3}
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
headers.append('Access-Control-Allow-Origin','*');
console.log('headers' + headers.get('Content-Type'));
return this.http.post(this.changePasswordURL+"?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token') + "&password=" + password, {headers: headers})
//this.http.post(this.createUserUrl, user, {headers: headers})
//.subscribe(respuesta =>JSON.stringify(console.log(respuesta)))
}
}
public exist(email: string){
let params = new HttpParams().set('email', email);
params.append('email', email);
return this.http.get(this.checkUserUrl, {params:params})
.map(res =>{console.log("exist----> "+res)});
//.map(res =>{return res});
//.subscribe(res =>{console.log(res)});
//.subscribe(res =>{return res});
}
public doSecureEcho(authToken: string): Observable<any>{
let httpParams = new HttpParams()
.append("mail", "<EMAIL>")
.append("password", "<PASSWORD>")
let headers = new HttpHeaders();
headers = headers.set('x-auth-token', authToken);
headers = headers.append('Content-Type', 'text/xml');
return this.http.get(this.secureEchoUrl, {headers: headers,responseType: 'text'}).pipe(
catchError(new ErrorHandler().handleError('LoginService', null))
);
}
}
<file_sep>/src/app/validators/async-email.validator.ts
import { AbstractControl } from '@angular/forms';
import { UserService } from '../services/user.service';
export class ValidateEmailNotTaken {
public createValidator(userService: UserService) {
return (control: AbstractControl) => {
return userService.exist(control.value).map(res => {
return res ? true : { emailTaken: true };
});
};
}
}
<file_sep>/src/app/services/login.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http';
import { LoginPayload } from './payload/LoginPayload';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import { URLSearchParams } from '@angular/http';
@Injectable()
export class LoginService {
private isUsedId = Constants.BASE_URL + 'loginController/isUsedId';
private passwordByEmail = Constants.BASE_URL + 'loginController/sendPasswordByMail';
private checkUserUrl = Constants.BASE_URL + 'loginController/isUsedId';
private createUserUrl = Constants.BASE_URL + 'systemController/createUser';
private secureEchoUrl = Constants.BASE_URL + 'Sdp/api/secure/echo/andrei';
constructor(private http: HttpClient, private router: Router) { }
public doLogin(payload: LoginPayload): Observable<any>{
return this.http.post(this.checkUserUrl, payload, {responseType: 'text'}).pipe(
catchError(new ErrorHandler().handleError('LoginService', null))
);
}
//<EMAIL>
public signin(user: User){
if (user.name !== '' && user.password !== '') { // {3}
console.log("ENTRO"+ user.name);
let bool= this.exist(user.email);
if (!this.exist(user.email)){
console.log("ENTRO"+ user);
//<EMAIL>
//this.http.post(this.checkUserUrl, user, {responseType: 'text'}).subscribe(respuesta =>this.manageLoginResponse(respuesta));
this.http.post(this.createUserUrl, user, {responseType: 'text'})
.subscribe(respuesta =>localStorage.setItem('currentUser', JSON.stringify({ token: respuesta })))
let currentUser = JSON.parse(localStorage.getItem('currentUser'));
localStorage.setItem('token',currentUser.token);
localStorage.setItem('userName',currentUser.name);
//localStorage.setItem('userID',currentUser.userID);
this.router.navigate(['/home']);
}
else{
console.log("NO EXISTIO: "+user.email);
}
}
}
public exist(email: string){
console.log(this.checkUserUrl);
let params = new HttpParams().set('email', email);
params.append('email', email);
console.log("paramsssss= " + params);
return this.http.get(this.checkUserUrl, {params:params})
.subscribe(respuesta =>{return respuesta});
}
public doSecureEcho(authToken: string): Observable<any>{
let headers = new HttpHeaders();
headers = headers.set('x-auth-token', authToken);
headers = headers.append('Content-Type', 'text/xml');
return this.http.get(this.secureEchoUrl, {headers: headers,responseType: 'text'}).pipe(
catchError(new ErrorHandler().handleError('LoginService', null))
);
}
getIsUsedId(eMail: string): boolean{
if (eMail!== '') { // {3}
console.log("email: "+ eMail);
this.http.post(this.passwordByEmail, eMail, {responseType: 'text'})
.subscribe(respuesta =>localStorage.setItem('currentUser', JSON.stringify({ token: respuesta })))
return true;
}
}
recuperarPassword(eMail: string): Observable<any>{
if (eMail!== '') { // {3}
console.log("email!!!!! : "+ eMail);
let headers = new HttpHeaders();
headers = headers.append('Content-Type', 'text/xml');
//this.http.post(this.checkUserUrl, user, {responseType: 'text'}).subscribe(respuesta =>this.manageLoginResponse(respuesta));
return this.http.get(this.passwordByEmail + "?email=" + eMail)
//localStorage.setItem('userID',currentUser.userID);
}
}
getPasswordByEmail(eMail: string ){
if (eMail!== '') { // {3}
console.log("email: "+ eMail);
//this.http.post(this.checkUserUrl, user, {responseType: 'text'}).subscribe(respuesta =>this.manageLoginResponse(respuesta));
this.http.post(this.passwordByEmail, eMail, {responseType: 'text'})
.subscribe(respuesta =>localStorage.setItem('currentUser', JSON.stringify({ token: respuesta })))
//localStorage.setItem('userID',currentUser.userID);
this.router.navigate(['/home']);
}
}
}
<file_sep>/src/app/services/payload/TokenParams.ts
export class TokenParams{
token_type: string;
token: string;
}
<file_sep>/src/app/services/home.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams} from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
@Injectable()
export class HomeService {
private dashBoardUrl = Constants.BASE_URL + 'systemController/getDashBoard';
constructor(
private http: HttpClient
) { }
getDashBoard(email: string, token: string): Observable<any>{
return this.http.post(this.dashBoardUrl + "?email=" + email + "&token=" + token , {responseType: 'text'})
//.pipe(catchError(new ErrorHandler().handleError('LoginService', null)));
}
}
<file_sep>/src/app/components/create-user/create-user.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
//import { AuthService, GoogleLoginProvider } from "angular5-social-login";
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
//[ existingMobileNumberValidator(this.userService),
@Component({
selector: 'app-create-user',
templateUrl: './create-user.component.html',
styleUrls: []
})
export class CreateUserComponent implements OnInit {
registerForm: FormGroup;
// role: FormGroup;
submitted = false;
emailExists:boolean;
successfullySaved = false;
errorSaved = false;
buttonDisabled: boolean = false;
private formSubmitAttempt: boolean; // {2}
rolesList = [{'name':'ADMIN'},{'name':'TUTOR'}]
constructor(
private userService: UserService,
private http: HttpClient,
private router: Router,
private fb: FormBuilder,
private authService: AuthService,
private modalService: NgbModal
)
{ }
ngOnInit() {
this.registerForm = this.fb.group({ // {5}
name: ['', Validators.required],
secondName: ['', Validators.required],
email: ['',
[Validators.required,Validators.email]],
roles: ['',Validators.required]
// roles: this.fb.group({
// rolname:['']
// })
});
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
return;
}
else{
if(this.registerForm.value.roles == "TUTOR"){
this.registerForm.value.roles= [{'name':'TUTOR'}]
}else{
this.registerForm.value.roles= [{'name':'ADMIN'}]
}
this.userService.createUser(this.registerForm.value).subscribe(res =>{
console.log("DATOOOOS " + JSON.stringify(res) + " +++++++");
console.log("DATOOOOS " + JSON.stringify(res['code']));
console.log(typeof res['code']);
if(res['code']==0){
this.successfullySaved = true;
this.openModal("Usuario creado", "","success","success");
this.submitted = false;
this.registerForm.reset();
//alert("")
}
else{
this.errorSaved = true;
this.openModal("Error al crear usuario", "","success","success");
// alert("Error al crear usuario")
}
})
}
}
goToLogin(){
this.router.navigate(['login']);
}
isFieldInvalid(field: string) { // {6}
return (
(!this.registerForm.get(field).valid && this.registerForm.get(field).touched) ||
(this.registerForm.get(field).untouched && this.formSubmitAttempt)
);
}
userExist(){
let value = this.userService.exist(this.registerForm.controls['email'].value);
//console.log(value);
this.registerForm.controls['email'].setErrors({'incorrect': value});
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.type = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/models/User.ts
export class Role{
"desc":string;
"id":string;
"name":string
}
export class User {
name: string;
secondName: string;
Name: string;
email: string;
googleMail: string;
password: string;
passwordGoogle: string;
roles:Role;
}
<file_sep>/src/app/components/change-password/change-password.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
//import { AuthService, GoogleLoginProvider } from "angular5-social-login";
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule,ActivatedRoute} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
@Component({
selector: 'app-change-password',
templateUrl: './change-password.component.html',
styleUrls: []
})
export class ChangePasswordComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
constructor(
private userService: UserService,
private http: HttpClient,
private router: Router,
private fb: FormBuilder,
private modalService: NgbModal,
private route: ActivatedRoute
) {}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
ngOnInit() {
this.registerForm = this.fb.group({ // {5}
password: ['', [Validators.required,Validators.minLength(6)]],
confirmation: ['', Validators.required]
});
}
onSubmit() {
this.submitted = true;
if (this.registerForm.invalid) {
return;
}
if(this.registerForm.value.password==this.registerForm.value.confirmation){
this.openModal("¿Esta seguro de querer reestablecer la contraseña?","Haga click en 'Confirmar' para reestablecer su contraseña o en 'Cerrar' para cancelar la accion","confirm","modificar")
}
else
{
this.openModal("Error: Las contraseñas no coinciden","Los campos 'Password' y 'Confirmacion' deben coincidir, modifiquielo e intentelo otra vez","error","error")
}
}
changePassword(){
this.userService.changePassword(this.registerForm.get("password").value).subscribe((res)=>{
this.openModal("Contraseña modificada","","success","success")
console.log("recuperarContrasena "+ JSON.stringify(res));
})
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
if(result=="modificar"){
this.changePassword()
}
if(result=="exito"){
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/components/edit-profile/edit-profile.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
@Component({
selector: 'app-edit-profile',
templateUrl: './edit-profile.component.html',
styleUrls: []
})
export class EditProfileComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
emailExists:boolean; // {1}
private formSubmitAttempt: boolean; // {2}
role= "";
constructor(
private userService: UserService,
private http: HttpClient,
private router: Router,
private fb: FormBuilder,
private authService: AuthService,
private modalService: NgbModal,
//private user: User
)
{ }
ngOnInit() {
this.getAllUsers();
this.registerForm = this.fb.group({ // {5}
name: ['', Validators.required],
secondName: ['', Validators.required],
email: [sessionStorage.getItem('email'),
[Validators.required,Validators.email]]
});
}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
onSubmit() {
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
this.openModal("Error al editar perfil", "Uno o mas campos son incorrectos, complete los campos correctamente y vuelva a intentarlo","error","error");
return;
}
else{
this.openModal("¿Esta seguro de modificar su perfil?", "Haga click en 'Confirmar' para modificar el perfil o en 'Cerrar' para cancelar la accion",'confirm',"edit")
}
}
editarPerfil(){
console.log("MIS DATOS "+ this.registerForm.value)
this.userService.modifyUser(this.registerForm.value).subscribe(res =>{
this.openModal("Perfil modificado", "","success","success");
})
}
goToLogin(){
this.router.navigate(['login']);
}
isFieldInvalid(field: string) { // {6}
return (
(!this.registerForm.get(field).valid && this.registerForm.get(field).touched) ||
(this.registerForm.get(field).untouched && this.formSubmitAttempt)
);
}
userExist(){
let value = this.userService.exist(this.registerForm.controls['email'].value);
console.log(value);
this.registerForm.controls['email'].setErrors({'incorrect': value});
}
getAllUsers(){
this.userService.getAllUsers().subscribe(res=>{
res['result'].forEach(variable => {
if(variable.email==sessionStorage.getItem('email')){
// this.user = variable;
this.registerForm.setValue({
name: variable.name,
secondName: variable.secondName,
email:sessionStorage.getItem('email')
//enablecheck: this.fileList[event.target.value].enable
});
this.role=variable.roles[0].name;
}
});
//this.user = res['result'];
})
}
goToChangePassword(){
this.router.navigate(['change-password']);
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
if(result=='edit'){
this.editarPerfil();
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/utils/Constants.ts
export class Constants{
static BASE_URL:string = "http://ec2-18-215-158-201.compute-1.amazonaws.com:8888/";
//static BASE_URL:string = "http://localhost:8080/";
}
<file_sep>/src/app/utils/modal/modal.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap';
@Component({
selector: 'app-modal',
templateUrl: './modal.component.html',
styleUrls: []
})
export class ModalComponent implements OnInit {
@Input() text = ``;
@Input() type = ``;
@Input() title = ``;
@Input() action = ``;
constructor(
public activeModal: NgbActiveModal,
)
{
console.log("DATA MODAL> "+ this.text + " " +this.type + " " +this.title + " " +this.action)
}
closeModal() {
this.activeModal.close('Modal Closed');
}
ngOnInit() {
console.log("TEXT: "+ this.text + " TYPE: " +this.type + " TITLE: " +this.title + " ACTION: " +this.action)
}
}
<file_sep>/src/app/validators/unique-email-validator.directive.ts
import { Directive } from '@angular/core';
import { NG_ASYNC_VALIDATORS, AsyncValidator, AbstractControl, ValidationErrors } from '@angular/forms';
import { UserService } from '../services/user.service';
import { Observable} from 'rxjs';
import { map} from 'rxjs/operators';
@Directive({
selector: '[uniqueEmail]',
providers:[
{
provide: NG_ASYNC_VALIDATORS,
useExisting:UniqueEmailValidatorDirective,
multi: true
}
]
})
export class UniqueEmailValidatorDirective implements AsyncValidator {
constructor(private userService:UserService) { }
validate(c:AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null >{
return this.userService.exist(c.value).pipe(
map(res =>{
return (res) ? {'uniqueEmail': true} : null;
})
);
}
}
<file_sep>/src/app/components/analyze/analyze.component.ts
import { Component, OnInit } from '@angular/core';
import { FileService } from '../../services/file.service';
import { AnalyzeService } from '../../services/analyze.service';
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
@Component({
selector: 'app-analyze',
templateUrl: './analyze.component.html',
styleUrls: []
})
export class AnalyzeComponent implements OnInit {
fileToAnalize:string;
fileList = [];
filesToCompare = [];
sharedFileList = [];
filesToCompareShared = [];
allFilesToCompare = [];
buttonDisabled : boolean = false;
selectedAll: boolean = false;
selectedAllShared: boolean = false;
constructor(
private analyzeService: AnalyzeService,
private fileService: FileService,
private http: HttpClient,
private router: Router,
private fb: FormBuilder,
private authService: AuthService,
private modalService: NgbModal
) {
this.fileToAnalize = '-1';
this.getAllUserFiles();
this.getSharedFiles();
}
doAnalysis(){
this.analyzeService.iniciarAnalisis(this.fileToAnalize,this.allFilesToCompare).subscribe(res=>{
console.log("ANALISIS " + JSON.stringify(res));
this.openModal("Analisis Iniciado","Podes ver el estado de este y otros analisis en la pestaña Reportes.","success","success")
this.uncheckAll();
});
}
onSubmit(){
// console.log("polo " + this.fileToAnalize);
this.allFilesToCompare= this.filesToCompare.concat(this.filesToCompareShared);
console.log("ARRAY A ANALIZAR " + this.allFilesToCompare);
if(this.fileToAnalize=="-1"){
this.openModal("No se inició el analisis","Seleccione documento a analizar y vuelva a intentarlo.","error","error")
}else
{
console.log("polo 2 " + this.allFilesToCompare.length);
if(this.allFilesToCompare.length == 0){
this.openModal("No se inició el analisis","Seleccione 1 o mas archivos de la lista para comparar y vuelva a intentarlo.","error","error")
}else{
this.openModal("¿Esta seguro de querer iniciar el analisis?","Haga click en 'Confirmar' para iniciar el analisis o en 'Cerrar' para cancelar la accion","confirm","analyze")
}
}
}
ngOnInit() {
// this.fileToAnalize = '-1';
// this.getAllUserFiles();
// this.getSharedFiles();
}
uncheckAll(){
for (var i = 0; i < this.fileList.length; i++) {
this.fileList[i].selected = this.selectedAll;
}
this.filesToCompare =[];
}
uncheckAllShared(){
for (var i = 0; i < this.sharedFileList.length; i++) {
this.sharedFileList[i].selected = this.selectedAllShared;
}
this.filesToCompareShared =[];
}
onSelectAll(isChecked: boolean){
this.selectedAll = !this.selectedAll;
if(isChecked) {
let aux1 = <any>this.fileList;
this.filesToCompare = aux1.map(a => a.idFile);
for (var i = 0; i < this.fileList.length; i++) {
console.log(" el chekbox ANTES "+ JSON.stringify( this.fileList[i]))
console.log(" this.selectedA "+ this.selectedAll)
this.fileList[i].selected = this.selectedAll;
console.log(" el chekbox DESPUES "+ JSON.stringify( this.fileList[i]))
}
} else {
this.uncheckAll();
// for (var i = 0; i < this.fileList.length; i++) {
// this.fileList[i].selected = this.selectedAll;
// }
//
// this.filesToCompare =[];
}
console.log(this.filesToCompare)
}
onSelectAllShared(isChecked: boolean){
this.selectedAllShared = !this.selectedAllShared;
console.log("selectedAllShared "+ this.selectedAllShared)
if(isChecked) {
console.log("ENTRO AL IF "+ this.selectedAllShared)
let aux = <any>this.sharedFileList;
this.filesToCompareShared = aux.map(a => a.idFile);
console.log("selectedAllShared "+ this.selectedAllShared)
for (var i = 0; i < this.sharedFileList.length; i++) {
console.log(" el chekbox ANTES "+ JSON.stringify( this.sharedFileList[i]))
console.log(" this.selectedAllShared "+ this.selectedAllShared)
this.sharedFileList[i].selected = this.selectedAllShared;
console.log(" el chekbox DESPUES "+ JSON.stringify( this.sharedFileList[i]))
}
} else {
this.uncheckAllShared();
// for (var i = 0; i < this.fileList.length; i++) {
// this.fileList[i].selected = this.selectedAll;
// }
//
// this.filesToCompare =[];
}
console.log(this.filesToCompareShared)
}
checkIfAllSelected(){
if (this.fileList.length == this.filesToCompare.length){
this.selectedAll = true;
}
this.selectedAll = false;
}
checkIfAllSelectedShared(){
console.log("all selected shared???")
if (this.sharedFileList.length == this.filesToCompareShared.length){
this.selectedAllShared = true;
console.log("YES")
}
this.selectedAllShared = false;
console.log("NO")
}
onChangeShared(id: string, isChecked: boolean) {
if(isChecked) {
this.filesToCompareShared.push(id);
console.log(JSON.stringify(this.sharedFileList.length) + " " + JSON.stringify(this.filesToCompareShared.length))
if (this.sharedFileList.length == this.filesToCompareShared.length){
console.log("SI!!! SELECCIONASTE TODOS LOS ELEMENTOS De la tabla shared")
this.selectedAllShared = true;
}else{
console.log("NO!!! SELECCIONASTE TODOS LOS ELEMENTOS De la tabla shared")
this.selectedAllShared = false;
}
} else {
let index = this.filesToCompareShared.indexOf(id);
this.filesToCompareShared.splice(index,1);
if(this.selectedAllShared){
this.selectedAllShared = false;
}
}
console.log(this.filesToCompareShared)
}
onChange(id: string, isChecked: boolean) {
//Check if all is Selected
if(isChecked) {
this.filesToCompare.push(id);
console.log(JSON.stringify(this.fileList.length) + " " + JSON.stringify(this.filesToCompare.length))
if (this.fileList.length == this.filesToCompare.length){
console.log("SI!!! SELECCIONASTE TODOS LOS ELEMENTOS")
this.selectedAll = true;
}else{
console.log("NO!!! SELECCIONASTE TODOS LOS ELEMENTOS")
this.selectedAll = false;
}
} else {
let index = this.filesToCompare.indexOf(id);
this.filesToCompare.splice(index,1);
if(this.selectedAll){
this.selectedAll = false;
}
}
console.log(this.filesToCompare)
}
onOptionSelected(event){
console.log(event.target.value);
this.fileToAnalize = event.target.value;
}
getAllUserFiles(){
this.fileService.userFilesList(sessionStorage.getItem('email'),sessionStorage.getItem('token'))
.subscribe(res => {
if (JSON.stringify(res['result'])!= "[]"){
this.fileList = res['result'];
console.log("PROBANDO!" + JSON.stringify(res['result']));
console.log("PROBANDO!" + res['result'].length);
this.fileList.forEach(function(obj) { obj.selected = false });
// for(let i = 0 ;i < res['result'].length;i++){
// this.names.push({ name : JSON.stringify(res['result'][i].idFile), selected : false })
// }
// console.log("testeo " + JSON.stringify(this.names));
}
console.log("lista files " + JSON.stringify(this.fileList));
});
}
getSharedFiles(){
this.fileService.getSharedFiles(sessionStorage.getItem('email'),sessionStorage.getItem('token'))
.subscribe(res => {
if (JSON.stringify(res['result'])!= "[]"){
this.sharedFileList = res['result'];
}
console.log("lista shared" + this.sharedFileList);
});
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+ result);
if(result=="analyze"){
this.doAnalysis()
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/services/analyze.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams } from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Session } from '../auth/loginData';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import {URLSearchParams} from '@angular/http';
@Injectable()
export class AnalyzeService {
private iniciarAnalisisUrl = Constants.BASE_URL + 'systemController/iniciarAnalisis/';
private analisisListUrl = Constants.BASE_URL + 'systemController/listarAnalisisPorUsuario/';
private obtenerResultadoAnalisisUrl = Constants.BASE_URL + 'systemController/reporteAnalisis';
constructor(private http:HttpClient) { }
public iniciarAnalisis(fileToAnalize, corpus): Observable<any>{
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
let body = {
"credentials": {
"mail": sessionStorage.getItem('email'),
"password": "<PASSWORD>",
"roleDTOs": [
{
"desc": "string",
"id": 0,
"name": "string"
}
],
"token": sessionStorage.getItem('token')
},
"fileToAnalyze": fileToAnalize,
"filesToCompare": corpus,
"finishDate": "2018-09-04T18:33:45.716Z",
"idAnalize": 0,
"initialDate": "2018-09-04T18:33:45.716Z",
"terminado": true
}
return this.http.post(this.iniciarAnalisisUrl,body,{headers: headers});
}
// public getReportList(): Observable<any>{
// return this.http.post(this.obtenerResultadoAnalisisUrl + "?email=" + sessionStorage.getItem('email') + "&token=" + sessionStorage.getItem('token') , {responseType: 'text'}).pipe(
// catchError(new ErrorHandler().handleError('LoginService', null))
// );
// }
public listarAnalisisPorUsuario(): Observable<any>{
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
let body = {
"mail": sessionStorage.getItem('email'),
"password": "<PASSWORD>",
"roleDTOs": [
{
"desc": "string",
"id": 0,
"name": "string"
}
],
"token": sessionStorage.getItem('token')
}
return this.http.post(this.analisisListUrl,body,{headers: headers});
}
reporteAnalisis(email: string, token: string, idAnalisis: string) { //get file from service
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
let url = this.obtenerResultadoAnalisisUrl + "?email=" + email + "&token=" + token + "&idAnalisis=" + idAnalisis
return this.http.get(url,{ headers: headers, responseType: 'blob' })
}
}
<file_sep>/src/app/services/file.service.ts
import { Injectable } from '@angular/core';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders,HttpParams} from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions } from '@angular/http';
import { Session } from '../auth/loginData';
import { ResponseContentType,RequestMethod } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
import { User } from '../models/User';
import { URLSearchParams } from '@angular/http';
@Injectable()
export class FileService {
private fileListUrl = Constants.BASE_URL + 'documentController/listUserFiles';
private sharedFilesUrl = Constants.BASE_URL + 'documentController/listSharedFiles/';
private downloadFileUrl = Constants.BASE_URL + 'documentController/downloadUserFiles/';
private downloadFileGoogleUrl = 'https://www.googleapis.com/drive/v3/files/';
private removeFileFromUserUrl = Constants.BASE_URL +'/documentController/removeFileFromUser';
//documentController/download/{fileID}/{email}/{token}
//documentController//downloadUserFiles/{email}/{token}/{fileID}/
constructor(private http:HttpClient) { }
public userFilesList(email: string, token: string): Observable<any>{
console.log("console log: " + this.fileListUrl);
return this.http.post(this.fileListUrl + "?email=" + email + "&token=" + token , {responseType: 'text'})
//.pipe(catchError(new ErrorHandler().handleError('LoginService', null)));
}
public getSharedFiles(email: string, token: string): Observable<any>{
return this.http.post(this.sharedFilesUrl + "?email=" + email + "&token=" + token , {responseType: 'text'})
//.pipe(catchError(new ErrorHandler().handleError('LoginService', null)));
}
downloadFile(email: string, token: string, fileId: string) { //get file from service
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
let url = this.downloadFileUrl + "?email=" + email + "&token=" + token + "&fileID=" + fileId
return this.http.get(url,{ headers: headers, responseType: 'blob' })
}
deleteFile(email: string, token: string, fileId: string) { //get file from service
let headers = new HttpHeaders();
headers = headers.set('Accept', 'application/pdf');
let url = this.removeFileFromUserUrl + "?email=" + email + "&token=" + token + "&fileID=" + fileId
return this.http.post(url,{ headers: headers, responseType: 'text' })
}
// http://localhost:8888/documentController/listUserFiles?email=<EMAIL>&token=<PASSWORD>
}
<file_sep>/src/app/components/edit-user/edit-user.component.ts
import { Component, OnInit } from '@angular/core';
import { UserService} from '../../services/user.service';
//import { AuthService, GoogleLoginProvider } from "angular5-social-login";
import { HttpClient} from '@angular/common/http'
import { Router,Routes, RouterModule} from '@angular/router';
import { FormGroup, FormBuilder, Validators, FormControl, AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { AuthService } from '../../auth/auth.service';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import { NgbModal,NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
@Component({
selector: 'app-edit-user',
templateUrl: './edit-user.component.html',
styles: []
})
export class EditUserComponent implements OnInit {
registerForm: FormGroup;
submitted = false;
emailExists:boolean; // {1}
fileList = [];
optionSelected: any;
enable:boolean;
private formSubmitAttempt: boolean; // {2}
private isChecked: boolean
rolesList = [{'name':'ADMIN'},{'name':'TUTOR'}]
constructor(
private userService: UserService,
private http: HttpClient,
private router: Router,
private fb: FormBuilder,
private authService: AuthService,
private modalService: NgbModal
) {}
// convenience getter for easy access to form fields
get f() { return this.registerForm.controls; }
ngOnInit() {
this.getAllUsers();
this.registerForm = this.fb.group({ // {5}
name: ['', Validators.required],
secondName: ['', Validators.required],
email: ['',
[Validators.required,Validators.email]],
roles: ['',Validators.required]
//passwordGoogle:['<PASSWORD>', Validators.required],
});
}
onSubmit(){
this.submitted = true;
// stop here if form is invalid
if (this.registerForm.invalid) {
this.openModal("Error al editar perfil", "Uno o mas campos son incorrectos, complete los campos correctamente y vuelva a intentarlo","error","error");
return;
}
else{
if(this.registerForm.value.roles == "TUTOR"){
this.registerForm.value.roles= [{'name':'TUTOR'}]
}else{
this.registerForm.value.roles= [{'name':'ADMIN'}]
}
this.openModal("¿Esta seguro de modificar su Usuario?", "Haga click en 'Confirmar' para modificar el usuario o en 'Cerrar' para cancelar la accion",'confirm',"edit")
}
}
editUser() {
console.log("valores para Edit usuer: "+ JSON.stringify(this.registerForm.value))
this.userService.modifyUser(this.registerForm.value).subscribe(res =>{
if(true){
this.getAllUsers();
this.openModal("Usuario modificado", "","success","success");
}
else{
// alert("Error al crear usuario")
}
})
}
getAllUsers(){
this.userService.getAllUsers().subscribe(res=>{
console.log('RES!!!'+JSON.stringify(res['result']) );
this.fileList = res['result'];
})
}
onOptionSelected(event){
console.log("cheked : "+ this.isChecked);
console.log(event); //option value will be sent as event
this.optionSelected = event.target.value;
console.log("REtencion "+ event.target.value.enable);
//this.isChecked=this.fileList[event.target.value].enable
console.log("cheked : "+ this.isChecked);
this.registerForm.setValue({
name: this.fileList[event.target.value].name,
secondName: this.fileList[event.target.value].secondName,
email: this.fileList[event.target.value].email,
roles: this.fileList[event.target.value].roles[0].name
//enablecheck: this.fileList[event.target.value].enable
});
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
console.log("resultados del modal "+result);
if(result=='edit'){
this.editUser()
}
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/auth/storageService.ts
import {Injectable} from '@angular/core';
import {Router, CanActivate, RouterStateSnapshot, ActivatedRouteSnapshot} from '@angular/router';
import {AuthService} from './auth.service';
import {Subject} from 'rxjs/Subject';
import {Observable} from 'rxjs/Observable';
@Injectable()
export class StorageService {
private storageSub = new Subject<boolean>();
watchStorage(): Observable<any> {
return this.storageSub.asObservable();
}
setItem(key: string, data: any) {
sessionStorage.setItem(key, data);
this.storageSub.next(data);
}
removeItem(key) {
sessionStorage.removeItem(key);
this.storageSub.next(null);
}
}
<file_sep>/src/app/validators/emailTaken.validator.ts
import { AsyncValidatorFn, AbstractControl, ValidationErrors } from '@angular/forms';
import { Observable } from "rxjs/Observable";
import 'rxjs/add/operator/map';
import {UserService} from '../services/user.service';
export function emailTaken(userService: UserService): AsyncValidatorFn {
return (control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null> => {
return userService.exist(control.value).map(
res => {
return (res) ? {"emailExists": true} : null;
}
);
};
}
<file_sep>/src/app/components/google-drive/google-drive.component.ts
import { Component, NgZone, OnInit } from "@angular/core";
import { AppContext } from "../../../infrastructure/app.context";
import { FileInfo, MIME_TYPE_FOLDER } from "../../../model/fileInfo"
import { BreadCrumbItem } from "../../../model/breadCrumbItem";
import { MatTableDataSource } from "@angular/material/table";
import { BreadCrumbItemOption, OPTION_NEW_FOLDER, OPTION_UPLOAD_FILES } from "../../../model/breadCrumbItemOption";
import { MatDialog } from "@angular/material/dialog";
import { DialogOneInputComponent } from "../dialogoneinput/dialogoneinput.component"
import { DialogOneInputData } from "../../../model/dialogOneInputData"
import { MatBottomSheet } from '@angular/material';
import { HttpClient, HttpEventType, HttpHeaders } from '@angular/common/http';
import { Constants } from '../../utils/Constants';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../../utils/modal/modal.component';
import { Router } from "@angular/router";
@Component({
selector: "google-drive",
templateUrl: "./google-drive.component.html",
styleUrls: []
})
export class GoogleDriveComponent implements OnInit{
breadCrumbItems: BreadCrumbItem[] = [];
dataSource: MatTableDataSource<FileInfo>;
//displayedColumns: string[] = ["icon", "name", "modifiedTime", "size", "delete"];
displayedColumns: string[] = ["icon", "name", "modifiedTime", "size"];
files: FileInfo[] = [];
isSignedIn: boolean = this.appContext.Session.Gapi.isSignedIn;
email: string;
public uploadFile = Constants.BASE_URL + 'documentController/addFileToUser';
public buttonDisabled: boolean = false;
public porcentaje=''
constructor(
private appContext: AppContext,
private router: Router,
private zone: NgZone,
public dialog: MatDialog,
private bottomSheet: MatBottomSheet,
private http: HttpClient,
private modalService: NgbModal
) {
console.log("TEST FILES "+ JSON.stringify(this.files))
this.dataSource = new MatTableDataSource(this.files);
}
onRefresh(){
this.refresh("root");
}
signIn(){
this.appContext.Session.Gapi.signIn().then(() => {
if(this.appContext.Session.Gapi.isSignedIn){
this.isSignedIn = this.appContext.Session.Gapi.isSignedIn;
console.log("ESTAS LOGUEADO")
this.appContext.Session.BreadCrumb.init();
this.breadCrumbItems = this.appContext.Session.BreadCrumb.items;
this.refresh("root");
}
else
console.log("NO ESTAS LOGUEADO")
});
}
singOut(){
this.appContext.Session.Gapi.signOut();
this.refresh("root");
}
browse(file: FileInfo) {
if (file.IsFolder) {
this.appContext.Repository.File.getFiles(file.Id)
.then((res) => {
this.zone.run(() => {
this.files = res;
this.dataSource.data = this.files;
this.appContext.Session.BreadCrumb.navigateTo(file.Id, file.Name);
this.breadCrumbItems = this.appContext.Session.BreadCrumb.items;
});
});
}
}
createNewFolder() {
var data: DialogOneInputData = new DialogOneInputData();
data.DefaultInputText = "Untitled folder";
data.Title = "New folder"
const dialogRef = this.dialog.open(DialogOneInputComponent, {
width: '250px',
data: data
});
dialogRef.afterClosed().subscribe(result => {
if (result) {
this.appContext.Repository.File.create(
this.appContext.Session.BreadCrumb.currentItem.Id,
result)
.then(() => {
this.refresh(this.appContext.Session.BreadCrumb.currentItem.Id);
});
}
});
}
delete(file: FileInfo) {
var index = this.files.indexOf(file);
if (index > -1) {
this.files.splice(index, 1);
this.appContext.Repository.File.delete(file.Id)
.then(() => {
this.zone.run(() => {
this.dataSource.data = this.files;
console.log("Delete successfully");
});
});
}
}
ngOnInit(): void {
console.log("isSignedIn 1 " +this.isSignedIn);
this.isSignedIn = this.appContext.Session.Gapi.isSignedIn;
this.appContext.Session.BreadCrumb.init();
this.breadCrumbItems = this.appContext.Session.BreadCrumb.items;
this.refresh("root");
console.log("isSignedIn 2 " +this.isSignedIn);
}
logout(): void{
}
onSelectedItemChanged($event: BreadCrumbItem) {
let fileInfo: FileInfo = new FileInfo();
fileInfo.Id = $event.Id;
fileInfo.Name = $event.Name;
fileInfo.MimeType = MIME_TYPE_FOLDER;
this.browse(fileInfo);
}
// onSelectedOptionChanged($event: BreadCrumbItemOption) {
// if ($event.Option === OPTION_NEW_FOLDER) {
// this.createNewFolder();
// }
// else if ($event.Option === OPTION_UPLOAD_FILES) {
// // this.importByUrl();
// this.bottomSheet.open(FilesUploadComponent, { data: $event.Data });
// }
// }
refresh(fileId: string) {
this.appContext.Repository.File.getFiles(fileId)
.then((res) => {
this.zone.run(() => {
this.files = res;
console.log('files: ' + JSON.stringify(res))
this.dataSource.data = this.files;
});
});
}
downloadFile(fileID: string,name:string ){
console.log("downloadFile");
console.log("entro!!! " + fileID)
console.log("%c entro!!!, {color= orange} " + fileID);
//console.log("GOOGLE AUTH: " + JSON.stringify(this.appContext.Session.Gapi.googleAuth));
this.appContext.Repository.File.downloadFileGoogle(fileID)
.subscribe(res => {
console.log("ENTRO AL BLOB!!!!!! " + res);
console.log("entro string !!! " + JSON.stringify(res));
var file = new Blob([res], {type: 'application/pdf'});
let fd=new FormData();
fd.append("blob",file, name);
this.upload(file,name)
//this.showFile(file)
});
}
upload(file:Blob, name:string){
this.buttonDisabled=true;
const fd = new FormData();
console.log("ULPLOAD()")
fd.append('file',file, name )
console.log("Archivo a subir" + file)
console.log("Archivo a subir" + JSON.stringify(file) )
this.http.post(this.uploadFile + "?email=" + sessionStorage.email + "&token=" + sessionStorage.token ,fd,{
reportProgress: true,
observe:'events'
})
.subscribe(event => {
if(event.type === HttpEventType.UploadProgress){
this.porcentaje = Math.round(event.loaded / event.total * 100) + "%";
//console.log('Upload Progress: '+ this.porcentaje)
}else if(event.type === HttpEventType.Response){
this.buttonDisabled = false;
//this.getAllUserFiles();
console.log("EVENT " + JSON.stringify(event));
console.log("EVENT " + JSON.stringify(HttpEventType.Response));
console.log("EVENT CODE" + JSON.stringify(event['body']['code']));
if(JSON.stringify(event['body']['code']) == '1'){
this.openModal(JSON.stringify(event['body']['message']),'El archivo ya existe en el sistem o fue eliminado.',"error","error");
}
if(JSON.stringify(event['body']['code']) == '0'){
this.openModal(JSON.stringify(event['body']['message']),'' ,"success","success");
}
}
});
}
showFile(blob){
console.log("size!!! " + blob.size);
// IE doesn't allow using a blob object directly as link href
// instead it is necessary to use msSaveOrOpenBlob
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
// For other browsers:
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(blob);
console.log("data windows url !!! " + JSON.stringify(data));
var link = document.createElement('a');
link.href = data;
link.download="file.pdf";
console.log("data file url !!! " + JSON.stringify(link));
link.click();
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
}).catch((error) => {
console.log(error);
});
}
}
<file_sep>/src/app/auth/auth.service.ts
import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';
import { BehaviorSubject } from 'rxjs';
import { Login, Logout, Session} from './loginData';
import { Constants } from '../utils/Constants';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { ErrorHandler } from '../utils/ErrorHandler';
import { RequestOptions, Headers } from '@angular/http';
import { catchError } from 'rxjs/operators';
import { StorageService } from './storageService';
import { NgbModal, NgbModalOptions } from '@ng-bootstrap/ng-bootstrap';
import { ModalComponent } from '../utils/modal/modal.component';
//import {Headers, RequestOptions} from 'angular2/http';
@Injectable()
export class AuthService {
private loggedIn = new BehaviorSubject<boolean>(false); // {1}
private loginUrl = Constants.BASE_URL + 'loginController/login';
private logoutUrl = Constants.BASE_URL + 'loginController/logout/';
private secureEchoUrl = Constants.BASE_URL + 'Sdp/api/secure/echo/andrei';
private isLoggedInUrl = Constants.BASE_URL + 'loginController/isLoggedIn';
get isLoggedIn() {
console.log("TOKEN: " + this.getToken())
if(this.getToken()){
this.loggedIn.next(true);
}
return this.loggedIn.asObservable(); // {2}
}
public getToken(): string {
return sessionStorage.getItem('token');
}
constructor(
private router: Router,
private http: HttpClient,
private storageService: StorageService,
private modalService: NgbModal
) {}
logout() {
let email = sessionStorage.getItem('email');
let token = sessionStorage.getItem('token');
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
console.log('headers' + headers.get('Content-Type'));
this.http.post(this.logoutUrl, {email: email, token: token}, {headers: headers})
.subscribe(res => {
sessionStorage.setItem('token','');
sessionStorage.setItem('email','');
sessionStorage.setItem('role','');
this.loggedIn.next(false);
this.router.navigate(['/login']);
});
}
login(login: Login){
console.log("User and password: "+ login);
let headers = new HttpHeaders();
headers = headers.set('Content-Type', 'application/json; charset=utf-8');
this.http.post(this.loginUrl, login, {headers: headers})
.subscribe(res => {
console.log(JSON.stringify("jjjjjjj" + JSON.stringify(res)));
if (JSON.stringify(res['code'])=="0"|| JSON.stringify(res['code'])=="2"){
console.log('SESION ' + JSON.stringify(res['result']));
this.storageService.setItem('token', res['result'][0].token)
this.storageService.setItem('email', res['result'][0].email)
this.storageService.setItem('role', res['result'][0].roles[0].id)
this.loggedIn.next(true);
this.router.navigate(['/home']);
}
else {
this.openModal(res['message'],"","error","error");
}
});
}
openModal(title,text,type,action) {
let ngbModalOptions: NgbModalOptions = {
backdrop : 'static',
keyboard : false
};
const modalRef = this.modalService.open(ModalComponent,ngbModalOptions);
modalRef.componentInstance.title = title;
modalRef.componentInstance.text = text;
modalRef.componentInstance.type = type;
modalRef.componentInstance.action = action;
modalRef.result.then((result) => {
console.log("resultados del modal "+result);
if(result=='edit'){
}
}).catch((error) => {
console.log(error);
});
}
// isLoggedIn(){
//
// let skeleton = {
// "mail": "string",
// "password": "<PASSWORD>",
// "roleDTOs": [
// {
// "desc": "string",
// "id": 0,
// "name": "string"
// }
// ],
// "token": "<PASSWORD>"
// }
//
// let headers = new HttpHeaders();
// headers = headers.set('Content-Type', 'application/json; charset=utf-8');
// headers.append('Access-Control-Allow-Origin','*');
// console.log('headers' + headers.get('Content-Type'));
// return this.http.post(this.allUsersUrl, skeleton, {headers: headers})
// //this.http.post(this.createUserUrl, user, {headers: headers})
// //.subscribe(respuesta =>JSON.stringify(console.log(respuesta))
//
// }
}
<file_sep>/src/app/app.routes.ts
import { RouterModule, Routes } from '@angular/router';
import { FilesComponent } from './components/files/files.component';
import { LoginComponent } from './components/login/login.component';
import { PasswordComponent } from './components/password/password.component';
import { CreateUserComponent } from './components/create-user/create-user.component';
import { EditUserComponent } from './components/edit-user/edit-user.component';
import { EditProfileComponent } from './components/edit-profile/edit-profile.component';
import { HomeComponent } from './components/home/home.component';
import { AnalyzeComponent } from './components/analyze/analyze.component';
import { ReportsComponent } from './components/reports/reports.component';
import { PageNotFoundComponent } from './components/page-not-found/page-not-found.component';
import { GoogleDriveComponent } from './components/google-drive/google-drive.component';
import { AuthGuard } from './auth/auth.guard';
import { HelpComponent } from './components/help/help.component';
import { NewPasswordComponent } from './components/new-password/new-password.component';
import { ChangePasswordComponent } from './components/change-password/change-password.component';
const APP_ROUTES: Routes = [
{ path: '', redirectTo: 'home', pathMatch: 'full', canActivate: [AuthGuard]},
{ path: 'files', component: FilesComponent, canActivate: [AuthGuard]},
{ path: 'login', component: LoginComponent },
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard]},
{ path: 'password', component: PasswordComponent },
{ path: 'analyze', component: AnalyzeComponent, canActivate: [AuthGuard]},
{ path: 'create-user', component: CreateUserComponent, canActivate: [AuthGuard],data: {
roles: {
only: ['1'],
redirectTo: 'password'
}
}},
{ path: 'edit-user', component: EditUserComponent, canActivate: [AuthGuard]},
{ path: 'edit-profile', component: EditProfileComponent, canActivate: [AuthGuard]},
{ path: 'reports', component: ReportsComponent, canActivate: [AuthGuard]},
{ path: 'google-drive', component: GoogleDriveComponent, canActivate: [AuthGuard]},
{ path: 'help', component: HelpComponent, canActivate: [AuthGuard]},
{ path: 'change-password', component: ChangePasswordComponent, canActivate: [AuthGuard]},
{ path: 'new-password', component: NewPasswordComponent},
//{ path: '**', pathMatch: 'full', redirectTo: '' },
{ path: '**', component: PageNotFoundComponent},
];
export const APP_ROUTING = RouterModule.forRoot(APP_ROUTES);
| fea6898e412c2e266ee849f06bfd506a3c5115f8 | [
"TypeScript"
] | 31 | TypeScript | apastorini/SDAP-GUI | ed4eee8d551374b80d45540937430b6d6411e932 | 9c7e50d7d6298b12a931b1c50923548a952ad4e4 | |
refs/heads/master | <file_sep>public enum Färg {
KLÖVER, RUTER, HJÄRTER, SPADER
}
<file_sep>public enum Nummer {
TVÅ, TRE, FYRA, FEM, SEX, SJU, ÅTTA, NIO, TIO, KNECKT, DAM, KUNG, ESS
}
<file_sep># GameOf21
To play this game you need to:
- have JavaSDK installed
- git clone this repository
- write ```javac src/GameOf21.java``` into the developer console
- write ```java src/GameOf21``` into the developer console
| 778fa802ffc57cba41f56236ff4e4f814c89b559 | [
"Markdown",
"Java"
] | 3 | Java | karolinfrennert/GameOf21 | 06dd1a94483aa76c7eac2b510e743d191c6efb1c | 9b81c212f9a29ca9ad9a95713a11301504ec9c93 | |
refs/heads/master | <repo_name>CASIOuitsu/acr<file_sep>/06laravel/blog/app/Http/Controllers/PagesController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class PagesController extends Controller
{
public function home() // action home
{
$tasks = [
'Go to the store',
'Go to the market',
'Go to work'
];
return view('welcome', [
'tasks' => $tasks,
'text' => 'ACR',
'title' => request('title'), # definido no url ?title=
'escaped' => "<script>alert('something')</script>",
]);
/* alternativas: usando with
return view('welcome')->withTasks($tasks)->withText('ACR');
return view('welcome')->withTasks([
'Go to the store',
'Go to the market',
'Go to work'
]);
return view('welcome')->with([
'tasks' => [
'Go to the store',
'Go to the market',
'Go to work'
],
'text' => 'ACR'
]);
*/
}
public function about(){
return view('about');
}
public function contact(){
return view('contact');
}
}
<file_sep>/06laravel/blog/app/Http/Controllers/ProjectsController.php
<?php
namespace App\Http\Controllers;
use App\Project;
class ProjectsController extends Controller
{
public function index() // action home
{
#$projects = \App\Project::all(); # com namespace. \ para começar na raiz
$projects = Project::all();
#$projects = auth()->user()->projects; # exemplo: projs de user com login atual
#return $projects; // retorna em json
return view('projects.index', ['projects' => $projects]);
#return view('projects.index', compact($projects); # apenas quando mesmo nome
}
public function create() # simples, retorna view que mostra form create
{
return view('projects.create');
}
public function store() # recebe do form e guarda os dados na BD
{
$validated = request()->validate([
'title' => ['required', 'min:1', 'max:255'],
'description' => 'required'
]);
#return $validated;
Project::create($validated); # $validated or attributes
#Project::create(request(['title', 'description'])); # apenas quando mesmo nome usado nas variaveis da view e na base de dados
/* igual a
Project::create([ # atalho create: obriga a usar o campo fillable ou guarded no model App\Project.php
'title' => request('title'),
'description' => request('description')
]);*/
return redirect('/projects');
}
public function storeAlt() # maneira basica, sem atalhos
{
#return request()->all();
#return request('title');
$project = new Project(); // criar novo
// atribuir dados
$project->title = request('title');
$project->description = request('title');
$project->save();
return redirect('/projects');
}
public function show($id)
{
$project = Project::findOrFail($id);
#return $project;
return view('projects.show', compact('project')); # compact ou ['project' => $project]
}
public function showAlt(Project $project) # com argumento, reconhece pelo standard de ter o id no url/route
{
return view('projects.show', compact('project')); # compact apenas quando mesmo nome
}
public function edit($id)
{
#return $id;
$project = Project::findOrFail($id);
return view('projects.edit', compact('project'));
}
public function update($id)
{
$project = Project::findOrFail($id);
$project->update(request(['title', 'description']));
return redirect('/projects');
}
public function updateAlt($id)
{
#dd('hi'); # debug, (die and dump)
##dd(request()->all()); # debug, (die and dump)
$project = Project::findOrFail($id);
$project->title = request('title');
$project->description = request('description');
$project->save();
return redirect('/projects');
}
public function destroy($id)
{
$project = Project::findOrFail($id)->delete();
#$project->delete();
return redirect('/projects');
}
public function first()
{
$project = Project::all()->first(); # funciona sem all()
return view('projects.show', compact('project'));
}
public function last()
{
$project = Project::all()->last(); # tem de ter all()
#$project = Project::last()->get(); # alternativa
return view('projects.show', compact('project'));
}
}
| 5610921bb992c9b3bb17ff7c607e3c8c93e3dddc | [
"PHP"
] | 2 | PHP | CASIOuitsu/acr | 82566d6b30eb0c598de7b4024fda1348ba6be214 | 49d90fb9b427fb09a25040b481e3f9b809eec804 | |
refs/heads/main | <repo_name>ArikeshiS/Insta-backend-API<file_sep>/README.md
# Insta-backend-API
Simple HTTP REST API implementation in GO.
<file_sep>/src/insta-backend-api.go
package main
import (
"log"
"net/http"
"encoding/json"
"io"
"os"
"context"
"fmt"
"time"
"strings"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
type User struct {
Id string `json:"id"`
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"<PASSWORD>"`
}
type Post struct {
Id string `bson:"id"`
Caption string `bson:"caption"`
ImageURL string `bson:"imageurl"`
Timestamp string `bson:"timestamp"`
}
var (
UserProfile *mongo.Collection
UserPost *mongo.Collection
Ctx = context.TODO()
)
func create_user_handler(rw http.ResponseWriter, req *http.Request) {
d := json.NewDecoder(req.Body)
d.DisallowUnknownFields()
var t User
err := d.Decode(&t)
if err != nil {
// bad JSON or unrecognized json field
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
if &t.Id == nil || &t.Name == nil || &t.Email == nil || &t.Password == nil {
http.Error(rw, "missing field 'test' from JSON object", http.StatusBadRequest)
return
}
// optional extra check
if d.More() {
http.Error(rw, "extraneous data after JSON object", http.StatusBadRequest)
return
}
// got the input we expected: no more, no less
out, err := CreateUser(t)
if err != nil {
io.WriteString(rw, "Error creating Post")
return
}
io.WriteString(rw,out+"200 OK - Post was created successfully")
log.Println(t)
}
func find_user_handler(rw http.ResponseWriter, req *http.Request) {
var sample User
usr_id := strings.TrimPrefix(req.URL.Path, "/users/")
log.Println(usr_id)
out, err := FindUser(sample, usr_id)
if err != nil {
io.WriteString(rw, "Error finding user")
return
}
rw.Header().Set("Content-type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusOK)
io.WriteString(rw, out+"\n")
}
func create_post_handler(rw http.ResponseWriter, req *http.Request) {
d := json.NewDecoder(req.Body)
d.DisallowUnknownFields()
var t Post
err := d.Decode(&t)
if err != nil {
// bad JSON or unrecognized json field
http.Error(rw, err.Error(), http.StatusBadRequest)
return
}
if &t.Id == nil || &t.Caption == nil || &t.ImageURL == nil || &t.Timestamp == nil {
http.Error(rw, "missing field 'test' from JSON object", http.StatusBadRequest)
return
}
// optional extra check
if d.More() {
http.Error(rw, "extraneous data after JSON object", http.StatusBadRequest)
return
}
// got the input we expected: no more, no less
out, err := CreatePost(t)
if err != nil {
io.WriteString(rw, "Error creating Post")
return
}
io.WriteString(rw,out+"200 OK - Post was created successfully")
log.Println(t)
}
func find_post_handler(rw http.ResponseWriter, req *http.Request) {
var sample Post
usr_id := strings.TrimPrefix(req.URL.Path, "/posts/")
log.Println(usr_id)
out, err := FindPost(sample, usr_id)
if err != nil {
io.WriteString(rw, "Error finding post")
return
}
rw.Header().Set("Content-type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusOK)
io.WriteString(rw, out+"\n")
}
func findall_post_handler(rw http.ResponseWriter, req *http.Request) {
var sample Post
usr_id := strings.TrimPrefix(req.URL.Path, "/posts/users/")
log.Println(usr_id)
out, err := AllPost(sample, usr_id)
if err != nil {
io.WriteString(rw, "Error finding post")
return
}
rw.Header().Set("Content-type", "text/html; charset=utf-8")
rw.WriteHeader(http.StatusOK)
io.WriteString(rw, out+"\n")
}
func main() {
md_pass := <PASSWORD>("MD_PASS")
client, err := mongo.NewClient(options.Client().ApplyURI("mongodb+srv://arikeshi:%[email protected]/Cluster0?retryWrites=true&w=majority" % md_pass))
if err != nil {
log.Fatal(err)
}
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
if err != nil {
log.Fatal(err)
}
defer client.Disconnect(ctx)
databases, err := client.ListDatabaseNames(ctx, bson.M{})
if err != nil {
log.Fatal(err)
}
fmt.Println("Connected to MongoDB")
db := client.Database("instagram")
UserProfile = db.Collection("user_profile")
UserPost = db.Collection("user_post")
http.HandleFunc("/users", create_user_handler)
http.HandleFunc("/users/", find_user_handler)
http.HandleFunc("/posts", create_post_handler)
http.HandleFunc("/posts/", find_post_handler)
http.HandleFunc("/posts/users/", findall_post_handler)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func CreateUser(b User) (string, error) {
result, err := UserProfile.InsertOne(Ctx, b)
if err != nil {
return "0", err
}
return fmt.Sprintf("%v", result.InsertedID), err
}
func FindUser(b User, usr_id string) (string, error) {
var result User
err := UserProfile.FindOne(Ctx, bson.D{{"id", usr_id}}).Decode(&result)
if err != nil {
fmt.Println(err)
return "0", err
}
fmt.Println(result)
return fmt.Sprintf("%v", result.Id), err
}
func CreatePost(b Post) (string, error) {
result, err := UserPost.InsertOne(Ctx, b)
if err != nil {
log.Fatal(err)
fmt.Println(err)
return "0", err
}
return fmt.Sprintf("%v", result.InsertedID), err
}
func FindPost(b Post, usr_id string) (string, error) {
var result Post
err := UserPost.FindOne(Ctx, bson.D{{"id", usr_id}}).Decode(&result)
if err != nil {
return "0", err
}
fmt.Println(result)
return fmt.Sprintf("%v", result), err
}
func AllPost(b Post, usr_id string) (string, error) {
cursor, err := UserPost.Find(Ctx,bson.D{{"id", usr_id}})
var result bson.D
if err != nil {
log.Fatal(err)
}
defer cursor.Close(Ctx)
for cursor.Next(Ctx){
if err = cursor.Decode(&result); err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
return fmt.Sprintf("%v", result), err
} | 3564ebbfd390469e459a771e2f11e511a2ce0d43 | [
"Markdown",
"Go"
] | 2 | Markdown | ArikeshiS/Insta-backend-API | dac21ad0b02ddd8cf85a296cfbfec9117480275b | f72a75c695ee82cbdf9e7e3196ad2ac1a98a0324 | |
refs/heads/master | <file_sep>import java.util.*;
import java.lang.*;
import java.io.*;
class MST
{
static int V;
static int graph[][] =new int[V][V];
int minKey(int key[], Boolean mstSet[])
{
int min = Integer.MAX_VALUE, min_index=-1;
for (int v = 0; v < V; v++)
if (mstSet[v] == false && key[v] < min)
{
min = key[v];
min_index = v;
}
return min_index;
}
void printMST(int parent[], int n, int graph[][])
{
System.out.println("Edge \tWeight");
for (int i = 1; i < V; i++)
System.out.println(parent[i]+" - "+ i+"\t"+
graph[i][parent[i]]);
}
void primMST(int graph[][])
{
int parent[] = new int[V];
int key[] = new int [V];
Boolean mstSet[] = new Boolean[V];
for (int i = 0; i < V; i++)
{
key[i] = Integer.MAX_VALUE;
mstSet[i] = false;
}
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V-1; count++)
{
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v]!=0 && mstSet[v] == false &&
graph[u][v] < key[v])
{
parent[v] = u;
key[v] = graph[u][v];
}
}
printMST(parent, V, graph);
}
public void readFile(String a){
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(a));
String textInALine;
V= Integer.parseInt(br.readLine());
String[] linetext = new String[V];
String line;
int i =0;
while((line = br.readLine())!= null){
linetext[i] = line;
i++;
}
graph= new int[V][V];
for(int b=0;b<V;b++){
String[] words=linetext[b].split(",");
for(int c=0;c<V;c++){
graph[b][c]=Integer.parseInt(words[c]);
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void out(int V)
{
for(int i =0;i < V ; i++)
{
for(int j =0 ; j< V ; j++)
{
System.out.print(graph[i][j]+" ");
}
System.out.println();
}
}
public static void main (String[] args)
{
MST t = new MST();
t.readFile("MST.txt");
t.out(V);
t.primMST(graph);
}
} | bb6b13e25f680b181d55ef68d6ef9346ab2d6126 | [
"Java"
] | 1 | Java | tranquanghuy141199/Combinatorial-Optimization | 1aeed5d72d7997fd986e0df6f906d547db8f99fe | b4666280be22ddbb9f6ad160759f5ec2e8658fbe | |
refs/heads/master | <file_sep># MovieBrowser
<p align="center"> <img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/android/0.jpg" align="center" height="760" width="448" ></p>
## Motivation
MovieBrowser is a simple read-only app, made for Android and iOS, to get an fast overview of currently popular movies and TVShows. Therefore I made use of an API provided by TheMovieDB. Feel free to check it out, imho the best public movie db API out there.
## Implementation
For the implementation I used a cross-platform framework called React Native. The next section covers my entire development setup:
### Environment
As an editor I used **Visual Studio Code**.
The command `react-native info` gives me this information:
```
React Native Environment Info:
System:
OS: macOS 10.14
CPU: x64 Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
Memory: 1.67 GB / 16.00 GB
Shell: 3.2.57 - /bin/bash
Binaries:
Node: 9.8.0 - ~/.nvm/versions/node/v10.9.0/bin/node
Yarn: 1.3.2 - ~/.yarn/bin/yarn
npm: 6.2.0 - ~/.nvm/versions/node/v10.9.0/bin/npm
Watchman: 4.7.0 - /usr/local/bin/watchman
SDKs:
iOS SDK:
Platforms: iOS 12.0, macOS 10.14, tvOS 12.0, watchOS 5.0
Android SDK:
Build Tools: 23.0.1, 23.0.2, 25.0.0, 25.0.1, 25.0.2, 25.0.3, 26.0.1, 26.0.2, 26.0.3, 27.0.2, 27.0.3, 28.0.0
API Levels: 16, 21, 23, 25, 26, 27, 28
IDEs:
Android Studio: 3.1 AI-173.4819257
Xcode: 10.0/10A255 - /usr/bin/xcodebuild
npmPackages:
react: 16.5.0 => 16.5.0
react-native: 0.57.0 => 0.57.0
```
As you can see I used React Native version `0.57.0`.
For desiging UI elements I usually use `Affinity Designer`.
### Node packages
If you want to have a closer look at the specific versions of the packages, please have a look at the `package.json` (and maybe `package-lock.json`).
This is the list of frameworks that make it happen to realize this project in such short amount of time:
- **Axios**: Easy network request handling
- **Lodash**: Utility framework
- **Shoutem UI**: UI Framework
- **React Navigation**: Javascript based navigation framework
- **Eslint & eslint airbnb config**: Lint javascript code by using the airbnb config as a base.
### Features
The app uses API calls to `Discover Movie`, `Discover TVShows` and `Discover Genre`, where genre is a list of all available movie genres of TMDb. A search for custom input is implemented, which responds movie and tvshow results for a certain keyword. If you are interested in an item, you can tap on the cover and get transitioned to a detail screen where more detailed information are provided.
### Evaluation and Findings
As I'm coming from "native" iOS development, I'm always curious about a comparison between a cross-platform solution and a native one. This comparison usually includes time-to-implement, performance, look-and-feel and fun. Before you read my 2 cents of this you should barely know what my background and level of experience is: I've done various professional iOS projects in the past 2 years. I've gained a basic knowledge in Android development by university and spare time projects. Currently I focus on react-native. I'm heavily using it for over a year now at work and whenever I'm free. I became a fan of javascript and the react component pattern, even if it is against the SOC pattern I learned at university.
That should be enough for now, let's talk about the project:
#### Time-To-Implement
All togheter it took me a full-time week to setup up the project, search for an api, think of a simple design, implement it, write the readme and create the store screenshots. In my opinion that's fair as far as I get an Android and iOS app. If you're really experinced in Android and iOS development, you might be faster with building the UI and doing the setup, but doing network requests feels so easy with javascript and I'm sure this would take me/you a lot longer in Obj-C or Java. In my opinion for such small projects and with these requirements, react-native is conciderable alternative to native development.
#### Performance
React-native is using a bridge to call native elements on every platform. That means a JS-Thread is running while the app is active and interprets the javascript code. That takes some time and surely reduces the speed of the app. It's a bit a trap that you can use react-native for "easily" building native apps that perform like native apps. It is highly recommened to think about what you are doing in every component, for example are you holding references or recreate the same object every render cycle? Do you use `React.Components` or `React.PureComponents`? What's the difference? Why and when do I implement `shouldComponentUpdate`? Those thoughs make the difference between a beginner and an experienced one (Not only that, but I think you get what I'm trying to say). If we now have look at the MovieBrowser, I did everything I know to boost the performance. For example, I used Flatlists, only pass references and use PureComponents. Still, there is a delay for scrolling events on the main page in Android. IOS is fine. Why is this? The reason for that is the implementation of `Flatlist` which is a javascript-based implementation of a Scrollview on Android and iOS. If you ever got in touch with Android development you will know that there is a special way of implementation for lists called `RecyclerView`. If you want the take benefits of it you should either implement it natively and write your own bridge or use an existing one, both ways cause more work.
You always have to balance the input you want to give and the output you can expect and in this case it wouldn't pay off to think of performance improvements in that manner. To sum it up, the performance highly depends on your coding style and experience, but in the end, native makes a difference as it comes to speed and look and feel. Wow, what a nice transition to the next section ;-)
#### Look-And-Feel
There exists a myth that cross-platform feels like hell to use and everybody notices it. That's true....NOT! Same as in the last section you just have to put more effort in development. That means more separate designs for Android and iOS, separate navigation and separate components. Do you want to do that? Probably not. That would ruin you time calculation and the main benefit of cross-platform, wouldn't it? Therefore you should decide wisely. In this project I didn't care that much if it feels "like native" to save time, so I didn't customized the navigation or added a floating button for Android. But I could. That's the point. Coming from web development, bungle some tutorials and bloaded modules togheter and then complain about Look-And-Feel is just lazy and nothing more. You should start thinking differently if it comes to react-native, through away the opinions of unexperienced and lazy people and make your own experiences.
#### Fun
The reason why I'm doing this in general is fun. I enjoy coding in javascript (especially in es6/7) and like the react component pattern. Another benefit is that I can support both, Android and iOS. I could also only support one of them, it's up to me. As it comes to network request or basic object/array modifications, javascript (/ node) gives you tons of frameworks and toolkits. Network requests actually make fun! Can you imagine that? Great, I know :D. Even if I think from time to time "man, it would be great to do this in a storyboard", but the nice thing is, I could. To sum it up, it's fun to code in the react pattern with javascript.
### Drawbacks
As you can see in the `packages.json` I used a UI Framework/Collection to improve my development speed. For the MovieBrowser I chose `Shoutem`. `Shoutem` promotes that they can help with almost everywhere concering mobile app development. I was only interested in the UI part which let you build react-native app "in not time", as they say on their website. If you ask me, do it by yourself. For prototyping it's fine, you get a nice looking app in short time. But then you need to customize. You need to go through the documentation and you recognize, the style is separated from the view. That remembers me of html and css separation. I'm not sure what I should think about it. For me at least, it's strange, I just don't like it. I'm sure a lot of you might like those frameworks (shoutem, native base ...), but in my opinion it's another way for lazy people build nice looking apps really fast. In the end you have no idea what's happening.
Another issue that hunts me since my first moment with react-native is the framework itself. It's still not `1.0`, so breaking changes are possible with each minor version. You often run into problems which require an update of the react-native version. Sometimes it is working, but more often the projects are broken. I hate it, spend time to fix something that was already working and now broken because I wanted to fix something else. It's a bit exhausting. And the fact that it's never gonna stop because Android and iOS is constantly improving and updating, makes me feel a bit irated. Enough rant for now :D
### Conclusion
I implemented a movie browser which gets the information from TMDB with a cross-platform framework called react-native. I enjoy coding in javascript to get native apps and the massive amount of node packages which can be used. Cross-platform has its benefits and drawbacks, but it highly depends on the usecase. My giveaways are the following: Read the react-native docs precisely, write your own code, use less than more modules/frameworks and go through the whole project in mind beforehand to decide if native or cross-platform is the one to go for.
### Screenshots
To get a overview of the app and how it works I did some fancy store-like screenshots:
#### iOS
<table>
<tr>
<td><a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/ios/0.jpg" align="center" height="760" width="448" ></a></td>
<td>
<a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/ios/1.jpg" align="center" height="760" width="448" ></a>
</td>
</tr>
<tr>
<td><a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/ios/2.jpg" align="center" height="760" width="448" ></a></td>
<td>
<a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/ios/3.jpg" align="center" height="760" width="448" ></a>
</td>
</tr>
</table>
#### Android
<table>
<tr>
<td><a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/android/0.jpg" align="center" height="760" width="448" ></a></td>
<td>
<a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/android/1.jpg" align="center" height="760" width="448" ></a>
</td>
</tr>
<tr>
<td><a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/android/2.jpg" align="center" height="760" width="448" ></a></td>
<td>
<a href="url"><img src="https://github.com/papsti7/MovieBrowserApp/blob/bb1428ee3189b79284b6b6043fe44919e2cd3cbf/Screenshots/android/3.jpg" align="center" height="760" width="448" ></a>
</td>
</tr>
</table>
<file_sep>import axios from "axios";
import _ from "lodash";
import { AsyncStorage } from "react-native";
import * as Constants from "./Constants";
import ApiKey from "./ApiKey";
export const GetMovieById = async id => {
const movieResponse = await axios.get(
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.MOVIE +
"/" +
id +
"?" +
ApiKey
);
return movieResponse;
};
export const GetTVShowById = async id => {
const showResponse = await axios.get(
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.TVSHOW +
"/" +
id +
"?" +
ApiKey
);
return showResponse;
};
export const DiscoverMoviesByPopularity = async (page = 1, genre) => {
let url =
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.DISCOVER +
Constants.API_ENDPOINT.MOVIE +
"?" +
ApiKey +
"&" +
"page=" +
page;
if (genre) {
url += "&" + "with_genres=" + genre;
}
const movieResponse = await axios.get(url);
return movieResponse;
};
export const DiscoverShowsByPopularity = async (page = 1, genre) => {
let url =
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.DISCOVER +
Constants.API_ENDPOINT.TVSHOW +
"?" +
ApiKey +
"&" +
"page=" +
page;
if (genre) {
url += "&" + "with_genres=" + genre;
}
const showResponse = await axios.get(url);
return showResponse;
};
export const GetImageByPath = async path => {
return await axios.get(Constants.ROOT_URL.IMAGE + path);
};
export const GetGenreList = async isMovie => {
let genreResponse;
if (isMovie) {
genreResponse = await axios.get(
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.GENRE_MOVIE_LIST +
"?" +
ApiKey
);
} else {
genreResponse = await axios.get(
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.GENRE_TVSHOW_LIST +
"?" +
ApiKey
);
}
return genreResponse;
};
export const GetGenreNameById = async (id, isMovie = true) => {
try {
let genres;
if (isMovie) {
genres = JSON.parse(
await AsyncStorage.getItem(Constants.ASYNCSTORAGE_KEYS.GENRE_MOVIE_LIST)
);
} else {
genres = JSON.parse(
await AsyncStorage.getItem(
Constants.ASYNCSTORAGE_KEYS.GENRE_TVSHOW_LIST
)
);
}
if (genres) {
const result = _.find(genres, genre => genre.id === id);
if (result) {
return result.name;
} else {
throw new Error("id not found in records");
}
} else {
throw new Error("no records saved yet");
}
} catch (err) {
try {
const {
status,
data: { genres }
} = await GetGenreList(isMovie);
if (status === 200) {
if (isMovie) {
await AsyncStorage.setItem(
Constants.ASYNCSTORAGE_KEYS.GENRE_MOVIE_LIST,
JSON.stringify(genres)
);
} else {
await AsyncStorage.setItem(
Constants.ASYNCSTORAGE_KEYS.GENRE_TVSHOW_LIST,
JSON.stringify(genres)
);
}
const result = _.find(genres, genre => genre.id === id);
if (result) {
return result.name;
} else {
throw new Error("id not found in newly fetched records");
}
}
} catch (err) {
return "unknown genre";
}
}
};
export const SearchForMovieByName = async (query = "Flash") => {
let url =
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.SEARCH +
Constants.API_ENDPOINT.MOVIE +
"?" +
ApiKey;
url += "&" + "query=" + query;
const searchResponse = await axios.get(url);
return searchResponse;
};
export const SearchForShowByName = async (query = "Flash") => {
let url =
Constants.ROOT_URL.API +
Constants.API_ENDPOINT.SEARCH +
Constants.API_ENDPOINT.TVSHOW +
"?" +
ApiKey;
url += "&" + "query=" + query;
const searchResponse = await axios.get(url);
return searchResponse;
};
<file_sep>import { createStackNavigator } from "react-navigation";
import React, { Component } from "react";
import MainScreen from "./screens/MainScreen";
import DetailScreen from "./screens/DetailScreen";
import SearchScreen from "./screens/SearchScreen";
class Router extends Component {
render() {
const StackNavigator = createStackNavigator(
{
main: {
screen: MainScreen
},
detail: {
screen: DetailScreen
},
search: {
screen: SearchScreen
}
},
{}
);
return <StackNavigator />;
}
}
export default Router;
<file_sep>import React, { Component } from "react";
import { ScrollView } from "react-native";
import { ImageBackground, Tile, Title, Text } from "@shoutem/ui";
import { ROOT_URL, TYPE_MOVIE_DISCOVER } from "../Constants";
import { GetGenreNameById } from "../ApiUtil";
class DetailScreen extends Component {
static navigationOptions = ({ navigation }) => {
const { state } = navigation;
const { item, type } = state.params;
return {
title:
type === TYPE_MOVIE_DISCOVER ? item.original_title : item.original_name
};
};
state = {
genres: [],
item: this.props.navigation.getParam("item", {}),
type: this.props.navigation.getParam("type", TYPE_MOVIE_DISCOVER)
};
async componentDidMount() {
const {
item: { genre_ids },
type
} = this.state;
const isMovie = type === TYPE_MOVIE_DISCOVER;
try {
let genres = await Promise.all(
genre_ids.map(id => GetGenreNameById(id, isMovie))
);
genres = genres.map(genre => <Text key={genre}>{genre}, </Text>);
this.setState({ genres });
} catch (err) {
console.log(err);
}
}
render() {
const { item, type, genres } = this.state;
return (
<ScrollView style={{ flex: 1 }}>
<ImageBackground
styleName="large-portrait"
source={{
uri: ROOT_URL.IMAGE + item.poster_path
}}
>
<Tile>
<Title styleName="md-gutter-top">
{type === TYPE_MOVIE_DISCOVER ? item.title : item.name}
</Title>
</Tile>
</ImageBackground>
<Text>
<Text styleName="bold">Release Date: </Text>
{type === TYPE_MOVIE_DISCOVER
? item.release_date
: item.first_air_date}
</Text>
<Text>
<Text styleName="bold">Genres: </Text>
{genres}
</Text>
<Title>
<Title styleName="bold">Overview: </Title>
{item.overview}
</Title>
</ScrollView>
);
}
}
export default DetailScreen;
<file_sep>import React, { PureComponent } from "react";
import _ from "lodash";
import { View, TouchableOpacity, FlatList, Image } from "react-native";
import { Title, Spinner } from "@shoutem/ui";
import { KEY_EXTRACTOR } from "../Constants";
import PlusSign from "../../assets/plus.png";
import CoverItem from "../components/CoverItem";
class HorizontalList extends PureComponent {
constructor(props) {
super(props);
this.state = {
...props,
renderItem: ({ item }) => this.renderRowItem(item, props.type),
actualApiCallPage: 1,
isFetchingData: false
};
}
componentDidMount() {
this.onListRefresh();
}
onListRefresh = () => {
new Promise(async (resolve, reject) => {
const { apiCall, args } = this.state;
try {
const { status, data } = await apiCall(1, args);
if (status === 200) {
const { results } = data;
this.listRef.scrollToOffset({ animated: true, offset: 0 });
this.setState({ data: results, actualApiCallPage: 1 });
resolve();
} else {
reject(status);
}
} catch (err) {
reject(err);
}
});
};
fetchNewData = async () => {
this.setState({ isFetchingData: true });
const { apiCall, args, actualApiCallPage } = this.state;
try {
const newActualApiCallPage = actualApiCallPage + 1;
const { status, data } = await apiCall(newActualApiCallPage, args);
if (status === 200) {
const { results } = data;
this.setState({
data: _.concat(this.state.data, results),
actualApiCallPage: newActualApiCallPage
});
}
} catch (err) {
console.log(err);
} finally {
this.setState({ isFetchingData: false });
}
};
onEndReached = async () => {
await this.fetchNewData();
};
renderRowItem = (item, type) => {
return (
<CoverItem item={item} type={type} navigation={this.props.navigation} />
);
};
renderFooterItem = () => {
const { isFetchingData } = this.state;
return (
<View style={styles.footerItemViewStyle}>
{isFetchingData ? (
<Spinner style={styles.footerItemSpinnerStyle} />
) : (
<TouchableOpacity onPress={this.fetchNewData}>
<Image style={styles.footerItemImageStyle} source={PlusSign} />
</TouchableOpacity>
)}
</View>
);
};
getItemLayout = (data, index) => {
return { length: 180, offset: (180 + 10) * index, index: index };
};
renderItemSeparator = () => <View style={{ width: 10, height: 250 }} />;
getRef = ref => (this.listRef = ref);
render() {
const { title, data, renderItem } = this.state;
return (
<View style={styles.viewStyle}>
<Title style={styles.titleStyle}>{title}</Title>
<FlatList
style={styles.listStyle}
contentContainerStyle={styles.listContainerStyle}
ItemSeparatorComponent={this.renderItemSeparator}
ListFooterComponent={this.renderFooterItem}
data={data}
renderItem={renderItem}
horizontal
ref={this.getRef}
showsHorizontalScrollIndicator={false}
keyExtractor={KEY_EXTRACTOR}
onEndReached={this.onEndReached}
getItemLayout={this.getItemLayout}
/>
</View>
);
}
}
const styles = {
listStyle: { height: 250 },
listContainerStyle: { paddingHorizontal: 20 },
viewStyle: { height: 300 },
titleStyle: {
color: "white",
paddingLeft: 20,
paddingVertical: 10
},
footerItemViewStyle: {
width: 180,
height: 250,
alignItems: "center",
justifyContent: "center"
},
footerItemSpinnerStyle: {
size: "large"
},
footerItemImageStyle: { width: 180, height: 250, resizeMode: "center" }
};
export default HorizontalList;
<file_sep>import React, { Component } from "react";
import _ from "lodash";
import {
View,
TouchableOpacity,
FlatList,
StatusBar,
Platform
} from "react-native";
import { Heading, Icon } from "@shoutem/ui";
import DiscoverMovies from "../DiscoverMovies.json";
import DiscoverTVShows from "../DiscoverTV.json";
import {
TYPE_MOVIE_DISCOVER,
TYPE_SHOW_DISCOVER,
TYPE_GENRE_MOVIE,
COLOR,
KEY_EXTRACTOR,
CAPITALIZE_FIRST_LETTER
} from "../Constants";
import * as API from "../ApiUtil";
import HorizontalList from "../components/HorizontalList";
class MainScreen extends Component {
static navigationOptions = ({ navigation }) => {
return {
headerTitle:
Platform.OS === "android" ? (
<Heading
style={{ color: "white", paddingLeft: 20, paddingVertical: 10 }}
>
MovieBrowser
</Heading>
) : (
<Heading style={{ color: "white" }}>MovieBrowser</Heading>
),
headerTintColor: "white",
headerStyle: {
backgroundColor: COLOR.NAVBAR
},
headerRight: (
<TouchableOpacity
style={{
paddingVertical: Platform.OS === "android" ? 20 : 0,
paddingHorizontal: 20
}}
onPress={() => navigation.navigate("search")}
>
<Icon name="search" style={{ color: "white" }} />
</TouchableOpacity>
)
};
};
state = {
isRefreshing: false,
listData: []
};
horizontalListRefs = {};
componentDidMount = async () => {
const listData = [
{
type: TYPE_MOVIE_DISCOVER,
title: "Discover Popular Movies",
getRef: ref => {
if (!this.horizontalListRefs[TYPE_MOVIE_DISCOVER] && ref) {
this.horizontalListRefs[TYPE_MOVIE_DISCOVER] = ref;
}
},
apiCall: API.DiscoverMoviesByPopularity,
data: DiscoverMovies.results
},
{
type: TYPE_SHOW_DISCOVER,
title: "Discover Popular TVShows",
getRef: ref => {
if (!this.horizontalListRefs[TYPE_SHOW_DISCOVER] && ref) {
this.horizontalListRefs[TYPE_SHOW_DISCOVER] = ref;
}
},
apiCall: API.DiscoverShowsByPopularity,
data: DiscoverTVShows.results
}
];
try {
const {
status,
data: { genres }
} = await API.GetGenreList(true);
if (status === 200) {
_.forEach(genres, genre => {
const entry = {
type: TYPE_GENRE_MOVIE,
title: "Movie Genre " + CAPITALIZE_FIRST_LETTER(genre.name),
args: genre.id,
getRef: ref => {
if (
!this.horizontalListRefs[TYPE_GENRE_MOVIE + genre.id] &&
ref
) {
this.horizontalListRefs[TYPE_GENRE_MOVIE + genre.id] = ref;
}
},
apiCall: API.DiscoverMoviesByPopularity,
data: []
};
listData.push(entry);
});
}
} catch (err) {
console.log(err);
}
this.setState({ listData });
};
renderHorizontalList = item => {
return (
<HorizontalList
{...item}
ref={item.getRef}
navigation={this.props.navigation}
/>
);
};
renderListItem = ({ item }) => {
return this.renderHorizontalList(item);
};
onRefresh = async () => {
this.setState({ isRefreshing: true });
try {
const refreshListPromises = [];
_.forOwn(this.horizontalListRefs, function(value, key) {
refreshListPromises.push(value.onListRefresh());
});
await Promise.all(refreshListPromises);
} catch (err) {
console.log(err);
} finally {
this.setState({ isRefreshing: false });
}
};
getItemLayout = (data, index) => {
return { length: 300, offset: 300 * index, index: index };
};
getRef = ref => (this.overallListRef = ref);
render() {
const { listData } = this.state;
return (
<View style={{ flex: 1, backgroundColor: COLOR.BACKGROUND }}>
<StatusBar backgroundColor="#111" />
<FlatList
data={listData}
renderItem={this.renderListItem}
showsVerticalScrollIndicator={false}
keyExtractor={KEY_EXTRACTOR}
onRefresh={this.onRefresh}
ref={this.getRef}
refreshing={this.state.isRefreshing}
initialNumToRender={2}
getItemLayout={this.getItemLayout}
/>
</View>
);
}
}
export default MainScreen;
| 74e7bfbc228bc26e69c1e620f8100f9203cea89e | [
"Markdown",
"JavaScript"
] | 6 | Markdown | papsti7/MovieBrowserApp | 84447b5edab22a59b8157bf24811b2b49443f55a | 2dd12b86036f0be73f563f13f52648fff08291d8 | |
refs/heads/master | <repo_name>chaoKing/javaproject<file_sep>/src/Test.java
/**
* king
*/
/**
* @author king
*
*/
public class Test {
}
| b074dbfb0e7b8658cbf5f00f6ad5e122fd01457c | [
"Java"
] | 1 | Java | chaoKing/javaproject | 67725807ec8670a0594cab7bfa82380f140afd6e | 86d41686e0ac1f8b01f89f4dcaa210cd56620428 | |
refs/heads/master | <repo_name>dshartnett/gravity<file_sep>/server.js
(function(){
"use strict";
function Timer()
{
this.then = Date.now();
this.int_count = 0;
this.time_array = [];
this.time_array_index = 0;
this.frame_count = 0;
this.time_count = 0;
}
Timer.prototype = {
get interval(){
var i = Date.now() - this.then;
this.then = Date.now();
this.time_array_index++;
if (this.time_array_index >= CONST.FRAME_MAX) this.time_array_index = 0;
if (this.frame_count >= CONST.FRAME_MAX) this.time_count -= this.time_array[this.time_array_index];
else this.frame_count++;
this.time_array[this.time_array_index] = i;
this.time_count += i;
this.int_count++;
return i;
},
get i_count(){return this.int_count;},
get frame_rate(){return 1000*this.frame_count/this.time_count;}
};
var CONST = require('./site/constants.js').getConstants();
var app = require('http').createServer(handler);
var io = require('socket.io').listen(app);
var staticReq = require('node-static'); // for serving files
// This will make all the files in the current folder accessible
var fileServer = new staticReq.Server('./site/');
// http://localhost:8080
app.listen(8080);
// If the URL of the socket server is opened in a browser
function handler(request, response) {request.addListener('end', function () {fileServer.serve(request, response);}); }
//function handler(request, response) {response.writeHeader(200, {'Content-Type': 'text/plain'}); response.end('Hello World\n');}
// Delete this row if you want to see debug messages
io.set('log level', 1);
var PLAYER_ID = 0;
var player_list = {};
var PAR_ID = 0;
var par_col = {};
var par_ids_to_del = [];
var OBJ_ID = 0;
var obj_col = {};
var obj_ids_to_del = [];
var power_up_count = {};
power_up_count[CONST.POWER_UP_CLOAK] = power_up_count[CONST.POWER_UP_INVINCIBLE] = power_up_count[CONST.POWER_UP_G_OBJECT] = power_up_count[CONST.POWER_UP_BOMB] = 0;
var team_count = [];
team_count[CONST.TEAM1] = team_count[CONST.TEAM2] = 0;
var main_timer = new Timer();
setInterval(function () {
//console.log(Date.now() + " " + Math.random()*Math.pow(2,32));
var server_interval = main_timer.interval;
// if(100*Math.random() < 1) obj_col[++OBJ_ID] = new G_Object(Math.random()*CONST.MAP_WIDTH, Math.random()*CONST.MAP_HEIGHT, 0, 0, 0, OBJ_ID, 0);
for (var u in player_list) player_list[u].player.refresh(server_interval, par_col, obj_col, par_ids_to_del);
for (var u in par_col) par_col[u].refresh(server_interval);
for (var i = 0, len = par_ids_to_del.length; i < len; i++) {
console.log("deleting particle " + par_ids_to_del[0] + " and emitting delete");
io.sockets.emit("par_delete", par_ids_to_del[0]);
delete par_col[par_ids_to_del.shift()];
}
power_up_count[CONST.POWER_UP_CLOAK] = power_up_count[CONST.POWER_UP_INVINCIBLE] = power_up_count[CONST.POWER_UP_G_OBJECT] = power_up_count[CONST.POWER_UP_BOMB] = 0;
for (var u in obj_col){
obj_col[u].refresh(server_interval, par_col, obj_col, player_list, obj_ids_to_del);
if(obj_col[u].object_type == CONST.OBJ_POWER_UP) power_up_count[obj_col[u].power_up_type]++;
}
//console.log(power_up_count);
for (var u in power_up_count)
{
//console.log(u);
if (power_up_count[u] < 1)
obj_col[++OBJ_ID] = new Power_Up_Object(OBJ_ID, Math.random()*CONST.MAP_WIDTH, Math.random()*CONST.MAP_HEIGHT, (Math.random()-0.5)*0.1, (Math.random()-0.5)*0.1, Number(u));
}
for (var i = 0, len = obj_ids_to_del.length; i < len; i++) {
console.log("deleting object " + obj_ids_to_del[0] + " and emitting delete");
io.sockets.emit("obj_delete", obj_ids_to_del[0]);
delete obj_col[obj_ids_to_del.shift()];
}
// console.log(server_interval);
},1000/CONST.UPS);
// Listen for incoming connections from clients
io.sockets.on('connection', function (socket) {
++PLAYER_ID;
player_list[socket.id] = {
start_interval: Date.now(),
end_interval: null,
player:new Player(PLAYER_ID, team_count[CONST.TEAM1]>team_count[CONST.TEAM2]?CONST.TEAM2:CONST.TEAM1)
};
team_count[player_list[socket.id].player.team]++;
console.log("player " + player_list[socket.id].player.player_id + " connected on socket " + socket.id + ". ponging now...");
socket.emit("player_id",{p_id:player_list[socket.id].player.player_id, team:player_list[socket.id].player.team});
//socket.broadcast.emit('player_added', player_list[socket.id].player.player_id);
socket.emit("pong",player_list[socket.id].player.data());
socket.on("request_player_list", function(data) {
var p_list = {};
for (var u in player_list) p_list[player_list[u].player.player_id] = player_list[u].player.team;
socket.emit("player_list", p_list);
});
socket.on("ping", function(data) {
player_list[socket.id].end_interval = Date.now();
var interval = player_list[socket.id].end_interval - player_list[socket.id].start_interval;
//console.log("pinged with: " + data + " player id: " + player_list[socket.id].player.player_id + " socket id: " + socket.id + " interval: " + interval);
player_list[socket.id].player.move_command_state = data;
//player_list[socket.id].player.refresh(interval);
player_list[socket.id].start_interval = Date.now();
//socket.volatile.emit("pong", player_list[socket.id].player.data());
for (var u in player_list) socket.volatile.emit("pong", player_list[u].player.data(player_list[socket.id].player.player_id));
for (var u in par_col) socket.volatile.emit("par", par_col[u].data());
for (var u in obj_col) socket.volatile.emit("obj", obj_col[u].data());
//setTimeout(function(){socket.emit("pong", player_list[socket.id].player.data());}, 200);
});
socket.on('disconnect', function(){
console.log("player " + player_list[socket.id].player.player_id + " disconnected");
socket.broadcast.emit('player_removed', player_list[socket.id].player.player_id);
player_list[socket.id].player.disconnect(par_ids_to_del);
team_count[player_list[socket.id].player.team]--;
delete player_list[socket.id];
});
});
function Particle(x,y,v_x,v_y,team,particle_id,player_id){
this.pos_x = x;
this.pos_y = y;
this.last_pos_x = x;
this.last_pos_y = y;
this.v_x = v_x;
this.v_y = v_y;
this.mass = CONST.PARTICLE_MASS;
this.charge = CONST.PARTICLE_CHARGE;
this.size = CONST.PARTICLE_SIZE;
this.half_size = this.size/2;
this.team = team;
this.particle_id = particle_id;
this.player_id = player_id;
this.data = function() {return {id:this.particle_id, x:this.pos_x, y:this.pos_y, v_x:this.v_x, v_y:this.v_y};};
this.refresh = function(interval) {
this.last_pos_x = this.pos_x;
this.last_pos_y = this.pos_y;
this.pos_x += this.v_x*interval;
this.pos_y += this.v_y*interval;
if (this.pos_x >= CONST.MAP_WIDTH) {this.pos_x = CONST.MAP_WIDTH - 1; this.v_x = -this.v_x*CONST.PARTICLE_WALL_LOSS;}
else if (this.pos_x <= 0) {this.pos_x = 1; this.v_x = -this.v_x*CONST.PARTICLE_WALL_LOSS;}
if (this.pos_y >= CONST.MAP_HEIGHT) {this.pos_y = CONST.MAP_HEIGHT - 1; this.v_y = -this.v_y*CONST.PARTICLE_WALL_LOSS;}
else if (this.pos_y <= 0) {this.pos_y = 1; this.v_y = -this.v_y*CONST.PARTICLE_WALL_LOSS;}
}
return this;
}
function Player(player_id, team){
this.player_id = player_id;
this.team = team;
this.pos_x = (0.1 + Math.random()*0.8)*CONST.MAP_WIDTH;
this.pos_y = (0.1 + Math.random()*0.8)*CONST.MAP_HEIGHT;
this.angle = Math.random()*2*Math.PI;
this.v_x = 0;
this.v_y = 0;
this.radius = CONST.PLAYER_RADIUS;
this.wing_angle = CONST.PLAYER_WING_ANGLE;
this.health = CONST.PLAYER_MAX_HEALTH;
this.mass = CONST.PLAYER_MASS;
this.dying_timer = 0;
this.cloak_timer = 0;
this.invincible_timer = 0;
this.fire_battery = 0;
this.stat = 0;
this.move_command_state = 0;
this.server_set = false;
var particle_ids = [];
this.disconnect = function(par_ids_to_del)
{
for (var i in particle_ids) par_ids_to_del.push(particle_ids[i]);
};
this.spawn = function()
{
this.health = CONST.PLAYER_MAX_HEALTH;
this.v_x = 0;
this.v_y = 0;
this.angle = Math.random()*2*Math.PI;
this.pos_x = (0.1 + Math.random()*0.8)*CONST.MAP_WIDTH;
this.pos_y = (0.1 + Math.random()*0.8)*CONST.MAP_HEIGHT;
this.dying_timer = 0;
this.fire_battery = 0;
this.stat = 0;
};
this.data = function(other_id){
if (this.stat & CONST.PLAYER_STATUS_CLOAKED && this.player_id != other_id)
return {p_id:this.player_id, x:0, y:0, v_x:0, v_y:0, angle:0, health:this.health, stat:this.stat};
else
return {p_id:this.player_id, x:this.pos_x, y:this.pos_y, v_x:this.v_x, v_y:this.v_y, angle:this.angle, health:this.health, stat:this.stat};
};
this.refresh = function (interval, par_col, obj_col, par_ids_to_del) {
this.v_x -= CONST.PLAYER_FRICTION*this.v_x*interval;
this.v_y -= CONST.PLAYER_FRICTION*this.v_y*interval;
if (this.stat & CONST.PLAYER_STATUS_DEAD)
{
this.cloak_timer = 0;
this.stat &= ~CONST.PLAYER_STATUS_CLOAKED;
this.dying_timer -= interval;
this.move_command_state = 0;
this.angle -= CONST.PLAYER_ROTATE_SPEED*interval;
}
if (this.dying_timer < 0) this.spawn();
if (this.stat & CONST.PLAYER_STATUS_CLOAKED) this.cloak_timer -= interval;
if (this.cloak_timer < 0) this.stat &= ~CONST.PLAYER_STATUS_CLOAKED;
if (this.stat & CONST.PLAYER_STATUS_INVINCIBLE) this.invincible_timer -= interval;
if (this.invincible_timer < 0) this.stat &= ~CONST.PLAYER_STATUS_INVINCIBLE;
//if (this.shield_fade > 0) this.shield_fade -= interval;
if (this.fire_battery > 0) this.fire_battery -= interval;
if (this.move_command_state & CONST.COMMAND_ROTATE_CC) this.angle -= CONST.PLAYER_ROTATE_SPEED*interval;
if (this.move_command_state & CONST.COMMAND_MOVE_FORWARD)
{
this.v_x += CONST.PLAYER_ACCELERATION*interval*Math.cos(this.angle);
this.v_y += CONST.PLAYER_ACCELERATION*interval*Math.sin(this.angle);
}
if (this.move_command_state & CONST.COMMAND_ROTATE_CW) this.angle += CONST.PLAYER_ROTATE_SPEED*interval;
if (this.move_command_state & CONST.COMMAND_MOVE_BACKWARD)
{
this.v_x -= CONST.PLAYER_ACCELERATION*interval*Math.cos(this.angle);
this.v_y -= CONST.PLAYER_ACCELERATION*interval*Math.sin(this.angle);
}
if (this.move_command_state & CONST.COMMAND_STRAFE_LEFT)
{
this.v_x += CONST.PLAYER_ACCELERATION*interval*Math.sin(this.angle);
this.v_y -= CONST.PLAYER_ACCELERATION*interval*Math.cos(this.angle);
}
if (this.move_command_state & CONST.COMMAND_STRAFE_RIGHT)
{
this.v_x -= CONST.PLAYER_ACCELERATION*interval*Math.sin(this.angle);
this.v_y += CONST.PLAYER_ACCELERATION*interval*Math.cos(this.angle);
}
if (this.fire_battery <= 0 && this.move_command_state & CONST.COMMAND_FIRE)
{
//this.request_state += CONST.COMMAND_FIRE;
//this.fire_request = true;
var temp_v_x = this.v_x;
var temp_v_y = this.v_y;
this.fire_battery = CONST.PLAYER_FIRE_BATTERY;
this.v_x -= CONST.PARTICLE_MASS*CONST.PARTICLE_INITIAL_VELOCITY*Math.cos(this.angle)/this.mass;
this.v_y -= CONST.PARTICLE_MASS*CONST.PARTICLE_INITIAL_VELOCITY*Math.sin(this.angle)/this.mass;
par_col[++PAR_ID] = new Particle(
this.pos_x,// + CONST.PLAYER_RADIUS*Math.cos(this.angle),
this.pos_y,// + CONST.PLAYER_RADIUS*Math.sin(this.angle),
temp_v_x + CONST.PARTICLE_INITIAL_VELOCITY*Math.cos(this.angle),
temp_v_y + CONST.PARTICLE_INITIAL_VELOCITY*Math.sin(this.angle),
this.team, PAR_ID, this.player_id);
console.log("player " + this.player_id + " fired particle " + PAR_ID);
particle_ids.push(PAR_ID);
if (particle_ids.length > CONST.PLAYER_MAX_BULLETS){
var last_p = particle_ids.shift();
console.log("deleting particle " + last_p + " from player " + this.player_id);
par_ids_to_del.push(last_p);
//delete par_col[last_p];
}
}
//else this.fire_request = false;
if (this.stat & CONST.PLAYER_STATUS_HAS_G_OBJECT && this.move_command_state & CONST.COMMAND_G_OBJECT)
{
var temp_v_x = this.v_x;
var temp_v_y = this.v_y;
this.v_x -= CONST.G_OBJECT_LAUNCH_MASS*CONST.G_OBJECT_INITIAL_VELOCITY*Math.cos(this.angle)/this.mass;
this.v_y -= CONST.G_OBJECT_LAUNCH_MASS*CONST.G_OBJECT_INITIAL_VELOCITY*Math.sin(this.angle)/this.mass;
obj_col[++OBJ_ID] = new G_Object(
this.pos_x,// + CONST.PLAYER_RADIUS*Math.cos(this.angle),
this.pos_y,// + CONST.PLAYER_RADIUS*Math.sin(this.angle),
temp_v_x + CONST.G_OBJECT_INITIAL_VELOCITY*Math.cos(this.angle),
temp_v_y + CONST.G_OBJECT_INITIAL_VELOCITY*Math.sin(this.angle),
this.team, OBJ_ID, this.player_id);
console.log("player " + this.player_id + " launched G_Object " + OBJ_ID);
this.stat -= CONST.PLAYER_STATUS_HAS_G_OBJECT;
}
if (this.stat & CONST.PLAYER_STATUS_HAS_BOMB && this.move_command_state & CONST.COMMAND_BOMB)
{
var temp_v_x = this.v_x;
var temp_v_y = this.v_y;
this.v_x -= CONST.BOMB_LAUNCH_MASS*CONST.BOMB_INITIAL_VELOCITY*Math.cos(this.angle)/this.mass;
this.v_y -= CONST.BOMB_LAUNCH_MASS*CONST.BOMB_INITIAL_VELOCITY*Math.sin(this.angle)/this.mass;
obj_col[++OBJ_ID] = new Bomb(
this.pos_x,// + CONST.PLAYER_RADIUS*Math.cos(this.angle),
this.pos_y,// + CONST.PLAYER_RADIUS*Math.sin(this.angle),
temp_v_x + CONST.G_OBJECT_INITIAL_VELOCITY*Math.cos(this.angle),
temp_v_y + CONST.G_OBJECT_INITIAL_VELOCITY*Math.sin(this.angle),
this.team, OBJ_ID, this.player_id);
console.log("player " + this.player_id + " launched bomb " + OBJ_ID);
this.stat -= CONST.PLAYER_STATUS_HAS_BOMB;
}
this.pos_x += this.v_x*interval;
this.pos_y += this.v_y*interval;
this.stat &= ~CONST.PLAYER_STATUS_MOVING;
this.stat |= this.move_command_state & CONST.PLAYER_MOVING?CONST.PLAYER_STATUS_MOVING:0;
if (this.health < CONST.PLAYER_MAX_HEALTH && !(this.stat & CONST.PLAYER_STATUS_DEAD)) this.health += CONST.PLAYER_HEALTH_REGEN*interval;
if (this.health > CONST.PLAYER_MAX_HEALTH) this.health = CONST.PLAYER_MAX_HEALTH;
var invincible_health_save = this.health;
for (var i in par_col)
{
if (par_col[i].team != this.team)
{
var diff_x = par_col[i].pos_x - this.pos_x;
var diff_y = par_col[i].pos_y - this.pos_y;
if (diff_x*diff_x + diff_y*diff_y < this.radius*this.radius)
{
this.health -= CONST.PARTICLE_DAMAGE;
par_ids_to_del.push(i);
console.log("collision");
}
}
}
for (var u in obj_col)
{
if (obj_col[u].object_type == CONST.OBJ_POWER_UP)
{
var diff_x = obj_col[u].pos_x - this.pos_x;
var diff_y = obj_col[u].pos_y - this.pos_y;
if (diff_x*diff_x + diff_y*diff_y < this.radius*this.radius)
{
switch(obj_col[u].power_up_type)
{
case CONST.POWER_UP_CLOAK:
if (!(this.stat & CONST.PLAYER_STATUS_CLOAKED))
{
this.stat += CONST.PLAYER_STATUS_CLOAKED*obj_col[u].power_up();
this.cloak_timer = CONST.PLAYER_CLOAK_TIMER_MAX;
}
break;
case CONST.POWER_UP_INVINCIBLE:
if (!(this.stat & CONST.PLAYER_STATUS_INVINCIBLE))
{
this.stat += CONST.PLAYER_STATUS_INVINCIBLE*obj_col[u].power_up();
this.invincible_timer = CONST.PLAYER_INVINCIBLE_TIMER_MAX;
}
break;
case CONST.POWER_UP_G_OBJECT:
if (!(this.stat & CONST.PLAYER_STATUS_HAS_G_OBJECT))
{
this.stat += CONST.PLAYER_STATUS_HAS_G_OBJECT*obj_col[u].power_up();
}
break;
case CONST.POWER_UP_BOMB:
if (!(this.stat & CONST.PLAYER_STATUS_HAS_BOMB))
{
this.stat += CONST.PLAYER_STATUS_HAS_BOMB*obj_col[u].power_up();
}
break;
}
}
}
}
if (this.pos_x - this.radius <= 0)
{this.v_x = -CONST.PLAYER_WALL_LOSS*this.v_x; this.pos_x = this.radius; this.health -= CONST.WALL_DAMAGE_MULTIPLIER*this.v_x + CONST.WALL_DAMAGE_MINIMUM;}
else if (this.pos_x + this.radius >= CONST.MAP_WIDTH)
{this.v_x = -CONST.PLAYER_WALL_LOSS*this.v_x; this.pos_x = CONST.MAP_WIDTH-this.radius; this.health -= -CONST.WALL_DAMAGE_MULTIPLIER*this.v_x + CONST.WALL_DAMAGE_MINIMUM;}
if (this.pos_y - this.radius <= 0)
{this.v_y = -CONST.PLAYER_WALL_LOSS*this.v_y; this.pos_y = this.radius; this.health -= CONST.WALL_DAMAGE_MULTIPLIER*this.v_y + CONST.WALL_DAMAGE_MINIMUM;}
else if (this.pos_y + this.radius >= CONST.MAP_HEIGHT)
{this.v_y = -CONST.PLAYER_WALL_LOSS*this.v_y; this.pos_y = CONST.MAP_HEIGHT-this.radius; this.health -= -CONST.WALL_DAMAGE_MULTIPLIER*this.v_y + CONST.WALL_DAMAGE_MINIMUM;}
if (this.stat & CONST.PLAYER_STATUS_INVINCIBLE) this.health = invincible_health_save;
if (this.health < 0 && !(this.stat & CONST.PLAYER_STATUS_DEAD)) {this.stat |= CONST.PLAYER_STATUS_DEAD; this.dying_timer = CONST.PLAYER_DEAD_COUNTER_MAX;}
};
return this;
}
function Power_Up_Object(obj_id, x, y, v_x, v_y, power_up_type)
{
this.obj_id = obj_id;
this.pos_x = x;
this.pos_y = y;
this.v_x = v_x;
this.v_y = v_y;
this.radius = CONST.POWER_UP_RADIUS;
this.object_type = CONST.OBJ_POWER_UP;
this.power_up_type = power_up_type;
this.item = 1;
this.power_up = function()
{
var to_ret = this.item;
this.item = 0;
return to_ret;
}
this.data = function(){
return {id:this.obj_id,
type:this.object_type,
p_t: this.power_up_type,
x:this.pos_x,
y:this.pos_y,
v_x:this.v_x,
v_y:this.v_y};
};
this.refresh = function(interval, par_col, obj_col, player_list, obj_ids_to_del)
{
if (this.pos_x - this.radius <= 0)
{this.v_x = -CONST.G_OBJECT_WALL_LOSS*this.v_x; this.pos_x = this.radius;}
else if (this.pos_x + this.radius >= CONST.MAP_WIDTH)
{this.v_x = -CONST.G_OBJECT_WALL_LOSS*this.v_x; this.pos_x = CONST.MAP_WIDTH-this.radius;}
if (this.pos_y - this.radius <= 0)
{this.v_y = -CONST.G_OBJECT_WALL_LOSS*this.v_y; this.pos_y = this.radius;}
else if (this.pos_y + this.radius >= CONST.MAP_HEIGHT)
{this.v_y = -CONST.G_OBJECT_WALL_LOSS*this.v_y; this.pos_y = CONST.MAP_HEIGHT-this.radius;}
this.pos_x += this.v_x*interval;
this.pos_y += this.v_y*interval;
if (this.item == 0) obj_ids_to_del.push(this.obj_id);
};
};
// Gravity object class
function G_Object(x, y, v_x, v_y, team, obj_id, player_id)
{
this.pos_x = x;
this.pos_y = y;
this.v_x = v_x;
this.v_y = v_y;
this.radius = CONST.G_OBJECT_MIN_RADIUS;
this.mass = CONST.G_OBJECT_MASS;
this.object_type = CONST.OBJ_G_OBJECT;
this.team = team;
this.obj_id = obj_id;
this.player_id = player_id;
this.timer = CONST.G_OBJECT_TIME_TO_DET;
this.stat = 0;
this.data = function(){
return {id:this.obj_id,
type:this.object_type,
x:this.pos_x,
y:this.pos_y,
v_x:this.v_x,
v_y:this.v_y,
team:this.team,
stat:this.stat,
timer:this.timer};
};
this.refresh = function(interval, par_col, obj_col, player_list, obj_ids_to_del)
{
if (this.pos_x - this.radius <= 0)
{this.v_x = -CONST.G_OBJECT_WALL_LOSS*this.v_x; this.pos_x = this.radius;}
else if (this.pos_x + this.radius >= CONST.MAP_WIDTH)
{this.v_x = -CONST.G_OBJECT_WALL_LOSS*this.v_x; this.pos_x = CONST.MAP_WIDTH-this.radius;}
if (this.pos_y - this.radius <= 0)
{this.v_y = -CONST.G_OBJECT_WALL_LOSS*this.v_y; this.pos_y = this.radius;}
else if (this.pos_y + this.radius >= CONST.MAP_HEIGHT)
{this.v_y = -CONST.G_OBJECT_WALL_LOSS*this.v_y; this.pos_y = CONST.MAP_HEIGHT-this.radius;}
this.pos_x += this.v_x*interval;
this.pos_y += this.v_y*interval;
this.timer -= interval;
if (this.timer < 0){
if (this.stat == 0){
this.stat |= CONST.G_OBJECT_STATUS_DETONATED;
this.timer = CONST.G_OBJECT_TIME_TO_LAST;
this.radius = CONST.G_OBJECT_MAX_RADIUS;
console.log("boom!");
}
else if (this.stat & CONST.G_OBJECT_STATUS_DETONATED)//add to objects to delete
{
// this.pos_x = this.pos_y = 100;
// this.v_x = this.v_y = 0.01;
// this.timer = CONST.G_OBJECT_TIME_TO_DET;
// this.stat = 0;
obj_ids_to_del.push(this.obj_id);
console.log("object added to delete array");
}
}
if (this.stat & CONST.G_OBJECT_STATUS_DETONATED)
{
var disX, disY, distance2, distance, force;
for (var i in par_col)
{
disX = this.pos_x - par_col[i].pos_x;
disY = this.pos_y - par_col[i].pos_y;
distance2 = disX*disX + disY*disY;
if (distance2 > this.radius*this.radius)
{
distance = Math.sqrt(distance2);
force = this.mass/distance2;
par_col[i].v_x += interval*disX*force/distance;
par_col[i].v_y += interval*disY*force/distance;
}
else
{
par_col[i].v_x -= CONST.G_OBJECT_FRICTION*par_col[i].v_x*interval;
par_col[i].v_y -= CONST.G_OBJECT_FRICTION*par_col[i].v_y*interval;
}
}
for (var i in obj_col)
{
if (obj_col[i].object_type == CONST.OBJ_BOMB)
{
disX = this.pos_x - obj_col[i].pos_x;
disY = this.pos_y - obj_col[i].pos_y;
distance2 = disX*disX + disY*disY;
if (distance2 > this.radius*this.radius){
distance = Math.sqrt(distance2);
force = this.mass/distance2;
obj_col[i].v_x += interval*disX*force/distance;
obj_col[i].v_y += interval*disY*force/distance;
}
else
{
obj_col[i].v_x -= CONST.G_OBJECT_FRICTION*obj_col[i].v_x*interval;
obj_col[i].v_y -= CONST.G_OBJECT_FRICTION*obj_col[i].v_y*interval;
}
}
}
for (var i in player_list){
if (this.team != player_list[i].player.team){
disX = this.pos_x - player_list[i].player.pos_x;
disY = this.pos_y - player_list[i].player.pos_y;
distance2 = disX*disX + disY*disY;
if (distance2 > this.radius*this.radius){
distance = Math.sqrt(distance2);
force = this.mass/distance2;
player_list[i].player.v_x += interval*disX*force/distance;
player_list[i].player.v_y += interval*disY*force/distance;
}
}
}
}
};
return this;
}
function Bomb(x, y, v_x, v_y, team, obj_id, player_id)
{
this.pos_x = x;
this.pos_y = y;
this.v_x = v_x;
this.v_y = v_y;
this.radius = CONST.BOMB_MIN_RADIUS;
this.mass = CONST.BOMB_MASS;
this.object_type = CONST.OBJ_BOMB;
this.team = team;
this.obj_id = obj_id;
this.player_id = player_id;
this.timer = CONST.BOMB_TIME_TO_DET;
this.stat = 0;
this.data = function(){
return {id:this.obj_id,
type:this.object_type,
x:this.pos_x,
y:this.pos_y,
v_x:this.v_x,
v_y:this.v_y,
team:this.team,
stat:this.stat,
timer:this.timer};
};
this.refresh = function(interval, par_col, obj_col, player_list, obj_ids_to_del)
{
if (this.pos_x - this.radius <= 0)
{this.v_x = -CONST.BOMB_WALL_LOSS*this.v_x; this.pos_x = this.radius;}
else if (this.pos_x + this.radius >= CONST.MAP_WIDTH)
{this.v_x = -CONST.BOMB_WALL_LOSS*this.v_x; this.pos_x = CONST.MAP_WIDTH-this.radius;}
if (this.pos_y - this.radius <= 0)
{this.v_y = -CONST.BOMB_WALL_LOSS*this.v_y; this.pos_y = this.radius;}
else if (this.pos_y + this.radius >= CONST.MAP_HEIGHT)
{this.v_y = -CONST.BOMB_WALL_LOSS*this.v_y; this.pos_y = CONST.MAP_HEIGHT-this.radius;}
if (this.stat & CONST.BOMB_STATUS_DETONATED) this.v_x = this.v_y = 0;
this.pos_x += this.v_x*interval;
this.pos_y += this.v_y*interval;
this.timer -= interval;
if (this.timer < 0){
if (this.stat == 0){
this.stat |= CONST.BOMB_STATUS_DETONATED;
this.timer = CONST.BOMB_TIME_TO_LAST;
//this.radius = CONST.BOMB_BLAST_RADIUS;
console.log("boom!");
}
else if (this.stat & CONST.BOMB_STATUS_DETONATED)//add to objects to delete
{
obj_ids_to_del.push(this.obj_id);
console.log("object added to delete array");
}
}
if (this.stat & CONST.BOMB_STATUS_DETONATED)
{
var disX, disY, distance2, distance, force;
/*for (var i in par_col)
{
disX = this.pos_x - par_col[i].pos_x;
disY = this.pos_y - par_col[i].pos_y;
distance2 = disX*disX + disY*disY;
if (distance2 > this.radius*this.radius)
{
distance = Math.sqrt(distance2);
force = this.mass/distance2;
par_col[i].v_x += interval*disX*force/distance;
par_col[i].v_y += interval*disY*force/distance;
}
else
{
par_col[i].v_x -= CONST.G_OBJECT_FRICTION*par_col[i].v_x*interval;
par_col[i].v_y -= CONST.G_OBJECT_FRICTION*par_col[i].v_y*interval;
}
}*/
for (var i in player_list){
disX = this.pos_x - player_list[i].player.pos_x;
disY = this.pos_y - player_list[i].player.pos_y;
distance2 = disX*disX + disY*disY;
if (distance2 < CONST.BOMB_MIN_RADIUS) distance2 = CONST.BOMB_MIN_RADIUS; // distance will be sqrt(CONST.BOMB_MIN_RADIUS) - lazy
if (distance2 < CONST.BOMB_BLAST_RADIUS*CONST.BOMB_BLAST_RADIUS){
distance = Math.sqrt(distance2);
force = this.mass/distance2;
player_list[i].player.v_x -= interval*disX*force/distance;
player_list[i].player.v_y -= interval*disY*force/distance;
if (!(player_list[i].player.stat & CONST.PLAYER_STATUS_INVINCIBLE) && this.team != player_list[i].player.team) player_list[i].player.health -= CONST.BOMB_DAMAGE_FACTOR*interval/distance;
}
}
}
};
return this;
}
})();
<file_sep>/site/main.js
window['Gravity']={};
(function(){
"use strict";
var CONST = CONSTANTS['getConstants']();
var tick = new Howl({'urls': ['./files/tick1.mp3', './files/tick1.ogg']});
var blast = new Howl({'urls': ['./files/bomb_blast1.mp3', './files/bomb_blast1.ogg']});
var g_obj = new Howl({'urls': ['./files/g_obj1.mp3', './files/g_obj1.ogg']});
var key_arr = {
r_cc:CONST.KEY_CODE_ROTATE_CC,
f:CONST.KEY_CODE_MOVE_FORWARD,
r_cw:CONST.KEY_CODE_ROTATE_CW,
bk:CONST.KEY_CODE_MOVE_BACKWARD,
s_l:CONST.KEY_CODE_STRAFE_LEFT,
s_r:CONST.KEY_CODE_STRAFE_RIGHT,
fr:CONST.KEY_CODE_FIRE,
g:CONST.KEY_CODE_G_OBJECT,
b:CONST.KEY_CODE_BOMB};
Gravity['options'] = function()
{
var temp = key_arr.r_cc;
key_arr.r_cc = key_arr.r_cw;
key_arr.r_cw = temp;
}
Gravity['about'] = function()
{
alert(CONST.ABOUT);
}
window.requestAnimFrame = (function () {
return window.requestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.oRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback){window.setTimeout(callback, 1000 / CONST.FPS);};
}
)();
function Timer()
{
this.then = Date.now();
this.int_count = 0;
this.time_array = [];
this.time_array_index = 0;
this.frame_count = 0;
this.time_count = 0;
}
Timer.prototype = {
get interval(){
var i = Date.now() - this.then;
this.then = Date.now();
this.time_array_index++;
if (this.time_array_index >= CONST.FRAME_MAX) this.time_array_index = 0;
if (this.frame_count >= CONST.FRAME_MAX) this.time_count -= this.time_array[this.time_array_index];
else this.frame_count++;
this.time_array[this.time_array_index] = i;
this.time_count += i;
this.int_count++;
return i;
},
get i_count(){return this.int_count;},
get frame_rate(){return 1000*this.frame_count/this.time_count;}
};//*/
function Background ()
{
//var background_canvas = $("<canvas id='background_canvas' width='" + CONST.MAP_WIDTH + "' height='" + CONST.MAP_HEIGHT + "'></canvas>");
//var background_context = background_canvas.get(0).getContext('2d');
var sf_0 = [];
var pf_0 = [];
this.initialize = function () {
//console.log("Generating background...");
/*var gradient = background_context.createLinearGradient(0,0,CONST.MAP_WIDTH,CONST.MAP_HEIGHT);
gradient.addColorStop(0.0,"black");
gradient.addColorStop(0.3,"black");
gradient.addColorStop(0.5,"purple");
gradient.addColorStop(0.7,"black");
gradient.addColorStop(1.0,"black");
background_context.fillStyle = gradient;
background_context.fillRect(0,0,CONST.MAP_WIDTH,CONST.MAP_HEIGHT);//*/
//console.log("Generating star field...");
//background_context.fillStyle = 'white';
for (var i = 0; i < CONST.BACKGROUND_STARS0; i++){
var star = {x:Math.random()*CONST.MAP_WIDTH, y: Math.random()*CONST.MAP_HEIGHT, star_size:Math.floor(1 + 2*Math.random())};
sf_0.push(star);
//background_context.fillRect(sf_0[i].x, sf_0[i].y, sf_0[i].star_size, sf_0[i].star_size);
}
/*
for (var i = 0; i < CONST.BACKGROUND_PLANETS0; i++){
var planet = {x:Math.random()*CONST.MAP_WIDTH, y: Math.random()*CONST.MAP_HEIGHT, planet_radius:CONST.BACKGROUND_PLANET_SIZE_MIN + CONST.BACKGROUND_PLANET_SIZE_RANGE*Math.random()};
pf_0.push(planet);
}
*/
}
this.draw = function (context, map_pos_x, map_pos_y) {
var gradient = context.createLinearGradient(-map_pos_x,-map_pos_y,CONST.MAP_WIDTH-map_pos_x,CONST.MAP_HEIGHT-map_pos_y);
gradient.addColorStop(0.0,"black");
gradient.addColorStop(0.3,"black");
gradient.addColorStop(0.5,"purple");
gradient.addColorStop(0.7,"black");
gradient.addColorStop(1.0,"black");
context.fillStyle = gradient;//'black';
context.fillRect(0,0,CONST.CANVAS_WIDTH,CONST.CANVAS_HEIGHT);
context.fillStyle = 'white';
for (var i = 0; i < CONST.BACKGROUND_STARS0; i++)
if (sf_0[i].x >= map_pos_x && sf_0[i].x <= map_pos_x + CONST.CANVAS_WIDTH && sf_0[i].y >= map_pos_y && sf_0[i].y <= map_pos_y + CONST.CANVAS_HEIGHT)
context.fillRect(sf_0[i].x - map_pos_x, sf_0[i].y - map_pos_y, sf_0[i].star_size, sf_0[i].star_size);
//*/
}
return this;
}
function Player(team){
var pos_x = 0,
pos_y = 0,
angle = 0,
v_x = 0,
v_y = 0,
radius = CONST.PLAYER_RADIUS,
team = team,
canvas_pos_x = CONST.CANVAS_WIDTH/2,
canvas_pos_y = CONST.CANVAS_HEIGHT/2,
mass = CONST.PLAYER_MASS,
health = CONST.PLAYER_MAX_HEALTH,
health_then = CONST.PLAYER_MAX_HEALTH,
shield_fade = 0,
fire_battery = 0,
stat = 0,
has_power_up_array = [0,0,0,0];
this.map_pos_x = pos_x - CONST.CANVAS_WIDTH/2;
this.map_pos_y = pos_y - CONST.CANVAS_HEIGHT/2;
var move_command_state = 0;
this.server_set = true;
this.set_command_state = function(key_down)
{
if (key_down[key_arr.r_cc]) move_command_state |= CONST.COMMAND_ROTATE_CC;
if (key_down[key_arr.f]) move_command_state |= CONST.COMMAND_MOVE_FORWARD;
if (key_down[key_arr.r_cw]) move_command_state |= CONST.COMMAND_ROTATE_CW;
if (key_down[key_arr.bk]) move_command_state |= CONST.COMMAND_MOVE_BACKWARD;
if (key_down[key_arr.s_l]) move_command_state |= CONST.COMMAND_STRAFE_LEFT;
if (key_down[key_arr.s_r]) move_command_state |= CONST.COMMAND_STRAFE_RIGHT;
if (key_down[key_arr.fr]) move_command_state |= CONST.COMMAND_FIRE;
if (key_down[key_arr.g]) move_command_state |= CONST.COMMAND_G_OBJECT;
if (key_down[key_arr.b]) move_command_state |= CONST.COMMAND_BOMB;
};
this.move_command_state = function(){return move_command_state;};
this.server_update = function(data)
{
var diff_x = data['x'] - pos_x;
var diff_y = data['y'] - pos_y;
var diff_a = data['angle'] - angle;
if (Math.abs(diff_x) > CONST.POSITION_CORRECT_X)
pos_x = data['x'];
else pos_x += diff_x*CONST.POSITION_CORRECTION_PERCENT;
if (Math.abs(diff_y) > CONST.POSITION_CORRECT_Y)
pos_y = data['y'];
else pos_y += diff_y*CONST.POSITION_CORRECTION_PERCENT;
angle = data['angle'];
v_x = data['v_x'];
v_y = data['v_y'];
health = data['health'];
stat = data['stat'];
this.server_set = true;
};
this.refresh = function (interval) {
has_power_up_array[CONST.POWER_UP_CLOAK] = stat & CONST.PLAYER_STATUS_CLOAKED;
has_power_up_array[CONST.POWER_UP_INVINCIBLE] = stat & CONST.PLAYER_STATUS_INVINCIBLE;
has_power_up_array[CONST.POWER_UP_G_OBJECT] = stat & CONST.PLAYER_STATUS_HAS_G_OBJECT;
has_power_up_array[CONST.POWER_UP_BOMB] = stat & CONST.PLAYER_STATUS_HAS_BOMB;
v_x -= CONST.PLAYER_FRICTION*v_x*interval;
v_y -= CONST.PLAYER_FRICTION*v_y*interval;
if (stat & CONST.PLAYER_STATUS_DEAD)
{
move_command_state = 0;
angle -= CONST.PLAYER_ROTATE_SPEED*interval;
}
if (shield_fade > 0) shield_fade -= interval;
if (fire_battery > 0) fire_battery -= interval;
if (move_command_state & CONST.COMMAND_ROTATE_CC) angle -= CONST.PLAYER_ROTATE_SPEED*interval;
if (move_command_state & CONST.COMMAND_MOVE_FORWARD)
{
v_x += CONST.PLAYER_ACCELERATION*interval*Math.cos(angle);
v_y += CONST.PLAYER_ACCELERATION*interval*Math.sin(angle);
}
if (move_command_state & CONST.COMMAND_ROTATE_CW) angle += CONST.PLAYER_ROTATE_SPEED*interval;
if (move_command_state & CONST.COMMAND_MOVE_BACKWARD)
{
v_x -= CONST.PLAYER_ACCELERATION*interval*Math.cos(angle);
v_y -= CONST.PLAYER_ACCELERATION*interval*Math.sin(angle);
}
if (move_command_state & CONST.COMMAND_STRAFE_LEFT)
{
v_x += CONST.PLAYER_ACCELERATION*interval*Math.sin(angle);
v_y -= CONST.PLAYER_ACCELERATION*interval*Math.cos(angle);
}
if (move_command_state & CONST.COMMAND_STRAFE_RIGHT)
{
v_x -= CONST.PLAYER_ACCELERATION*interval*Math.sin(angle);
v_y += CONST.PLAYER_ACCELERATION*interval*Math.cos(angle);
}
if (fire_battery <= 0 && move_command_state & CONST.COMMAND_FIRE)
{
fire_battery = CONST.PLAYER_FIRE_BATTERY;
v_x -= CONST.PARTICLE_MASS*CONST.PARTICLE_INITIAL_VELOCITY*Math.cos(angle)/mass;
v_y -= CONST.PARTICLE_MASS*CONST.PARTICLE_INITIAL_VELOCITY*Math.sin(angle)/mass;
}
if (stat & CONST.PLAYER_STATUS_HAS_G_OBJECT && move_command_state & CONST.COMMAND_G_OBJECT)
{
v_x -= CONST.G_OBJECT_LAUNCH_MASS*CONST.G_OBJECT_INITIAL_VELOCITY*Math.cos(angle)/mass;
v_y -= CONST.G_OBJECT_LAUNCH_MASS*CONST.G_OBJECT_INITIAL_VELOCITY*Math.sin(angle)/mass;
}
if (stat & CONST.PLAYER_STATUS_HAS_BOMB && move_command_state & CONST.COMMAND_BOMB)
{
v_x -= CONST.BOMB_LAUNCH_MASS*CONST.BOMB_INITIAL_VELOCITY*Math.cos(angle)/mass;
v_y -= CONST.BOMB_LAUNCH_MASS*CONST.BOMB_INITIAL_VELOCITY*Math.sin(angle)/mass;
}
pos_x += v_x*interval;
pos_y += v_y*interval;
if (health < health_then) shield_fade = CONST.PLAYER_SHIELD_FADE_MAX;
health_then = health;
// Handles wall bounce
if (pos_x - radius <= 0)
{v_x = -CONST.PLAYER_WALL_LOSS*v_x; pos_x = radius;}
else if (pos_x + radius >= CONST.MAP_WIDTH)
{v_x = -CONST.PLAYER_WALL_LOSS*v_x; pos_x = CONST.MAP_WIDTH-radius;}
if (pos_y - radius <= 0)
{v_y = -CONST.PLAYER_WALL_LOSS*v_y; pos_y = radius;}
else if (pos_y + radius >= CONST.MAP_HEIGHT)
{v_y = -CONST.PLAYER_WALL_LOSS*v_y; pos_y = CONST.MAP_HEIGHT-radius;}
// Handles map location for drawing
if (pos_x <= CONST.CANVAS_WIDTH/2)
{this.map_pos_x = 0; canvas_pos_x = pos_x;}
else if (pos_x >= CONST.MAP_WIDTH - CONST.CANVAS_WIDTH/2)
{this.map_pos_x = CONST.MAP_WIDTH - CONST.CANVAS_WIDTH; canvas_pos_x = CONST.CANVAS_WIDTH - CONST.MAP_WIDTH + pos_x;}
else {this.map_pos_x = pos_x - CONST.CANVAS_WIDTH/2; canvas_pos_x = CONST.CANVAS_WIDTH/2;}
if (pos_y <= CONST.CANVAS_HEIGHT/2)
{this.map_pos_y = 0; canvas_pos_y = pos_y;}
else if (pos_y >= CONST.MAP_HEIGHT - CONST.CANVAS_HEIGHT/2)
{this.map_pos_y = CONST.MAP_HEIGHT - CONST.CANVAS_HEIGHT; canvas_pos_y = CONST.CANVAS_HEIGHT - CONST.MAP_HEIGHT + pos_y;}
else {this.map_pos_y = pos_y - CONST.CANVAS_HEIGHT/2; canvas_pos_y = CONST.CANVAS_HEIGHT/2;}
move_command_state = 0;
};
function draw_player(context)
{
var gradient = context.createRadialGradient(0, 0, 0, 0, 0, 1*radius);
gradient.addColorStop(0, CONST.TEAM_DARK[team]);
gradient.addColorStop(1, "black");
context.beginPath();
context.moveTo(radius,0);
context.lineTo(CONST.PLAYER_WING_ANGLE_COS,CONST.PLAYER_WING_ANGLE_SIN);
context.lineTo(0,0);
context.lineTo(CONST.PLAYER_WING_ANGLE_COS,-CONST.PLAYER_WING_ANGLE_SIN);
context.lineTo(radius,0);
context.closePath();
context.fillStyle = gradient;
context.fill();
context.lineWidth = 1;
context.strokeStyle = "gray";
context.stroke();
}
function draw_moving(context)
{
var gradient;
context.beginPath();
context.moveTo(0,0);
context.lineTo(CONST.PLAYER_WING_ANGLE_COS,CONST.PLAYER_WING_ANGLE_SIN);
context.arc(0,0,radius,-CONST.PLAYER_WING_ANGLE,CONST.PLAYER_WING_ANGLE,true);
context.lineTo(CONST.PLAYER_WING_ANGLE_COS,-CONST.PLAYER_WING_ANGLE_SIN);
context.moveTo(0,0);
context.closePath();
gradient = context.createRadialGradient(0, 0, 0, 0, 0, radius);
gradient.addColorStop(0, CONST.TEAM_LIGHT[team]);
gradient.addColorStop(0.4+0.3*Math.random(), CONST.TEAM_LIGHT[team]);
gradient.addColorStop(1, "transparent");
context.strokeStyle = "transparent";
context.fillStyle = gradient;
context.fill();
context.stroke();
}
function draw_cloaked(context)
{
var gradient;
context.beginPath();
context.arc(0,0,CONST.PLAYER_SHIELD_RADIUS,0,2*Math.PI,false);
gradient = context.createRadialGradient(0, 0, 0, 0, 0, radius*2);
gradient.addColorStop(0, "transparent");
gradient.addColorStop(1, "violet");
context.fillStyle = gradient;
context.fill();
context.stroke();
}
function draw_invincible(context)
{
var gradient;
context.beginPath();
context.arc(0,0,CONST.PLAYER_SHIELD_RADIUS,0,2*Math.PI,false);
gradient = context.createRadialGradient(0, 0, 0, 0, 0, radius*2);
gradient.addColorStop(0, "transparent");
gradient.addColorStop(0.5+0.1*Math.random(), "white");
gradient.addColorStop(1, "transparent");
context.fillStyle = gradient;
context.fill();
context.stroke();
}
function draw_shield_fade(context)
{
var gradient;
context.beginPath();
context.arc(0,0,CONST.PLAYER_SHIELD_RADIUS,0,2*Math.PI,false);
gradient = context.createRadialGradient(0, 0, 0, 0, 0, radius*2);
gradient.addColorStop(0, "transparent");
gradient.addColorStop(1-shield_fade/CONST.PLAYER_SHIELD_FADE_MAX, CONST.TEAM_LIGHT[team]);
gradient.addColorStop(1, "transparent");
context.fillStyle = gradient;
context.fill();
context.stroke();
}
this.draw = function (context) {
context.save();
context.translate(canvas_pos_x, canvas_pos_y);
context.rotate(angle);
var gradient;
draw_player(context);
if (stat & CONST.PLAYER_STATUS_MOVING) draw_moving(context);
if (has_power_up_array[CONST.POWER_UP_CLOAK])draw_cloaked(context);
if (has_power_up_array[CONST.POWER_UP_INVINCIBLE]) draw_invincible(context);
if (shield_fade > 0) draw_shield_fade(context);
context.restore();
if (health > 0){
for (var i = -1; i <= 1; i += 2){
context.save();
context.translate(CONST.HEALTH_LOCATION_X,CONST.HEALTH_LOCATION_Y);
context.scale(i,1)
context.beginPath();
gradient = context.createLinearGradient(0,0,CONST.HEALTH_WIDTH,0);
gradient.addColorStop(0, CONST.TEAM_DARK[team]);
gradient.addColorStop(1, CONST.TEAM_LIGHT[team]);
context.rect(0,0,CONST.HEALTH_WIDTH*health/CONST.PLAYER_MAX_HEALTH, CONST.HEALTH_HEIGHT);
context.fillStyle = gradient;
context.fill();
context.lineWidth = 1;
context.strokeStyle = CONST.TEAM_DARK[team];
context.stroke();
context.restore();
}}
for (var u in has_power_up_array)
{
if (has_power_up_array[u])
{
context.save();
context.translate(CONST.HAS_LOC_X[u], CONST.HAS_LOC_Y[u]);
gradient = context.createRadialGradient(CONST.INFO_BOX_SIDE/2, CONST.INFO_BOX_SIDE/2, 0, CONST.INFO_BOX_SIDE/2, CONST.INFO_BOX_SIDE/2, CONST.INFO_BOX_SIDE);
gradient.addColorStop(0, CONST.TEAM_LIGHT[CONST.TEAM0]);
gradient.addColorStop(1, CONST.TEAM_DARK[CONST.TEAM0]);
context.fillStyle = gradient;
context.lineWidth = 1;
context.strokeStyle = CONST.TEAM_DARK[CONST.TEAM0];
context.fillRect(0, 0, CONST.INFO_BOX_SIDE, CONST.INFO_BOX_SIDE);
context.fillStyle = CONST.POWER_UP_TEXT_COLOR;
context.font = CONST.POWER_UP_FONT;
context.fillText(CONST.POWER_UP_CHAR[u],3,CONST.INFO_BOX_SIDE-5);
context.restore();
}
}
};
this.net_draw = function(context, map_pos_x, map_pos_y){
if (stat & CONST.PLAYER_STATUS_CLOAKED) return;
var x = pos_x - map_pos_x;
var y = pos_y - map_pos_y;
if (x >= (-radius) && x <= (CONST.CANVAS_WIDTH + radius) && y >= (-radius) && y <= (CONST.CANVAS_HEIGHT + radius))
{
context.save();
context.translate(x, y);
context.rotate(angle);
draw_player(context);
if (stat & CONST.PLAYER_STATUS_MOVING) draw_moving(context);
if (shield_fade > 0) draw_shield_fade(context);
if (has_power_up_array[CONST.POWER_UP_INVINCIBLE]) draw_invincible(context);
context.restore();
}
};
return this;
}
function Particle(p_id,x,y,v_x,v_y,p_color){
var id = p_id,
pos_x = x,
pos_y = y,
v_x = v_x,
v_y = v_y,
mass = CONST.PARTICLE_MASS,
charge = CONST.PARTICLE_CHARGE,
p_color = p_color,
size = CONST.PARTICLE_SIZE,
half_size = size/2;
this.server_update = function(data)
{
var diff_x = data['x'] - pos_x;
var diff_y = data['y'] - pos_y;
if (Math.abs(diff_x) > CONST.PARTICLE_CORRECT_X)
pos_x = data['x'];
else pos_x += diff_x*CONST.PARTICLE_CORRECTION_PERCENT;
if (Math.abs(diff_y) > CONST.PARTICLE_CORRECT_Y)
pos_y = data['y'];
else pos_y += diff_y*CONST.PARTICLE_CORRECTION_PERCENT;
v_x = data['v_x'];
v_y = data['v_y'];
};
this.refresh = function(interval) {
pos_x += v_x*interval;
pos_y += v_y*interval;
if (pos_x >= CONST.MAP_WIDTH) {pos_x = CONST.MAP_WIDTH - 1; v_x = -v_x*CONST.PARTICLE_WALL_LOSS;}
else if (pos_x <= 0) {pos_x = 1; v_x = -v_x*CONST.PARTICLE_WALL_LOSS;}
if (pos_y >= CONST.MAP_HEIGHT) {pos_y = CONST.MAP_HEIGHT - 1; v_y = -v_y*CONST.PARTICLE_WALL_LOSS;}
else if (pos_y <= 0) {pos_y = 1; v_y = -v_y*CONST.PARTICLE_WALL_LOSS;}
};
this.draw = function(context, map_pos_x, map_pos_y) {
var gradient;
var x = pos_x - map_pos_x;
var y = pos_y - map_pos_y;
if (x >= 0 && x <= CONST.CANVAS_WIDTH && y >= 0 && y <= CONST.CANVAS_HEIGHT)
{
context.save();
context.translate(x, y);
context.beginPath();
context.arc(0,0,size,0,2*Math.PI,false);
gradient = context.createRadialGradient(0, 0, 0, 0, 0, size);
gradient.addColorStop(0, "black");
gradient.addColorStop(1, p_color);
context.fillStyle = gradient;
context.fill();
context.lineWidth = 1;
context.strokeStyle = p_color;
context.stroke();
context.restore();
}
};
return this;
}
function G_Object(x, y, v_x, v_y, team)
{
var pos_x = x,
pos_y = y,
v_x = v_x,
v_y = v_y,
radius = CONST.G_OBJECT_MIN_RADIUS,
mass = CONST.G_OBJECT_MASS,
object_type = CONST.OBJ_G_OBJECT,
team = team,
timer = CONST.G_OBJECT_TIME_TO_DET,
stat = 0,
timer_ceil = Math.ceil(timer/1000),
blast_played = false;
this.server_update = function(data)
{
var diff_x = data['x'] - pos_x;
var diff_y = data['y'] - pos_y;
if (Math.abs(diff_x) > CONST.OBJECT_POSITION_CORRECT_X)
pos_x = data['x'];
else pos_x += diff_x*CONST.POSITION_CORRECTION_PERCENT;
if (Math.abs(diff_y) > CONST.OBJECT_POSITION_CORRECT_Y)
pos_y = data['y'];
else pos_y += diff_y*CONST.POSITION_CORRECTION_PERCENT;
v_x = data['v_x'];
v_y = data['v_y'];
stat = data['stat'];
timer = data['timer'];
};
this.refresh = function(interval, par_col, player_list, obj_ids_to_del)
{
if (pos_x - radius <= 0)
{v_x = -CONST.G_OBJECT_WALL_LOSS*v_x; pos_x = radius;}
else if (pos_x + radius >= CONST.MAP_WIDTH)
{v_x = -CONST.G_OBJECT_WALL_LOSS*v_x; pos_x = CONST.MAP_WIDTH-radius;}
if (pos_y - radius <= 0)
{v_y = -CONST.G_OBJECT_WALL_LOSS*v_y; pos_y = radius;}
else if (pos_y + radius >= CONST.MAP_HEIGHT)
{v_y = -CONST.G_OBJECT_WALL_LOSS*v_y; pos_y = CONST.MAP_HEIGHT-radius;}
pos_x += v_x*interval;
pos_y += v_y*interval;
if (stat & CONST.G_OBJECT_STATUS_DETONATED) radius = CONST.G_OBJECT_MAX_RADIUS;
timer -= interval;
if (timer < 0) timer = 0;
}
this.draw = function (context, map_pos_x, map_pos_y)
{
var x = pos_x - map_pos_x;
var y = pos_y - map_pos_y;
if (x >= (-radius) && x <= (CONST.CANVAS_WIDTH + radius) && y >= (-radius) && y <= (CONST.CANVAS_HEIGHT + radius))
{
if (Math.ceil(timer/1000) < timer_ceil && !(stat & CONST.G_OBJECT_STATUS_DETONATED))
{
tick.play();
timer_ceil = Math.ceil(timer/1000);
}
else if (stat & CONST.G_OBJECT_STATUS_DETONATED && !blast_played)
{
g_obj.play();
blast_played = true;
}
context.save();
context.translate(x, y);
var gradient = context.createRadialGradient(0, 0, 0, 0, 0, 1*radius);
if (stat == 0){
gradient.addColorStop(0, CONST.TEAM_LIGHT[team]);
gradient.addColorStop(1, CONST.TEAM_DARK[team]);
} else if (stat & CONST.G_OBJECT_STATUS_DETONATED){
gradient.addColorStop(0, "transparent");
gradient.addColorStop(1 - timer/CONST.G_OBJECT_TIME_TO_LAST, CONST.TEAM_DARK[team]);
gradient.addColorStop(1, "transparent");
}
context.beginPath();
context.arc(0,0,radius,0,2*Math.PI,false);
context.fillStyle = gradient;
context.fill();
context.stroke();
if (stat == 0){
context.fillStyle = CONST.POWER_UP_TEXT_COLOR;
context.font = CONST.POWER_UP_FONT;
context.fillText(timer_ceil,-6,5);
}
context.restore();
}
}
return this;
};
function Bomb(x, y, v_x, v_y, team, obj_id, player_id)
{
var pos_x = x,
pos_y = y,
v_x = v_x,
v_y = v_y,
radius = CONST.BOMB_MIN_RADIUS,
mass = CONST.BOMB_MASS,
object_type = CONST.OBJ_BOMB,
team = team,
obj_id = obj_id,
player_id = player_id,
timer = CONST.BOMB_TIME_TO_DET,
stat = 0,
timer_ceil = Math.ceil(timer/1000),
blast_played = false;
this.server_update = function(data)
{
var diff_x = data['x'] - pos_x;
var diff_y = data['y'] - pos_y;
if (Math.abs(diff_x) > CONST.OBJECT_POSITION_CORRECT_X)
pos_x = data['x'];
else pos_x += diff_x*CONST.POSITION_CORRECTION_PERCENT;
if (Math.abs(diff_y) > CONST.OBJECT_POSITION_CORRECT_Y)
pos_y = data['y'];
else pos_y += diff_y*CONST.POSITION_CORRECTION_PERCENT;
v_x = data['v_x'];
v_y = data['v_y'];
stat = data['stat'];
timer = data['timer'];
};
this.refresh = function(interval, par_col, player_list, obj_ids_to_del)
{
if (pos_x - CONST.BOMB_MIN_RADIUS <= 0)
{v_x = -CONST.BOMB_WALL_LOSS*v_x; pos_x = radius;}
else if (pos_x + CONST.BOMB_MIN_RADIUS >= CONST.MAP_WIDTH)
{v_x = -CONST.BOMB_WALL_LOSS*v_x; pos_x = CONST.MAP_WIDTH-radius;}
if (pos_y - CONST.BOMB_MIN_RADIUS <= 0)
{v_y = -CONST.BOMB_WALL_LOSS*v_y; pos_y = radius;}
else if (pos_y + CONST.BOMB_MIN_RADIUS >= CONST.MAP_HEIGHT)
{v_y = -CONST.BOMB_WALL_LOSS*v_y; pos_y = CONST.MAP_HEIGHT-radius;}
if (stat & CONST.BOMB_STATUS_DETONATED)
{
radius = CONST.BOMB_BLAST_RADIUS;
v_x = v_y = 0;
}
pos_x += v_x*interval;
pos_y += v_y*interval;
timer -= interval;
if (timer < 0) timer = 0;
};
this.draw = function (context, map_pos_x, map_pos_y)
{
var x = pos_x - map_pos_x;
var y = pos_y - map_pos_y;
if (x >= (-radius) && x <= (CONST.CANVAS_WIDTH + radius) && y >= (-radius) && y <= (CONST.CANVAS_HEIGHT + radius))
{
if (Math.ceil(timer/1000) < timer_ceil && !(stat & CONST.G_OBJECT_STATUS_DETONATED))
{
tick.play();
timer_ceil = Math.ceil(timer/1000);
}
else if (stat & CONST.G_OBJECT_STATUS_DETONATED && !blast_played)
{
blast.play();
blast_played = true;
}
context.save();
context.translate(x, y);
var gradient = context.createRadialGradient(0, 0, 0, 0, 0, 1*radius);
if (stat == 0){
gradient.addColorStop(0, CONST.TEAM_LIGHT[team]);
gradient.addColorStop(1, CONST.TEAM_DARK[team]);
} else if (stat & CONST.BOMB_STATUS_DETONATED){
gradient.addColorStop(0, "transparent");
gradient.addColorStop(1 - timer/CONST.BOMB_TIME_TO_LAST, CONST.TEAM_LIGHT[team]);
gradient.addColorStop(1, "transparent");
}
context.beginPath();
context.arc(0,0,radius,0,2*Math.PI,false);
context.fillStyle = gradient;
context.fill();
context.lineWidth = 0;
context.strokeStyle = "transparent";
context.stroke();
if (stat == 0){
context.fillStyle = CONST.POWER_UP_TEXT_COLOR;
context.font = CONST.POWER_UP_FONT;
context.fillText(timer_ceil,-6,5);
}
context.restore();
}
}
return this;
}
function Power_Up_Object(x, y, v_x, v_y, power_up_type)
{
var pos_x = x,
pos_y = y,
v_x = v_x,
v_y = v_y,
radius = CONST.POWER_UP_RADIUS,
type = CONST.OBJ_POWER_UP,
power_up_type = power_up_type,
text = CONST.POWER_UP_CHAR[power_up_type];
this.server_update = function(data)
{
var diff_x = data['x'] - pos_x;
var diff_y = data['y'] - pos_y;
if (Math.abs(diff_x) > CONST.OBJECT_POSITION_CORRECT_X)
pos_x = data['x'];
else pos_x += diff_x*CONST.POSITION_CORRECTION_PERCENT;
if (Math.abs(diff_y) > CONST.OBJECT_POSITION_CORRECT_Y)
pos_y = data['y'];
else pos_y += diff_y*CONST.POSITION_CORRECTION_PERCENT;
v_x = data['v_x'];
v_y = data['v_y'];
};
this.refresh = function(interval)
{
if (pos_x - radius <= 0)
{v_x = -CONST.G_OBJECT_WALL_LOSS*v_x; pos_x = radius;}
else if (pos_x + radius >= CONST.MAP_WIDTH)
{v_x = -CONST.G_OBJECT_WALL_LOSS*v_x; pos_x = CONST.MAP_WIDTH-radius;}
if (pos_y - radius <= 0)
{v_y = -CONST.G_OBJECT_WALL_LOSS*v_y; pos_y = radius;}
else if (pos_y + radius >= CONST.MAP_HEIGHT)
{v_y = -CONST.G_OBJECT_WALL_LOSS*v_y; pos_y = CONST.MAP_HEIGHT-radius;}
pos_x += v_x*interval;
pos_y += v_y*interval;
};
this.draw = function (context, map_pos_x, map_pos_y)
{
var x = pos_x - map_pos_x;
var y = pos_y - map_pos_y;
if (x >= (-radius) && x <= (CONST.CANVAS_WIDTH + radius) && y >= (-radius) && y <= (CONST.CANVAS_HEIGHT + radius))
{
context.save();
context.translate(x, y);
var gradient = context.createRadialGradient(0, 0, 0, 0, 0, 1*radius);
gradient.addColorStop(0, CONST.TEAM_LIGHT[CONST.TEAM0]);
gradient.addColorStop(1, CONST.TEAM_DARK[CONST.TEAM0]);
context.beginPath();
context.arc(0,0,radius,0,2*Math.PI,false);
context.fillStyle = gradient;
context.fill();
context.stroke();
context.fillStyle = CONST.POWER_UP_TEXT_COLOR;
context.font = CONST.POWER_UP_FONT;
context.fillText(text,-6,5);
context.restore();
}
}
};
function Game()
{
var request_id;
var interval_id;
var main_canvas = $("<canvas id='main_canvas' width='" + CONST.CANVAS_WIDTH + "' height='" + CONST.CANVAS_HEIGHT + "'>Update your browser</canvas>");
var main_context = main_canvas.get(0).getContext('2d');
var server_url = 'http://' + (window.location.hostname || "localhost") + ':8080';
var socket;
var socket_worker;
var key_down = {};
var background = new Background();
var draw_timer = new Timer();
var refresh_timer = new Timer();
var ping_timer = new Timer();
var ping = 0;
var ping_arr = [];
for (var i=0; i<200;i++) ping_arr.push(0);
var debug = false;
var frame_rates = false;
var quit = false;
var player_col = {};
var player_id = 0;
var par_col = {};
var obj_col = {};
function draw_ping (context)
{
var ping_max = 200;
context.save();
context.fillStyle = "lime";
context.fillText(ping_max, 10, 10);
context.fillText((1000/ping_timer.frame_rate).toFixed(1), 10, 30);
context.fillText("0", 10, 50);
for (var i = 0, len = ping_arr.length; i < len; i++)
{
context.beginPath();
context.strokeStyle = "lime";
context.lineWidth = 1;
context.moveTo(40+i,ping_max-ping_arr[i]>0?50*(ping_max-ping_arr[i])/ping_max:0);
context.lineTo(40+i,50);
context.stroke();
}
context.restore();
}
this.initialize = function () {
background.initialize();
$(window)['keydown'](function (key_code) {
if (debug) console.log("Key down: " + key_code.keyCode);
key_down[key_code.keyCode]=true;
});
$(window)['keyup'](function (key_code) {
if (key_code.keyCode==CONST.KEY_CODE_DEBUG) { debug = !debug; console.log("Debug " + (debug?"on.":"off.")); }
if (key_code.keyCode==CONST.KEY_CODE_FRAMERATE) frame_rates = !frame_rates;
if (debug) console.log("Key up: " + key_code.keyCode);
key_down[key_code.keyCode]=false;
});
console.log("Attempting to connect to " + server_url);
socket = io['connect'](server_url);
//if (socket) console.log("Server is down");
socket['on']("connect", function(){console.log("connected...");});
socket['on']("error", function(){console.log("connection error...");});
socket['on']("player_id", function(data){ player_id = data['p_id']; player_col[player_id] = new Player(data['team']); });
socket['on']("player_list", function(data){
for (var u in data) if (typeof player_col[u] === 'undefined') player_col[u] = new Player(data[u]);
});
socket['on']("player_removed", function(data){delete player_col[data]; });
socket['on']("par", function(data){
if (typeof par_col[data['id']] === 'undefined') par_col[data['id']] = new Particle(data['id'],data['x'],data['y'],data['v_x'],data['v_y'],CONST.PARTICLE_COLOR);
par_col[data['id']].server_update(data);
});
socket['on']("par_delete", function(data) { delete par_col[data]; });
socket['on']("obj", function(data){
if (typeof obj_col[data['id']] === 'undefined'){
switch (data['type']){
case CONST.OBJ_POWER_UP:
obj_col[data['id']] = new Power_Up_Object(data['x'], data['y'], data['v_x'], data['v_y'], data['p_t']);
break;
case CONST.OBJ_G_OBJECT:
obj_col[data['id']] = new G_Object(data['x'], data['y'], data['v_x'], data['v_y'], data['team']);
break;
case CONST.OBJ_BOMB:
obj_col[data['id']] = new Bomb(data['x'], data['y'], data['v_x'], data['v_y'], data['team']);
break;
}
}
obj_col[data['id']].server_update(data);
});
socket['on']("obj_delete", function(data) { delete obj_col[data]; });
var init_wait = function(){
if (player_id != 0){
socket['on']("pong", function(data){
if (player_id == 0) return;
if (typeof player_col[data['p_id']] === 'undefined')
{
socket['emit']("request_player_list", player_id);
return;
}
if (data['p_id']==player_id)
{
ping = ping_timer.interval;
ping_arr.shift();
ping_arr.push(ping);
if (debug) console.log(ping);
}
player_col[data['p_id']].server_update(data);
});
main_canvas['appendTo']("body");
refresh();
interval_id = setInterval(refresh, 1000/CONST.UPS);
draw();
} else setTimeout(init_wait, 500);
};
init_wait();
};
function refresh() {
var refresh_interval = refresh_timer.interval;
player_col[player_id].set_command_state(key_down);
if (player_col[player_id].server_set)
{
socket['emit']("ping", player_col[player_id].move_command_state());
player_col[player_id].server_set = false;
}
for (var u in player_col) player_col[u].refresh(refresh_interval);
for (var u in par_col) par_col[u].refresh(refresh_interval);
for (var u in obj_col) obj_col[u].refresh(refresh_interval);
if (frame_rates) console.log("refresh interval: " + refresh_interval + " frame rate: " + refresh_timer.frame_rate.toFixed(2));
if (key_down[81]) {quit = true; clearInterval(interval_id); console.log("Quit command sent");}
//if (!socket.socket.connected) {console.log("socket not connected, quitting"); quit = true;clearInterval(interval_id);}
};
function draw() {
if (!quit) request_id = window.requestAnimFrame(draw);//self.draw);
var draw_interval = draw_timer.interval;
background.draw(main_context, player_col[player_id].map_pos_x, player_col[player_id].map_pos_y);
for (var u in obj_col) obj_col[u].draw(main_context, player_col[player_id].map_pos_x, player_col[player_id].map_pos_y);
for (var u in par_col) par_col[u].draw(main_context, player_col[player_id].map_pos_x, player_col[player_id].map_pos_y);
for (var u in player_col) if (u != player_id) player_col[u].net_draw(main_context, player_col[player_id].map_pos_x, player_col[player_id].map_pos_y);
player_col[player_id].draw(main_context);
if (debug) draw_ping(main_context);
if (frame_rates) console.log("draw interval: " + draw_interval + " frame rate: " + draw_timer.frame_rate.toFixed(2));
};
return this;
}
var main_game = new Game();
main_game.initialize();
})();
<file_sep>/site/constants.js
(function (exports){
var constant_refs =
{
CANVAS_WIDTH: 1024,
CANVAS_HEIGHT: 640,
MAP_SIZE: 11,
PLAYER_WING_ANGLE: 5*Math.PI/6
};
var CONST =
{
ABOUT: "Gravity is a multiplayer 2D space shooter written in javascript using HTML5 Canvas on the client and node.js on the server side.\n\nMovement: Arrow keys to manuever, keys 'E' and 'R' to strafe left and right respectively\n\nBullets (default key 'S'): Supply is limitless but after ten have been fired the earliest bullet fired will disappear.\n\nPower-Ups:\n\nBomb (B) (default key 'B'): A five second count down. The bomb will not harm players on the same team but will still cause a blast effect. Damage to enemy players drops off with distance.\n\nG_Object (G) (default key 'G'): The G_Object is a gravity well with a three second countdown. It will attract enemy team players, all bullets, and all bombs for fifteen seconds.\n\nCloak (C): Your ship will be invisible to all players for 15 seconds.\n\nInvincibility (I): Your ship will take no damage for 10 seconds.",
FPS: 35,
UPS: 35,
TIME_INTERVAL: 1000,
FRAME_MAX: 30,
KEY_CODE_DEBUG: 68,
KEY_CODE_FRAMERATE: 70,
KEY_CODE_ROTATE_CC: 37,
KEY_CODE_ROTATE_CW: 39,
KEY_CODE_MOVE_FORWARD: 38,
KEY_CODE_MOVE_BACKWARD: 40,
KEY_CODE_STRAFE_LEFT: 69,
KEY_CODE_STRAFE_RIGHT: 82,
KEY_CODE_FIRE: 83,
KEY_CODE_G_OBJECT: 71,
KEY_CODE_BOMB: 66,
POSITION_CORRECT_X: 40,
POSITION_CORRECT_Y: 40,
POSITION_CORRECT_ANGLE: Math.PI/3,
POSITION_CORRECTION_PERCENT: 0.1,
CANVAS_WIDTH: constant_refs.CANVAS_WIDTH,
CANVAS_HEIGHT: constant_refs.CANVAS_HEIGHT,
MAP_WIDTH: 2*Math.pow(2, constant_refs.MAP_SIZE),
MAP_HEIGHT: Math.pow(2, constant_refs.MAP_SIZE),
BACKGROUND_STARS0: Math.pow(2,constant_refs.MAP_SIZE + 2),
BACKGROUND_STARS1: 1000,
BACKGROUND_PLANETS0: 10,
BACKGROUND_PLANET_SIZE_MIN: 30,
BACKGROUND_PLANET_SIZE_RANGE: 20,
PARTICLE_SIZE: 4,
PARTICLE_COLOR: "lime",
PARTICLE_WALL_LOSS: 0.5,
PARTICLE_MASS: 100,
PARTICLE_CHARGE: 100,
PARTICLE_INITIAL_VELOCITY: 0.6,// pixels per millisecond
PARTICLE_CORRECT_X: 4,
PARTICLE_CORRECT_Y: 4,
PARTICLE_CORRECTION_PERCENT: 0.2,
PARTICLE_DAMAGE: 120,
OBJECT_POSITION_CORRECT_X: 20,
OBJECT_POSITION_CORRECT_Y: 20,
G_OBJECT_STATUS_DETONATED: 1,
G_OBJECT_TIME_TO_DET: 3000,
G_OBJECT_TIME_TO_LAST: 15000,
G_OBJECT_MIN_RADIUS: 10,
G_OBJECT_MAX_RADIUS: 100,
G_OBJECT_WALL_LOSS: 0.5,
G_OBJECT_LAUNCH_MASS: 2000,
G_OBJECT_INITIAL_VELOCITY: 0.1,
G_OBJECT_MASS: 100,
G_OBJECT_FRICTION: 0.002,
BOMB_STATUS_DETONATED: 1,
BOMB_TIME_TO_DET: 5000,
BOMB_TIME_TO_LAST: 1000,
BOMB_MIN_RADIUS: 10,
BOMB_BLAST_RADIUS: 400,
BOMB_DAMAGE_FACTOR: 1000,
BOMB_WALL_LOSS: 0.5,
BOMB_LAUNCH_MASS: 2000,
BOMB_MASS: 200,
BOMB_INITIAL_VELOCITY: 0.1,
OBJ_POWER_UP: 0,
OBJ_G_OBJECT: 1,
OBJ_BOMB: 2,
HEALTH_LOCATION_X: constant_refs.CANVAS_WIDTH/2,
HEALTH_LOCATION_Y: 10,
HEALTH_WIDTH: 100,
HEALTH_HEIGHT: 20,
POWER_UP_TEXT_COLOR: "black",
POWER_UP_FONT: "bold 20px Courier",
POWER_UP_RADIUS: 10,
POWER_UP_CLOAK: 0,
POWER_UP_INVINCIBLE: 1,
POWER_UP_G_OBJECT: 2,
POWER_UP_BOMB: 3,
POWER_UP_CHAR:["C","I","G","B"],
INFO_BOX_SIDE: 20,
HAS_LOC_X:[constant_refs.CANVAS_WIDTH/2 - 180, constant_refs.CANVAS_WIDTH/2 - 140, constant_refs.CANVAS_WIDTH/2 + 120,constant_refs.CANVAS_WIDTH/2 + 160],
HAS_LOC_Y:[10,10,10,10],
HAS_G_LOCATION_X: constant_refs.CANVAS_WIDTH/2 + 120,
HAS_G_LOCATION_Y: 10,
HAS_CLOAK_LOCATION_X: constant_refs.CANVAS_WIDTH/2 - 140,
HAS_CLOAK_LOCATION_Y: 10,
TEAM0: 0,
TEAM1: 1,
TEAM2: 2,
TEAM3: 3,
TEAM4: 4,
TEAM_DARK: ["black","red","blue","gray","orange"],
TEAM_LIGHT: ["white","pink","cyan","white","yellow"],
WALL_DAMAGE_MINIMUM: 30,
WALL_DAMAGE_MULTIPLIER: 900,
PLAYER_MAX_HEALTH: 1000,
PLAYER_HEALTH_REGEN: 0.1,
PLAYER_MAX_ENERGY: 1000,
PLAYER_MAX_BULLETS: 10,
PLAYER_RADIUS: 20,
PLAYER_SHIELD_RADIUS: 26,
PLAYER_SHIELD_FADE_MAX: 700,
PLAYER_DEAD_COUNTER_MAX: 3000,
PLAYER_CLOAK_TIMER_MAX: 15000,
PLAYER_INVINCIBLE_TIMER_MAX: 10000,
PLAYER_WING_ANGLE: constant_refs.PLAYER_WING_ANGLE,
PLAYER_WING_ANGLE_SIN: 20*Math.sin(constant_refs.PLAYER_WING_ANGLE),
PLAYER_WING_ANGLE_COS: 20*Math.cos(constant_refs.PLAYER_WING_ANGLE),
PLAYER_ACCELERATION: 0.0007,
PLAYER_ROTATE_SPEED: 1/360,
PLAYER_FRICTION: 0.001,
PLAYER_WALL_LOSS: 0.5,
PLAYER_FIRE_BATTERY: 120,
PLAYER_MASS: 2000,
PLAYER_STATUS_MOVING: 1,
PLAYER_STATUS_HIT: 2,
PLAYER_STATUS_INVINCIBLE: 4,
PLAYER_STATUS_CLOAKED: 8,
PLAYER_STATUS_DEAD: 16,
PLAYER_STATUS_HAS_G_OBJECT: 32,
PLAYER_STATUS_HAS_BOMB: 64,
COMMAND_ROTATE_CC: 1,
COMMAND_MOVE_FORWARD: 2,
COMMAND_ROTATE_CW: 4,
COMMAND_MOVE_BACKWARD: 8,
COMMAND_STRAFE_RIGHT: 16,
COMMAND_STRAFE_LEFT: 32,
PLAYER_MOVING: 63,
COMMAND_FIRE: 1024,
COMMAND_G_OBJECT: 2048,
COMMAND_BOMB: 4096
};
if (typeof exports ==='undefined') var exports = {};
exports.getConstants = function () {return CONST;}
})(typeof exports === 'undefined' ? CONSTANTS={}: exports);
| df00e9a34ed59940d8c330305a1f574f0feaeca2 | [
"JavaScript"
] | 3 | JavaScript | dshartnett/gravity | 6b1a07fa514b74468371aa6160171e4098fbb36f | ee86f136696805dcd39f485de8ecd0eda589bc08 | |
refs/heads/master | <repo_name>bluegraybox/js-time-series-chart<file_sep>/mygraph.js
// I don't know if the data is guaranteed to finish loading before the page is ready, so don't try to plot the graph until both are done.
var pageReady = false;
var parsed = false;
var series;
var options = {
xaxis: { mode: "time", timeformat: "%Y/%m/%d" },
yaxis: { min: 0 },
grid: { hoverable: true }
};
// Show the value when we're hovering over a point on the chart
function hover(event, pos, item) {
if (item) {
$("#label").css("display", "block");
$("#label").css("position", "absolute");
// Offset the label so it's not covered by the cursor
$("#label").css("left", (item.pageX + 10) + "px");
$("#label").css("top", (item.pageY - 20) + "px");
$("#label").text(item.datapoint[1]);
}
else {
$("#label").css("display", "none");
}
};
// parse a point of the form [ '2017-11-13 00:00:00', 271662.4285714286 ]
// into JS time and integer
function parsePoint(text) {
var ds = text[0].replace(/ /, 'T');
var d = new Date(ds);
return [d.getTime(), Math.round(text[1])];
}
// parse all the points in a series
function parseSeries(text) {
return text.map(parsePoint);
}
// parse all the series in the response
// This is the function specified in index.html as the JSONP callback, which is invoked when the data finishes loading.
// (Which is why it's not referenced anywhere else in this file.)
function parseResponse(text) {
series = text.map(parseSeries);
parsed = true;
plotSeries();
}
// use Flot to plot the series on the chart
function plotSeries() {
// only if the page is ready and the data is loaded and parsed
if (parsed && pageReady) {
var placeholder = $("#placeholder");
var p = $.plot(placeholder, series, options);
// call our hover function on plothover events
placeholder.bind("plothover", hover);
}
}
// when the page is ready
$(function () {
pageReady = true;
plotSeries();
});
<file_sep>/random.cgi
#!/bin/bash
# Web service that generates a random number and returns it as JSONP.
echo 'Content-type: application/javascript'
echo
echo "addData($RANDOM);"
<file_sep>/README.md
# JS Time Series Chart
Very simple demo project using [Flot](https://github.com/flot/flot/blob/master/README.md) to graph time series data.
Data is stored as JavaScript in `n-transactions.js` and loaded using JSONP.
It's done this way so that you don't need to run a web server - you can just open the `index.html` file in a browser.
At first, I tried to load the data file with jQuery's `load` function, and got a cross-site request error.
For security reasons I don't fully understand, Chrome won't load files with a `file:` URL - it requires `http:`.
So you need to be running a web server, and getting that set up and configured is more hassle than I want to put someone through.
# Realtime
The various `realtime` files demonstrate graphing a continuous feed of data from a service.
They require a web server because the data service is a local CGI script.
<file_sep>/realtime.js
/* Display a graph of historical values retrieved from the random.cgi service.
* Clicking anywhere on the page pauses/resumes the requests to the server.
*/
var SERVICE_URL = 'http://localhost/~colin/jsgraph/random.cgi';
var MAX_POINTS = 1000; // How much history we keep
var UPDATE_INTERVAL = 250; // Delay between updates, in milliseconds
var timer;
var series = [];
var options = {
xaxis: { mode: "time", timeformat: "%M:%S" }, // only show minutes & seconds
yaxis: { min: 0 },
grid: { hoverable: true }
};
// Show the value when we're hovering over a point on the chart
function hover(event, pos, item) {
if (item) {
$("#label").css("display", "block");
$("#label").css("position", "absolute");
// Offset the label so it's not covered by the cursor
$("#label").css("left", (item.pageX + 10) + "px");
$("#label").css("top", (item.pageY - 20) + "px");
$("#label").text(item.datapoint[1]);
}
else {
$("#label").css("display", "none");
}
};
// Callback function which adds retrieved value to time series.
function addData(response) {
var timestamp = (new Date()).getTime();
series.push([timestamp, response]);
plotSeries();
while (series.length > MAX_POINTS) {
series.shift();
}
};
// Fetch data from web service
function update() {
$.ajax({
url: SERVICE_URL,
jsonp: 'addData',
dataType: 'jsonp',
success: function(response) {
// addData() does all the work
}
});
}
// use Flot to plot the series on the chart
function plotSeries() {
if (series.length < 2)
return;
var placeholder = $("#placeholder");
var p = $.plot(placeholder, [series], options);
}
// Start timer to periodically fetch data.
function startTimer() {
timer = setInterval(update, UPDATE_INTERVAL);
}
// Pause or resume fetching of data
function toggleTimer() {
if (timer) {
clearTimeout(timer);
timer = undefined;
}
else {
startTimer();
}
}
// when the page is ready
$(function () {
// call our hover function on plothover events
var placeholder = $("#placeholder");
placeholder.bind("plothover", hover);
addEventListener("click", toggleTimer);
timer = setInterval(update, 250);
});
| d2f17570237a333f5aa44e3f0f6dd96216a6537f | [
"JavaScript",
"Markdown",
"Shell"
] | 4 | JavaScript | bluegraybox/js-time-series-chart | f95b2649b2d33f9f1039b5ae5cf5ec184f691692 | b08cbef0c3232faed839b143b26fd68179955697 | |
refs/heads/master | <file_sep>drop schema if exists sbkavtal cascade;
create schema sbkavtal;
drop table if exists sbkavtal.avtal;
drop table if exists sbkavtal.person;
drop table if exists sbkavtal.intaktskontering;
drop table if exists sbkavtal.avtalsinnehåll;
drop type if exists sbkavtal.avtalsstatus;
create type sbkavtal.avtalsstatus as enum('Aktivt', 'Inaktivt');
drop type if exists sbkavtal.motpartstyp;
create type sbkavtal.motpartstyp as enum('Extern', 'Förvaltning', 'Kommunalt bolag', 'Uppgift saknas);
drop type if exists sbkavtal.avtalsinnehallstyp;
create type sbkavtal.avtalsinnehallstyp as enum('avtalsinnehåll 1', 'avtalsinnehåll 2', 'avtalsinnehåll 3');
create table sbkavtal.person(
id serial primary key,
first_name varchar(50),
last_name varchar(50),
belagenhetsadress varchar(50),
postnummer varchar(20),
postort varchar(50),
tfn_nummer varchar(20),
epost varchar(50)
);
create table sbkavtal.fakturaadress(
id serial primary key,
first_name varchar,
last_name varchar,
belagenhetsadress varchar,
postnummer varchar,
postort varchar,
referens varchar
);
create table sbkavtal.avtal(
id serial primary key,
diarienummer bigint,
status avtalsstatus,
startdate date,
enddate date,
orgnummer varchar(20),
motpartstyp motpartstyp,
SBKavtalsid int,
scan_url varchar(512),
enligt_avtal text,
internt_alias text,
kommentar text,
avtalstecknare integer references person,
avtalskontakt integer references person,
upphandlat_av integer references person,
ansvarig_SBK integer references person,
ansvarig_avd varchar(50),
ansvarig_enhet varchar(50),
-- avtalsinnehall text,
avtalsvärde bigint,
datakontakt person,
-- intaktskontering integer references intaktskontering,
konto varchar not null,
kstl varchar not null,
vht varchar not null,
mtp varchar not null,
aktivitet varchar not null,
objekt varchar not null,
projekt varchar not null,
fakt_adress integer references sbkavtal.fakturaadress,
vitalt_avtal boolean,
gallringsår date
);
create table sbkavtal.avtalsinnehall(
id serial primary key,
innehall sbkavtal.avtalsinnehallstyp,
avtalsid integer references avtal not null
);
-- insert into sbkavtal.person(first_name, last_name, belagenhetsadress, postnummer, postort, tfn_nummer, epost)
-- values ('Sven', 'Andersson', 'Svedalavägen', '111 11', 'Svedala', '010-100100', '<EMAIL>');
--
-- insert into sbkavtal.avtal(diarienummer, startdate, enddate, orgnummer, status, avtalstecknare, avtalskontakt)
-- values (314, '2017-01-01', CURRENT_DATE, '820403', 'Aktivt', 1, 1);
-- -- (1000, CURRENT_DATE, CURRENT_DATE, '820403', 'Aktivt'),
-- -- (666, '1982-04-03', CURRENT_DATE, '140807', 'Inaktivt');
--
-- select * from sbkavtal.avtal inner join sbkavtal.person
-- on sbkavtal.avtal.avtalstecknare = sbkavtal.person.id;
-- --select * from person;
--
-- insert into sbkavtal.avtalsinnehall(innehall, avtalsid)
-- select 'avtalsinnehåll 1', id from sbkavtal.avtal where diarienummer = 314;
--
--
--
-- select * from sbkavtal.avtalsinnehall;
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Configuration;
using Npgsql;
namespace SBKAvtalskatalog.Controllers
{
[RoutePrefix("")]
[Route("{action=index}")]
public class KatalogController : Controller
{
// GET: Katalog
[Route("")]
public ActionResult Index()
{
return View();
}
[Route("Start")]
public ActionResult Start()
{
return View();
}
public ActionResult TestPage()
{
return View();
}
[Route("editpage")]
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult EditPage()
{
var model = new Models.Avtalsmodel
{
diarienummer = 555,
startdate = DateTime.Now,
enddate = DateTime.Now,
orgnummer = "7707077777"
};
return View(model);
}
[Route("editpage")]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditPage(Models.Avtalsmodel model)
{
System.Diagnostics.Debug.WriteLine("Diarienummer:" + model.diarienummer);
return Redirect("/Tabell");
}
[Route("Tabell")]
public ActionResult Tabell()
{
var cs = connstr();
var lst = new List<SBKAvtalskatalog.Models.Avtalsmodel>();
using (var conn = new NpgsqlConnection("Host=localhost;Username=postgres;Database=avtalskatalogSBK"))
{
conn.Open();
using (var cmd = new NpgsqlCommand())
{
cmd.Connection = conn;
cmd.CommandText = "select diarienummer, startdate, enddate, orgnummer from avtal";
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
lst.Add(new Models.Avtalsmodel
{
diarienummer = reader.GetInt64(0),
startdate = reader.GetDateTime(1),
enddate = reader.GetDateTime(2),
orgnummer = reader.GetString(3)
});
}
}
}
}
return View(lst);
}
private string connstr()
{
return "Host=localhost;Username=postgres;Database=mydb";
}
}
} | b38f05e62524c6e3b748a3fa0a9f69c329f30156 | [
"C#",
"SQL"
] | 2 | SQL | arvidsigvardsson/SBKAvtalskatalog | d217949062ef4c01a7d0bb0972f8037963a22e95 | 6cdd631eaa018df3d8fcc37c5b35640075ef0fe4 | |
refs/heads/master | <repo_name>webrenee7/col-activityshare<file_sep>/README.md
## 使用方法
- 加入以下代码
```html
<!--分享标题-->
<input class="actitle" type="hidden" value="分享标题" />
<!--分享描述-->
<input class="actsummary" type="hidden" value="分享描述!" />
<!--分享图标-->
<input class="actlink" type="hidden" value="http://image.kuaikuaidai.com/h5/static/images/lendimgwx.png" />
<!--分享链接地址-->
<input class="linkpage" type="hidden" value="" />
<!--以下隐藏域的值都是从后台代入的-->
<input id="appId" name="appId" type="hidden" value="${appId}"/>
<input id="timestamp" name="timestamp" type="hidden" value="${timestamp}"/>
<input id="nonceStr" name="nonceStr" type="hidden" value="${nonceStr}"/>
<input id="signature" name="signature" type="hidden" value="${signature}"/>
```
- 引入js
```javascript
<script src="../projectusual/static/js/activityshare.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script type="text/javascript" src="http://qzonestyle.gtimg.cn/qzone/qzact/common/share/share.js"></script>
```
## 微信分享敏感词汇
目前发现的:
红包、现金、现金红包、福利
之后再做补充
<file_sep>/js/activityshare.js
$(document).ready(function() {
var actitle = $(".actitle").val();
var actsummary = $(".actsummary").val();
var actlink = $(".actlink").val();
var linkpage = $(".linkpage").val();
var appId = $("#appId").val();
var timestamp = $("#timestamp").val();
var nonceStr = $("#nonceStr").val();
var signature = $("#signature").val();
wx.config({
debug: false,
appId: appId,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature,
jsApiList: ["onMenuShareTimeline", "onMenuShareAppMessage", "onMenuShareQQ", "onMenuShareWeibo", "onMenuShareQZone"]
});
wx.ready(function() {
wx.onMenuShareTimeline({
title: actitle,
link: linkpage,
imgUrl: actlink,
success: function() {},
cancel: function() {}
});
wx.onMenuShareAppMessage({
title: actitle,
desc: actsummary,
link: linkpage,
imgUrl: actlink,
type: "",
dataUrl: "",
success: function() {},
cancel: function() {}
});
wx.onMenuShareQQ({
title: actitle,
desc: actsummary,
link: linkpage,
imgUrl: actlink,
success: function() {},
cancel: function() {}
});
wx.onMenuShareWeibo({
title: actitle,
desc: actsummary,
link: linkpage,
imgUrl: actlink,
success: function() {},
cancel: function() {}
});
wx.onMenuShareQZone({
title: actitle,
desc: actsummary,
link: linkpage,
imgUrl: actlink,
success: function() {},
cancel: function() {}
})
});
wx.error(function(res) {});
setShareInfo({
title: actitle,
summary: actsummary,
pic: actlink,
url: linkpage,
WXconfig: {
swapTitleInWX: true,
appId: appId,
timestamp: timestamp,
nonceStr: nonceStr,
signature: signature
}
});
});
| 44e15c7583edf7d5d9e9a5475accd7fca9f52c67 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | webrenee7/col-activityshare | a77ed338718ccee75a991c341a3fbbe79044a221 | 409fa3a96ee1dd9d9c4fe3022f79d2e9641102f7 | |
refs/heads/master | <repo_name>khang1995/Ass_INF205<file_sep>/js/history.js
if (sessionStorage.clickcount==1) {
$('#thunhapactive').attr('class','active');
$('#chitieuactive').attr('class','');
$('#chuyenactive').attr('class','');
$('#tab_content2').attr('class','tab-pane active in fade');
$('#tab_content1').attr('class','tab-pane fade');
$('#tab_content3').attr('class','tab-pane fade');
}else if (sessionStorage.clickcount==2) {
$('#thunhapactive').attr('class','');
$('#chitieuactive').attr('class','');
$('#chuyenactive').attr('class','active');
$('#tab_content1').attr('class','tab-pane fade');
$('#tab_content2').attr('class','tab-pane fade');
$('#tab_content3').attr('class','tab-pane active in fade');
}
sessionStorage.IsLogin = 1;
var magd;
var taikhoanbandau;
var key;
var sothebandau;
var sothe=[];
var k=0,n=0,l=0;
var sotienbandau=0;
var sotienmathientai=0,sotientietkiemhientai=0;
var ref=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/khoanchi').orderByChild('ngaythang');
var ref1=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/khoanthu').orderByChild('ngaythang');
var datatable,datatable1,datatable2;
var ref_lichsu=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat');
var ref_lichsu1=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard');
var ref_lichsu2=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutietkiem');
var reftienmat=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/tienmat');
var reftietkiem=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/tientietkiem');
var refkhoanchuyen=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/khoanchuyen');
reftienmat.on('value', function(snapshot) {
sotienmathientai= Number(snapshot.val());
});
reftietkiem.on('value', function(snapshot) {
sotientietkiemhientai= Number(snapshot.val());
});
var lichsudata=[],lichsudata1=[],lichsudata2=[];
ref_lichsu.on("value", function(snapshot, prevChildKey) {
lichsudata=[];
snapshot.forEach(function(childSnapshot) {
lichsudata.push({magd:childSnapshot.val().magd,sotien:childSnapshot.val().sotien,key:childSnapshot.key,sodu:childSnapshot.val().sodu,ngaythang:childSnapshot.val().ngaythang,trangthai:childSnapshot.val().trangthai});
});
});
ref_lichsu1.on("value", function(snapshot, prevChildKey) {
lichsudata1=[];
snapshot.forEach(function(childSnapshot) {
lichsudata1.push({magd:childSnapshot.val().magd,sotien:childSnapshot.val().sotien,key:childSnapshot.key,sodu:childSnapshot.val().sodu,sothe:childSnapshot.val().sothe,ngaythang:childSnapshot.val().ngaythang,trangthai:childSnapshot.val().trangthai});
});
});
ref_lichsu2.on("value", function(snapshot, prevChildKey) {
lichsudata2=[];
snapshot.forEach(function(childSnapshot) {
lichsudata2.push({magd:childSnapshot.val().magd,loaichuyen:childSnapshot.val().loaichuyen,sotien:childSnapshot.val().sotien,key:childSnapshot.key,sodu:childSnapshot.val().sodu,sothe:childSnapshot.val().sothe,ngaythang:childSnapshot.val().ngaythang});
});
});
var chedochuyen,opttm,opttd,opttk;
var refdanhsachthe=firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/danhsachthe');
refdanhsachthe.on('value', function(snapshot) {
if(snapshot.val()==null){
$('#divthe').html('Bạn không có thẻ nào');
$('#chonhide').hide();
dkchonhide=false;
}else{
sothe=[];
$('#divthe').html('');
dem=0;
chedochuyen='';
opttm='';
opttd='';
opttk='';
$(".chedochuyen").html('');
}
snapshot.forEach(function(childSnapshot) {
sothe.push({sothe:childSnapshot.val().sothe,idthe:"the"+dem,sotien:childSnapshot.val().sotien,tenthe:childSnapshot.val().tenthe,key:childSnapshot.key});
if(dem==0)
$('#divthe').append('<label style="width: 100%"><input id="the'+dem+'" type="radio" checked="checked" name="chonthe" value="'+ childSnapshot.val().sothe +'"><b style="margin-left: 15px">'+childSnapshot.val().tenthe+' ('+ childSnapshot.val().sothe +')</b></label>');
else
$('#divthe').append('<label style="width: 100%"><input id="the'+dem+'" type="radio" name="chonthe" value="'+ childSnapshot.val().sothe +'"><b style="margin-left: 15px">'+childSnapshot.val().tenthe+' ('+ childSnapshot.val().sothe +')</b></label>');
dem++;
opttm += '<option data-chedochuyen="Tiền mặt -> Thẻ" data-sothe="'+childSnapshot.val().sothe+'" data-key="'+childSnapshot.key+'" data-tenthe="'+childSnapshot.val().tenthe+'" data-sotien="'+childSnapshot.val().sotien+'" >Tiền mặt -> Thẻ('+childSnapshot.val().tenthe+')</option>';
opttk += '<option data-chedochuyen="Tiền tiết kiệm -> Thẻ" data-sothe="'+childSnapshot.val().sothe+'" data-key="'+childSnapshot.key+'" data-tenthe="'+childSnapshot.val().tenthe+'" data-sotien="'+childSnapshot.val().sotien+'">Tiền tiết kiệm -> Thẻ('+childSnapshot.val().tenthe+')</option>';
opttd += '<option data-chedochuyen="Thẻ -> Tiền mặt" data-sothe="'+childSnapshot.val().sothe+'" data-key="'+childSnapshot.key+'" data-tenthe="'+childSnapshot.val().tenthe+'" data-sotien="'+childSnapshot.val().sotien+'">Thẻ('+childSnapshot.val().tenthe+') -> Tiền mặt</option><option data-chedochuyen="Thẻ -> Tiền tiết kiệm" data-sothe="'+childSnapshot.val().sothe+'" data-key="'+childSnapshot.key+'" data-tenthe="'+childSnapshot.val().tenthe+'" data-sotien="'+childSnapshot.val().sotien+'">Thẻ('+childSnapshot.val().tenthe+') -> Tiền tiết kiệm</option>';
});
chedochuyen='<select><option disabled selected value="default"> -- Chọn chế độ -- </option><optgroup label="Tiền mặt"><option data-chedochuyen="Tiền mặt -> Tiền tiết kiệm">Tiền mặt -> Tiền tiết kiệm</option>'+opttm+'</optgroup><optgroup label="Tín dụng">'+opttd+'</optgroup><optgroup label="Tiền tiết kiệm"> <option data-chedochuyen="Tiền tiết kiệm -> Tiền mặt">Tiền tiết kiệm -> Tiền mặt</option>'+opttk+'</optgroup></select>';
$(".chedochuyen").append(chedochuyen);
$('select option:not(:selected)');
$('select').change(function(){
chedo=$(this).find(':selected').data('chedochuyen');
sothechuyen=$(this).find(':selected').data('sothe');
isnull=true;
if(sothechuyen!=null){
isnull=false;
sotienchuyen= $(this).find(':selected').data('sotien');
tenthechuyen=$(this).find(':selected').data('tenthe');
keychuyen=$(this).find(':selected').data('key');
}
});
});
$(document).ready(function() {
NProgress.start();
//Set name
$('.profilename').html(localStorage.getItem("name"));
$('#left-col-name').html(localStorage.getItem("name"));
//Load data
ref.on("value", function(snapshot, prevChildKey) {
var data=[];
snapshot.forEach(function(childSnapshot) {
tongtien=childSnapshot.val().sotien;
if (tongtien.toString().length==4){
tongtien=tongtien.toString().substr(0,1)+"."+tongtien.toString().substr(1,3);
}else if (tongtien.toString().length==5){
tongtien=tongtien.toString().substr(0,2)+"."+tongtien.toString().substr(2,4);
}else if (tongtien.toString().length==6){
tongtien=tongtien.toString().substr(0,3)+"."+tongtien.toString().substr(3,5);
}else if (tongtien.toString().length==7){
tongtien=tongtien.toString().substr(0,1)+"."+tongtien.toString().substr(1,3)+"."+tongtien.toString().substr(4,6);
}else if (tongtien.toString().length==8){
tongtien=tongtien.toString().substr(0,2)+"."+tongtien.toString().substr(2,3)+"."+tongtien.toString().substr(5,7);
}else if (tongtien.toString().length==9){
tongtien=tongtien.toString().substr(0,3)+"."+tongtien.toString().substr(3,3)+"."+tongtien.toString().substr(6,8);
}
var ngay=childSnapshot.val().ngaythang.split(' ');
var date= ngay[0].split('-');
var format=date[2]+'-'+date[1]+'-'+date[0];
var stringngaythang="<span>"+format+"</span>"+childSnapshot.val().ngaythang;
var hanhdong='<a href="#" data-sothe="'+childSnapshot.val().sothe+'" data-magd="'+childSnapshot.val().magd+'" data-st="'+childSnapshot.val().sotien+'" data-sotien="'+tongtien+'" data-loaichitieu="'+childSnapshot.val().loaichitieu+'" data-taikhoan="'+childSnapshot.val().taikhoan+'" data-key="'+childSnapshot.key+'" data-mota="'+childSnapshot.val().mota+'" data-ngaythang="'+childSnapshot.val().ngaythang+'" class="openModal" data-toggle="modal" data-target="#myModal"><i class="fa fa-pencil-square-o"></i></a><a href="#" data-mota="'+childSnapshot.val().mota+'" data-magd="'+childSnapshot.val().magd+'" data-sothe="'+childSnapshot.val().sothe+'" data-sotien="'+tongtien+'" class="openModal1" data-toggle="modal" data-target="#myModal1" data-st="'+childSnapshot.val().sotien+'" data-taikhoan="'+childSnapshot.val().taikhoan+'" data-key="'+childSnapshot.key+'"><i class="fa fa-times" style="padding-left:10px"></i></a>';
if(childSnapshot.val().taikhoan == "Card"){
for (var i = 0; i < sothe.length; i++) {
if(childSnapshot.val().sothe==sothe[i].sothe){
data.push({'loaichitieu':childSnapshot.val().loaichitieu,'tongtien':tongtien,'ngaythang':stringngaythang,'mota':childSnapshot.val().mota,'taikhoan':childSnapshot.val().taikhoan+" ("+sothe[i].tenthe+")",'hanhdong':hanhdong});
}
}
}
else
data.push({'loaichitieu':childSnapshot.val().loaichitieu,'tongtien':tongtien,'ngaythang':stringngaythang,'mota':childSnapshot.val().mota,'taikhoan':childSnapshot.val().taikhoan,'hanhdong':hanhdong});
});
if(k==0){
k=1;
datatable=$('.datatable').DataTable({
data:data,
columns : [
{ 'data' : 'loaichitieu'},
{ 'data' : 'taikhoan'},
{ 'data' : 'tongtien'},
{ 'data' : 'ngaythang'},
{ 'data' : 'mota'},
{ 'data' : 'hanhdong'},
],
'order': [[ 3, 'desc' ]]
});
}else
datatable.clear().rows.add(data).draw(false);
NProgress.done();
});
ref1.on("value", function(snapshot, prevChildKey) {
var data=[];
snapshot.forEach(function(childSnapshot) {
tongtien=childSnapshot.val().sotien;
if (tongtien.toString().length==4){
tongtien=tongtien.toString().substr(0,1)+"."+tongtien.toString().substr(1,3);
}else if (tongtien.toString().length==5){
tongtien=tongtien.toString().substr(0,2)+"."+tongtien.toString().substr(2,4);
}else if (tongtien.toString().length==6){
tongtien=tongtien.toString().substr(0,3)+"."+tongtien.toString().substr(3,5);
}else if (tongtien.toString().length==7){
tongtien=tongtien.toString().substr(0,1)+"."+tongtien.toString().substr(1,3)+"."+tongtien.toString().substr(4,6);
}else if (tongtien.toString().length==8){
tongtien=tongtien.toString().substr(0,2)+"."+tongtien.toString().substr(2,3)+"."+tongtien.toString().substr(5,7);
}else if (tongtien.toString().length==9){
tongtien=tongtien.toString().substr(0,3)+"."+tongtien.toString().substr(3,3)+"."+tongtien.toString().substr(6,8);
}
var ngay=childSnapshot.val().ngaythang.split(' ');
var date= ngay[0].split('-');
var format=date[2]+'-'+date[1]+'-'+date[0];
var stringngaythang="<span>"+format+"</span>"+childSnapshot.val().ngaythang;
var hanhdong='<a href="#" data-magd="'+childSnapshot.val().magd+'" data-st="'+childSnapshot.val().sotien+'" data-sotien="'+tongtien+'" data-loaithunhap="'+childSnapshot.val().loaithunhap+'" data-key="'+childSnapshot.key+'" data-taikhoan="'+childSnapshot.val().taikhoan+'" data-mota="'+childSnapshot.val().mota+'" data-sothe="'+childSnapshot.val().sothe+'" data-ngaythang="'+childSnapshot.val().ngaythang+'" class="openModal2" data-toggle="modal" data-target="#myModal2"><i class="fa fa-pencil-square-o"></i></a><a href="#" data-mota="'+childSnapshot.val().mota+'" data-sotien="'+tongtien+'" data-st="'+childSnapshot.val().sotien+'" data-magd="'+childSnapshot.val().magd+'" data-sothe="'+childSnapshot.val().sothe+'" class="openModal3" data-toggle="modal" data-target="#myModal3" data-st="'+childSnapshot.val().sotien+'" data-taikhoan="'+childSnapshot.val().taikhoan+'" data-key="'+childSnapshot.key+'"><i class="fa fa-times" style="padding-left:20px"></i></a>';
if(childSnapshot.val().taikhoan == "Card"){
for (var i = 0; i < sothe.length; i++) {
if(childSnapshot.val().sothe==sothe[i].sothe){
data.push({'loaithunhap':childSnapshot.val().loaithunhap,'tongtien':tongtien,'ngaythang':stringngaythang,'mota':childSnapshot.val().mota,'taikhoan':childSnapshot.val().taikhoan+" ("+sothe[i].tenthe+")",'hanhdong':hanhdong});
}
}
}
else
data.push({'loaithunhap':childSnapshot.val().loaithunhap,'tongtien':tongtien,'ngaythang':stringngaythang,'mota':childSnapshot.val().mota,'taikhoan':childSnapshot.val().taikhoan,'hanhdong':hanhdong});
});
if(n==0){
n=1;
datatable1= $('.datatable1').DataTable({
data:data,
columns : [
{ 'data' : 'loaithunhap'},
{ 'data' : 'taikhoan'},
{ 'data' : 'tongtien'},
{ 'data' : 'ngaythang'},
{ 'data' : 'mota'},
{ 'data' : 'hanhdong'},
],
order: [[ 3, 'desc' ]],
});
}else{datatable1.clear().rows.add(data).draw(false);}
});
refkhoanchuyen.on('value', function(snapshot) {
var data=[];
snapshot.forEach(function(childSnapshot) {
tongtien=childSnapshot.val().sotien;
if (tongtien.toString().length==4){
tongtien=tongtien.toString().substr(0,1)+"."+tongtien.toString().substr(1,3);
}else if (tongtien.toString().length==5){
tongtien=tongtien.toString().substr(0,2)+"."+tongtien.toString().substr(2,4);
}else if (tongtien.toString().length==6){
tongtien=tongtien.toString().substr(0,3)+"."+tongtien.toString().substr(3,5);
}else if (tongtien.toString().length==7){
tongtien=tongtien.toString().substr(0,1)+"."+tongtien.toString().substr(1,3)+"."+tongtien.toString().substr(4,6);
}else if (tongtien.toString().length==8){
tongtien=tongtien.toString().substr(0,2)+"."+tongtien.toString().substr(2,3)+"."+tongtien.toString().substr(5,7);
}else if (tongtien.toString().length==9){
tongtien=tongtien.toString().substr(0,3)+"."+tongtien.toString().substr(3,3)+"."+tongtien.toString().substr(6,8);
}
sodu=childSnapshot.val().sodu;
if (sodu.toString().length==4){
sodu=sodu.toString().substr(0,1)+"."+sodu.toString().substr(1,3);
}else if (sodu.toString().length==5){
sodu=sodu.toString().substr(0,2)+"."+sodu.toString().substr(2,4);
}else if (sodu.toString().length==6){
sodu=sodu.toString().substr(0,3)+"."+sodu.toString().substr(3,5);
}else if (sodu.toString().length==7){
sodu=sodu.toString().substr(0,1)+"."+sodu.toString().substr(1,3)+"."+sodu.toString().substr(4,6);
}else if (sodu.toString().length==8){
sodu=sodu.toString().substr(0,2)+"."+sodu.toString().substr(2,3)+"."+sodu.toString().substr(5,7);
}else if (sodu.toString().length==9){
sodu=sodu.toString().substr(0,3)+"."+sodu.toString().substr(3,3)+"."+sodu.toString().substr(6,8);
}
var ngay=childSnapshot.val().ngaythang.split(' ');
var date= ngay[0].split('-');
var format=date[2]+'-'+date[1]+'-'+date[0];
var stringngaythang="<span>"+format+"</span>"+childSnapshot.val().ngaythang;
var hanhdong='<a href="#" class="openModal6" data-toggle="modal" data-target="#myModal6" data-chedo="'+childSnapshot.val().loaichuyen+'" data-sotien="'+childSnapshot.val().sotien+'" data-sothe="'+childSnapshot.val().sothe+'" data-key="'+childSnapshot.key+'" data-magd="'+childSnapshot.val().magd+'"><i class="fa fa-times"></i></a>';
if(childSnapshot.val().sothe != null){
for (var i = 0; i < sothe.length; i++) {
if(childSnapshot.val().sothe == sothe[i].sothe){
if(childSnapshot.val().loaichuyen=="Thẻ -> Tiền tiết kiệm"){
split=childSnapshot.val().loaichuyen.toString().split('-');
data.push({'loaichuyen':split[0]+"("+sothe[i].tenthe+") -"+split[1],'tongtien':tongtien,'ngaythang':stringngaythang,'sodu':sodu,'hanhdong':hanhdong});
}else if(childSnapshot.val().loaichuyen=="Thẻ -> Tiền mặt"){
split=childSnapshot.val().loaichuyen.toString().split('-');
data.push({'loaichuyen':split[0]+"("+sothe[i].tenthe+") -"+split[1],'tongtien':tongtien,'ngaythang':stringngaythang,'sodu':sodu,'hanhdong':hanhdong});
}else
data.push({'loaichuyen':childSnapshot.val().loaichuyen+"("+sothe[i].tenthe+")",'tongtien':tongtien,'ngaythang':stringngaythang,'sodu':sodu,'hanhdong':hanhdong});
}
}
}else
data.push({'loaichuyen':childSnapshot.val().loaichuyen,'tongtien':tongtien,'ngaythang':stringngaythang,'sodu':sodu,'hanhdong':hanhdong});
});
if(l==0){
l=1;
datatable2= $('.datatable2').DataTable({
data:data,
columns : [
{ 'data' : 'loaichuyen'},
{ 'data' : 'tongtien'},
{ 'data' : 'sodu'},
{ 'data' : 'ngaythang'},
{ 'data' : 'hanhdong'},
],
order: [[ 3, 'desc' ]],
});
}else{datatable2.clear().rows.add(data).draw(false);}
});
$(document).on("click", ".openModal", function () {
sothebandau=$(this).data('sothe');
if(sothe.length != 0){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==$(this).data('sothe'))
$('#'+sothe[i].idthe).prop('checked',true);
}
}
sotienbandau=$(this).data('st');
taikhoanbandau=$(this).data('taikhoan');
key= $(this).data('key');
magd=$(this).data('magd');
lstk= $(this).data('taikhoan');
$("#sotien").val( $(this).data('sotien') );
$("#mota").html( $(this).data("mota") );
$("#datetimepicker4").val( $(this).data('ngaythang') );
if($(this).data('taikhoan')=="Card"){
$('#card').prop('checked',true);
$('#tienmat1').attr('class','btn btn-primary fa fa-usd ');
$('#card1').attr('class','btn btn-danger fa fa-credit-card active');
}else{
$('#tienmat').prop('checked',true);
$('#tienmat1').trigger("click");
}
if($(this).data('loaichitieu')=="Đi chơi"){
$('#dichoi').prop('checked',true);
$('#dichoi1').trigger("click");
}else if($(this).data('loaichitieu')=="Đổ xăng"){
$('#doxang').prop('checked',true);
$('#doxang1').trigger("click");
} if($(this).data('loaichitieu')=="Mua đồ"){
$('#muado').prop('checked',true);
$('#muado1').trigger("click");
}else{
$('#' + $(this).data('loaichitieu') ).prop('checked',true);
$('#' + $(this).data('loaichitieu')+"1" ).trigger("click");
}
});
$("#quayvechontienmat").on("click",function(){
if(sothe.length != 0){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==sothebandau)
$('#'+sothe[i].idthe).prop('checked',true);
}
}
});
$(document).on("click", ".openModal1", function () {
key= $(this).data('key');
$("#deltien").html( $(this).data('sotien') );
$("#delmota").html( $(this).data("mota") );
magd=$(this).data('magd');
sothebandau=$(this).data('sothe');
sotienbandau=$(this).data('st');
lstk= $(this).data('taikhoan');
});
$(document).on("click", ".openModal2", function () {
sotienbandau=$(this).data('st');
magd=$(this).data('magd');
key= $(this).data('key');
taikhoanbandau=$(this).data('taikhoan');
sothebandau=$(this).data('sothe');
magd=$(this).data('magd');
if(sothe.length != 0){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==$(this).data('sothe'))
$('#'+sothe[i].idthe).prop('checked',true);
}
}
if($(this).data('taikhoan')=="Card"){
$('#card3').prop('checked',true);
$('#tienmat2').attr('class','btn btn-primary fa fa-usd ');
$('#card2').attr('class','btn btn-danger fa fa-credit-card active');
}else{
$('#tienmat3').prop('checked',true);
$('#tienmat2').trigger("click");
}
$("#sotien1").val( $(this).data('sotien') );
$("#motathu").html( $(this).data("mota") );
$("#datetimepicker5").val( $(this).data('ngaythang') );
if($(this).data('loaithunhap')=="Bán đồ"){
$('#bando').prop('checked',true);
$('#bando1').trigger("click");
}else if($(this).data('loaithunhap')=="Khác"){
$('#khacthu').prop('checked',true);
$('#khacthu1').trigger("click");
}else{
$('#luong').prop('checked',true);
$('#luong1').trigger("click");
}
});
$(document).on("click", ".openModal3", function () {
magd=$(this).data('magd');
key= $(this).data('key');
sothebandau=$(this).data('sothe');
sotienbandau=$(this).data('st');
taikhoanbandau= $(this).data('taikhoan');
$("#deltienthu").html( $(this).data('sotien') );
$("#delmotathu").html( $(this).data("mota") );
});
var chedochon,sothechuyen;
$(document).on("click", ".openModal6", function () {
chedo=$(this).data('chedo');
magd=$(this).data('magd');
key= $(this).data('key');
sotienbandau=$(this).data('sotien');
sothebandau=$(this).data('sothe');
$("#deltienthu").html( $(this).data('sotien') );
$("#delmotathu").html( $(this).data("mota") );
});
//logout
$('#logout').on('click',function(){
localStorage.removeItem("key");
localStorage.removeItem("name");
localStorage.removeItem("username");
localStorage.removeItem("password");
});
// Fill Nhập liệu chi tiêu
$('#mota').on('click',function(){
$('.err').html('');
});
$('#chitieu').on('click',function(){
$('.err').html('');
});
$('#sotien').on('click',function(){
$('.err').html('');
});
$('#sotien2').on('click',function(){
$('.err').html('');
});
$('#motathu').on('click',function(){
$('.err').html('');
});
$('#thunhap').on('click',function(){
$('.err').html('');
});
$('#sotien1').on('click',function(){
$('.err').html('');
});
$('#datetimepicker4').datetimepicker(
{format: 'DD-MM-YYYY HH:mm'}
);
$('#datetimepicker4').keydown(function(e){
if (e.which === 8)
return false;
});
$('#datetimepicker5').keydown(function(e){
if (e.which === 8)
return false;
});
$('#datetimepicker6').keydown(function(e){
if (e.which === 8)
return false;
});
$('#datetimepicker5').datetimepicker(
{format: 'DD-MM-YYYY HH:mm'}
);
$('#datetimepicker6').datetimepicker(
{format: 'DD-MM-YYYY HH:mm'}
);
$('#sotien1').keyup(function(event) {
$(this).val(
this.value.replace(text,"") + text
);
if (this.value.length==8){
$(this).val(
this.value.substr(0,1)+"."+this.value.substr(1,8)
);
}
else if (this.value.length==10){
$(this).val(
this.value.substr(0,1)+this.value.substring(2,3)+"."+this.value.substr(3,10)
);
}
else if (this.value.length==11){
$(this).val(
this.value.substr(0,2)+this.value.substring(3,4)+"."+this.value.substr(4,11)
);
}else if(this.value.length>11){
$(this).val("Số tiền quá lớn");
}
if(reg.test(this.value) || reg1.test(this.value)|| reg2.test(this.value)){
}else{
$(this).val("");
}
if(event.keyCode == 8) $(this).val("");
});
$("#sotien").click(function(){
document.getElementById('sotien').value="";
});
$('#sotien2').keyup(function(event) {
$(this).val(
this.value.replace(text,"") + text
);
if (this.value.length==8){
$(this).val(
this.value.substr(0,1)+"."+this.value.substr(1,8)
);
}
else if (this.value.length==10){
$(this).val(
this.value.substr(0,1)+this.value.substring(2,3)+"."+this.value.substr(3,10)
);
}
else if (this.value.length==11){
$(this).val(
this.value.substr(0,2)+this.value.substring(3,4)+"."+this.value.substr(4,11)
);
}else if(this.value.length>11){
$(this).val("Số tiền quá lớn");
}
if(reg.test(this.value) || reg1.test(this.value)|| reg2.test(this.value)){
}else{
$(this).val("");
}
if(event.keyCode == 8) $(this).val("");
});
$("#sotien2").click(function(){
document.getElementById('sotien2').value="";
});
$("#sotien1").click(function(){
document.getElementById('sotien1').value="";
});
var text= ".000";
var reg=/^([0-9])+\.([0-9])+\.([0-9])+$/;
var reg1=/^([0-9])+\.([0-9])+$/;
var reg3=/^([0-9])+\s([0-9])+\s+$/;
var reg4=/^([0-9])+\s+$/;
var reg6=/^([0-9])+\s([0-9])+$/;
var reg5=/^([0-9])+\s([0-9])+\s([0-9])+\s+$/;
var reg8=/^([0-9])+\s([0-9])+\s([0-9])+\s([0-9])+$/;
var reg7=/^([0-9])+\s([0-9])+\s([0-9])+$/;
var reg2=/^([0-9])+$/;
$('#sotien').keyup(function(event) {
$(this).val(
this.value.replace(text,"") + text
);
if (this.value.length==8){
$(this).val(
this.value.substr(0,1)+"."+this.value.substr(1,8)
);
}
else if (this.value.length==10){
$(this).val(
this.value.substr(0,1)+this.value.substring(2,3)+"."+this.value.substr(3,10)
);
}
else if (this.value.length==11){
$(this).val(
this.value.substr(0,2)+this.value.substring(3,4)+"."+this.value.substr(4,11)
);
}else if(this.value.length>11){
$(this).val("Số tiền quá lớn");
}
if(reg.test(this.value) || reg1.test(this.value)|| reg2.test(this.value)){
}else{
$(this).val("");
}
if(event.keyCode == 8) $(this).val("");
});
});
function confirmdel(){
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/khoanchi/'+key).remove();
$('#myModal1').modal('toggle');
if(lstk=="Card"){
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
for (var j = i+1; j < lichsudata1.length; j++) {
if(lichsudata1[j].sothe == $('input[name=chonthe]:checked').val()){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:+lichsudata1[j].sodu+Number(lichsudata1[i].sotien),
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[i].key).remove();
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == sothebandau){
var postData1 = {
sotien: sothe[i].sotien + sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
}
}else{
for (var i = 0; i < lichsudata.length; i++) {
if(lichsudata[i].magd==magd){
sotienmathientai += Number(lichsudata[i].sotien);
reftienmat.set(sotienmathientai);
for (var j = i+1; j < lichsudata.length; j++) {
var postData = {
sotien:lichsudata[j].sotien,
sodu:+lichsudata[j].sodu+Number(lichsudata[i].sotien),
ngaythang:lichsudata[j].ngaythang,
magd:lichsudata[j].magd,
trangthai:lichsudata[j].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[j].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[i].key).remove();
}
}
}
sessionStorage.clickcount=0;
}
function myclick(){
var sotien=$('#sotien').val();
if(sotien.length==5){
sotien=sotien.substr(0,1)+sotien.substr(2,5);
}else if(sotien.length==6){
sotien=sotien.substr(0,2)+sotien.substr(3,6);
}else if(sotien.length==7){
sotien=sotien.substr(0,3)+sotien.substr(4,7);
}else if(sotien.length==9){
sotien=sotien.substr(0,1)+sotien.substr(2,3)+sotien.substr(6,9);
}else if(sotien.length==10){
sotien=sotien.substr(0,2)+sotien.substr(3,3)+sotien.substr(7,10);
}else if(sotien.length==11){
sotien=sotien.substr(0,3)+sotien.substr(4,3)+sotien.substr(8,11);
}
if ($('input[name=chitieu]:checked').val() == null ||$('input[name=chitieu]:checked').val() =="") {
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng chọn loại chi tiêu</li</ul>');
return false;
}else if($('#sotien').val()==""){
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng nhập số tiền</li</ul>');
return false;
}else if($('#datetimepicker4').val()==""){
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng chọn ngày giờ</li</ul>');
return false;
}else if($('#mota').val()==""){
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng nhập mô tả</li</ul>');
return false;
}else{
if(taikhoanbandau != $('input[name=taikhoan]:checked').val() && taikhoanbandau == "Card"){
var postData = {
loaichitieu:$('input[name=chitieu]:checked','#chitieuform1').val(),
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
mota:$('#mota').val(),
taikhoan:$('input[name=taikhoan]:checked').val(),
magd:magd
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanchi/' + key] = postData;
firebase.database().ref().update(updates);
sotienmathientai -= +sotien;
reftienmat.set(sotienmathientai);
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
for (var j = i+1; j < lichsudata1.length; j++) {
var postData = {
sotien:lichsudata1[j].sotien,
sodu:+lichsudata1[j].sodu+Number(lichsudata1[i].sotien),
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[i].key).remove();
}
}
ref_lichsu.push().set({
trangthai:"Chi",
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
sodu:sotienmathientai,
magd:magd
});
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==sothebandau){
var postData1 = {
sotien:+sothe[i].sotien+ +sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else if(taikhoanbandau != $('input[name=taikhoan]:checked').val() && taikhoanbandau == "Tiền mặt"){
var postData = {
loaichitieu:$('input[name=chitieu]:checked','#chitieuform1').val(),
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
mota:$('#mota').val(),
taikhoan:$('input[name=taikhoan]:checked').val(),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanchi/' + key] = postData;
firebase.database().ref().update(updates);
sotienmathientai += + sotienbandau;
reftienmat.set(sotienmathientai);
for (var i = 0; i < lichsudata.length; i++) {
if(lichsudata[i].magd==magd){
for (var j = i+1; j < lichsudata.length; j++) {
var postData = {
sotien:lichsudata[j].sotien,
sodu:+lichsudata[j].sodu+Number(lichsudata[i].sotien),
ngaythang:lichsudata[j].ngaythang,
magd:lichsudata[j].magd,
trangthai:lichsudata[j].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[j].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[i].key).remove();
}
}
soducuathe=0;
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==$('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:+sothe[i].sotien - sotien,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
soducuathe=+sothe[i].sotien - sotien;
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
ref_lichsu1.push().set({
trangthai:"Chi",
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
sodu:soducuathe,
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
});
}else if(taikhoanbandau == $('input[name=taikhoan]:checked').val()){
if(lstk=="Card"){
var postData = {
loaichitieu:$('input[name=chitieu]:checked','#chitieuform1').val(),
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
mota:$('#mota').val(),
taikhoan:$('input[name=taikhoan]:checked').val(),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanchi/' + key] = postData;
firebase.database().ref().update(updates);
if(sothebandau != $('input[name=chonthe]:checked').val()){
sodubandau=0;
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
if(i==lichsudata1.length-1){
if(i>0){
for (var k = lichsudata1.length-1; k >= 0; k--) {
if(lichsudata1[k].sothe==$('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: +lichsudata1[k].sodu - Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
break;
}
}
}else{
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: +lichsudata1[i].sodu - Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}else{
if(i>0){
for (var j = i-1; j >=0; j--) {
if(lichsudata1[j].sothe == $('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: +lichsudata1[j].sodu - Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
sodubandau=+lichsudata1[j].sodu - Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
break;
}
if(j==0){
for(var k=0;k<sothe.length;k++){
if(sothe[k].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau=0;
for(var l=i+1;l<lichsudata1.length;l++){
if(lichsudata1[l].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau+= +lichsudata1[l].sotien;
}
}
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: (+sothe[k].sotien +tongsodubandau) - Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
sodubandau=(+sothe[k].sotien +tongsodubandau) - Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
}
}else{
for(var k=0;k<sothe.length;k++){
if(sothe[k].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau=0;
for(var l=i+1;l<lichsudata1.length;l++){
if(lichsudata1[l].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau+= +lichsudata1[l].sotien;
}
}
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: (+sothe[k].sotien +tongsodubandau) - Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
sodubandau=(+sothe[k].sotien +tongsodubandau) - Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
for (var j = i+1; j < lichsudata1.length; j++) {
if(lichsudata1[j].sothe==sothebandau){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:+lichsudata1[j].sodu +sotienbandau,
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}else if(lichsudata1[j].sothe==$('input[name=chonthe]:checked').val()){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:sodubandau - +lichsudata1[j].sotien,
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
sodubandau=sodubandau - +lichsudata1[j].sotien;
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
}
}
}
}
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == $('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:+sothe[i].sotien - sotien,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==sothebandau){
var postData1 = {
sotien:+sothe[i].sotien + sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else{
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==$('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:(sothe[i].sotien +sotienbandau) - sotien,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: (+lichsudata1[i].sodu +sotienbandau) - Number(sotien),
magd:magd,
sothe:sothebandau
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
for (var j = i+1; j < lichsudata1.length; j++) {
if(lichsudata1[j].sothe==$('input[name=chonthe]:checked').val()){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:(lichsudata1[j].sodu +sotienbandau) - sotien,
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
}
}
}
}
}else{
var postData = {
loaichitieu:$('input[name=chitieu]:checked','#chitieuform1').val(),
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
mota:$('#mota').val(),
taikhoan:$('input[name=taikhoan]:checked').val(),
magd:magd
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanchi/' + key] = postData;
firebase.database().ref().update(updates);
for (var i = 0; i < lichsudata.length; i++) {
if(lichsudata[i].magd == magd){
sotienmathientai = (sotienmathientai+sotienbandau)-sotien;
reftienmat.set(sotienmathientai);
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker4').val(),
trangthai: "Chi",
sodu: (lichsudata[i].sodu + Number(lichsudata[i].sotien))-sotien,
magd:magd
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[i].key] = postData1;
firebase.database().ref().update(updates1);
for (var j = i+1; j < lichsudata.length; j++) {
var postData = {
sotien:lichsudata[j].sotien,
sodu: (+lichsudata[j].sodu+sotienbandau)-sotien,
ngaythang:lichsudata[j].ngaythang,
magd:lichsudata[j].magd,
trangthai:lichsudata[j].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[j].key] = postData;
firebase.database().ref().update(updates);
}
}
}
}
}
$('#myModal').modal('toggle');
sessionStorage.clickcount=0;
}
}
$("#themthu").on("click",function(){
var sotien=$('#sotien1').val();
if(sotien.length==5){
sotien=sotien.substr(0,1)+sotien.substr(2,5);
}else if(sotien.length==6){
sotien=sotien.substr(0,2)+sotien.substr(3,6);
}else if(sotien.length==7){
sotien=sotien.substr(0,3)+sotien.substr(4,7);
}else if(sotien.length==9){
sotien=sotien.substr(0,1)+sotien.substr(2,3)+sotien.substr(6,9);
}else if(sotien.length==10){
sotien=sotien.substr(0,2)+sotien.substr(3,3)+sotien.substr(7,10);
}else if(sotien.length==11){
sotien=sotien.substr(0,3)+sotien.substr(4,3)+sotien.substr(8,11);
}
if ($('input[name=khoanthu]:checked').val() == null ||$('input[name=khoanthu]:checked').val() =="") {
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng chọn loại thu nhập</li</ul>');
return false;
}else if(sotien==""){
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng nhập số tiền</li</ul>');
return false;
}else if($('#datetimepicker5').val()==""){
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng chọn ngày giờ</li</ul>');
return false;
}else if($('#motathu').val()==""){
$('.err').html('<ul><li style="color:red;font-size:16px">Vui lòng nhập mô tả</li</ul>');
return false;
}else{
if(taikhoanbandau != $('input[name=taikhoan1]:checked').val() && taikhoanbandau == "Card"){
var postData = {
loaithunhap:$('input[name=khoanthu]:checked').val(),
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
mota:$('#motathu').val(),
magd:magd,
taikhoan:$('input[name=taikhoan1]:checked').val()
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanthu/' + key] = postData;
firebase.database().ref().update(updates);
reftienmat.set(sotienmathientai+Number(sotien));
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
for (var j = i+1; j < lichsudata1.length; j++) {
var postData = {
sotien:lichsudata1[j].sotien,
sodu:+lichsudata1[j].sodu - Number(lichsudata1[i].sotien),
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[i].key).remove();
}
}
ref_lichsu.push().set({
trangthai:"Thu",
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
sodu:sotienmathientai,
magd:magd
});
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==sothebandau){
var postData1 = {
sotien:sothe[i].sotien - sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else if(taikhoanbandau != $('input[name=taikhoan1]:checked').val() && taikhoanbandau == "Tiền mặt"){
var postData = {
loaithunhap:$('input[name=khoanthu]:checked').val(),
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
mota:$('#motathu').val(),
sothe:$('input[name=chonthe]:checked').val(),
magd:magd,
taikhoan:$('input[name=taikhoan1]:checked').val()
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanthu/' + key] = postData;
firebase.database().ref().update(updates);
sotienmathientai -= sotienbandau;
reftienmat.set(sotienmathientai);
for (var i = 0; i < lichsudata.length; i++) {
if(lichsudata[i].magd==magd){
for (var j = i+1; j < lichsudata.length; j++) {
var postData = {
sotien:lichsudata[j].sotien,
sodu:+lichsudata[j].sodu - Number(lichsudata[i].sotien),
ngaythang:lichsudata[j].ngaythang,
magd:lichsudata[j].magd,
trangthai:lichsudata[j].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[j].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[i].key).remove();
}
}
soducuathe=0;
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==$('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:+sothe[i].sotien + Number(sotien),
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
soducuathe=+sothe[i].sotien + Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
ref_lichsu1.push().set({
trangthai:"Thu",
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
sodu:soducuathe,
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
});
}else if(taikhoanbandau == $('input[name=taikhoan1]:checked').val()){
if(taikhoanbandau=="Card"){
var postData = {
loaithunhap:$('input[name=khoanthu]:checked').val(),
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
mota:$('#motathu').val(),
sothe:$('input[name=chonthe]:checked').val(),
magd:magd,
taikhoan:$('input[name=taikhoan1]:checked').val()
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanthu/' + key] = postData;
firebase.database().ref().update(updates);
if(sothebandau != $('input[name=chonthe]:checked').val()){
sodubandau=0;
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
if(i==lichsudata1.length-1){
if(i>0){
for (var k = lichsudata1.length-1; k >= 0; k--) {
if(lichsudata1[k].sothe==$('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: +lichsudata1[k].sodu + Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
break;
}
}
}else{
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: +lichsudata1[i].sodu + Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}else{
if(i>0){
for (var j = i-1; j >=0; j--) {
if(lichsudata1[j].sothe == $('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: +lichsudata1[j].sodu + Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
sodubandau=+lichsudata1[j].sodu + Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
break;
}else if(j==0){
for(var k=0;k<sothe.length;k++){
if(sothe[k].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau=0;
for(var l=i+1;l<lichsudata1.length;l++){
if(lichsudata1[l].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau-= +lichsudata1[l].sotien;
}
}
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: (+sothe[k].sotien -tongsodubandau) + Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
sodubandau=(+sothe[k].sotien -tongsodubandau) + Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
}
}else{
for(var k=0;k<sothe.length;k++){
if(sothe[k].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau=0;
for(var l=i+1;l<lichsudata1.length;l++){
if(lichsudata1[l].sothe==$('input[name=chonthe]:checked').val()){
tongsodubandau-= +lichsudata1[l].sotien;
}
}
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: (+sothe[k].sotien -tongsodubandau) + Number(sotien),
magd:magd,
sothe:$('input[name=chonthe]:checked').val()
};
sodubandau=(+sothe[k].sotien -tongsodubandau) + Number(sotien);
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
for (var j = i+1; j < lichsudata1.length; j++) {
if(lichsudata1[j].sothe==sothebandau){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:+lichsudata1[j].sodu - sotienbandau,
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}else if(lichsudata1[j].sothe==$('input[name=chonthe]:checked').val()){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:sodubandau + +lichsudata1[j].sotien,
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
sodubandau=sodubandau + +lichsudata1[j].sotien;
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
}
}
}
}
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == $('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:+sothe[i].sotien + Number(sotien),
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==sothebandau){
var postData1 = {
sotien:+sothe[i].sotien - sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else{
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe==$('input[name=chonthe]:checked').val()){
var postData1 = {
sotien:(sothe[i].sotien - sotienbandau) + Number(sotien),
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: (+lichsudata1[i].sodu -sotienbandau) + Number(sotien),
magd:magd,
sothe:sothebandau
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[i].key] = postData1;
firebase.database().ref().update(updates1);
for (var j = i+1; j < lichsudata1.length; j++) {
if(lichsudata1[j].sothe==sothebandau){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:(lichsudata1[j].sodu -sotienbandau) + Number(sotien),
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
}
}
}
}
}else{
var postData = {
loaithunhap:$('input[name=khoanthu]:checked').val(),
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
mota:$('#motathu').val(),
magd:magd,
taikhoan:$('input[name=taikhoan1]:checked').val()
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/khoanthu/' + key] = postData;
firebase.database().ref().update(updates);
for (var i = 0; i < lichsudata.length; i++) {
if(lichsudata[i].magd == magd){
sotienmathientai = (sotienmathientai-sotienbandau)+Number(sotien);
reftienmat.set(sotienmathientai);
var postData1 = {
sotien:sotien,
ngaythang:$('#datetimepicker5').val(),
trangthai: "Thu",
sodu: (lichsudata[i].sodu - Number(lichsudata[i].sotien))+ Number(sotien),
magd:magd
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[i].key] = postData1;
firebase.database().ref().update(updates1);
for (var j = i+1; j < lichsudata.length; j++) {
var postData = {
sotien:lichsudata[j].sotien,
sodu: (+lichsudata[j].sodu-sotienbandau)+Number(sotien),
ngaythang:lichsudata[j].ngaythang,
magd:lichsudata[j].magd,
trangthai:lichsudata[j].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[j].key] = postData;
firebase.database().ref().update(updates);
}
}
}
}
}
$('#myModal2').modal('toggle');
sessionStorage.clickcount = 1;
}
});
function confirmdel1(){
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/khoanthu/'+key).remove();
$('#myModal3').modal('toggle');
if(taikhoanbandau=="Card"){
for (var i = 0; i < lichsudata1.length; i++) {
if(lichsudata1[i].magd==magd){
for (var j = i+1; j < lichsudata1.length; j++) {
if(lichsudata1[j].sothe == $('input[name=chonthe]:checked').val()){
var postData = {
sotien:lichsudata1[j].sotien,
sodu:+lichsudata1[j].sodu - Number(lichsudata1[i].sotien),
ngaythang:lichsudata1[j].ngaythang,
magd:lichsudata1[j].magd,
trangthai:lichsudata1[j].trangthai,
sothe:lichsudata1[j].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[j].key] = postData;
firebase.database().ref().update(updates);
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[i].key).remove();
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == sothebandau){
var postData1 = {
sotien: sothe[i].sotien - sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
}
}else{
for (var i = 0; i < lichsudata.length; i++) {
if(lichsudata[i].magd==magd){
sotienmathientai -= Number(lichsudata[i].sotien);
reftienmat.set(sotienmathientai);
for (var j = i+1; j < lichsudata.length; j++) {
var postData = {
sotien:lichsudata[j].sotien,
sodu:+lichsudata[j].sodu - Number(lichsudata[i].sotien),
ngaythang:lichsudata[j].ngaythang,
magd:lichsudata[j].magd,
trangthai:lichsudata[j].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[j].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[i].key).remove();
}
}
}
sessionStorage.clickcount = 1;
}
function confirmdel2(){
if(chedo=="Tiền mặt -> Thẻ"){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == sothebandau){
reftienmat.set(sotienmathientai + Number(sotienbandau));
for (var j = 0; j < lichsudata.length; j++) {
if(lichsudata[j].magd == magd){
for (var k = j+1; k < lichsudata.length; k++) {
var postData = {
sotien:lichsudata[k].sotien,
sodu:+lichsudata[k].sodu + Number(lichsudata[j].sotien),
ngaythang:lichsudata[k].ngaythang,
magd:lichsudata[k].magd,
trangthai:lichsudata[k].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[j].key).remove();
}
}
for (var j = 0; j < lichsudata1.length; j++) {
if(lichsudata1[j].magd == magd){
for (var k = j+1; k < lichsudata1.length; k++) {
if(lichsudata1[k].sothe==sothebandau){
var postData = {
sotien:lichsudata1[k].sotien,
sodu:lichsudata1[k].sodu - Number(lichsudata1[j].sotien),
ngaythang:lichsudata1[k].ngaythang,
magd:lichsudata1[k].magd,
trangthai:lichsudata1[k].trangthai,
sothe:lichsudata1[k].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[k].key] = postData;
firebase.database().ref().update(updates);
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[j].key).remove();
}
}
var postData1 = {
sotien: sothe[i].sotien - sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else if(chedo=="Tiền mặt -> Tiền tiết kiệm"){
reftienmat.set(sotienmathientai + Number(sotienbandau));
reftietkiem.set(sotientietkiemhientai - Number(sotienbandau));
for (var j = 0; j < lichsudata.length; j++) {
if(lichsudata[j].magd == magd){
for (var k = j+1; k < lichsudata.length; k++) {
var postData = {
sotien:lichsudata[k].sotien,
sodu:+lichsudata[k].sodu + Number(lichsudata[j].sotien),
ngaythang:lichsudata[k].ngaythang,
magd:lichsudata[k].magd,
trangthai:lichsudata[k].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[j].key).remove();
}
}
for (var j = 0; j < lichsudata2.length; j++) {
if(lichsudata2[j].magd == magd){
for (var k = j+1; k < lichsudata2.length; k++) {
var postData = {
sotien:lichsudata2[k].sotien,
sodu:+lichsudata2[k].sodu - Number(lichsudata2[j].sotien),
ngaythang:lichsudata2[k].ngaythang,
magd:lichsudata2[k].magd,
loaichuyen:lichsudata2[k].loaichuyen,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/' + lichsudata2[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/'+lichsudata2[j].key).remove();
}
}
}else if(chedo=="Tiền tiết kiệm -> Thẻ"){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == sothebandau){
reftietkiem.set(sotientietkiemhientai + Number(sotienbandau));
for (var j = 0; j < lichsudata1.length; j++) {
if(lichsudata1[j].magd == magd){
for (var k = j+1; k < lichsudata1.length; k++) {
if(lichsudata1[k].sothe==sothebandau){
var postData = {
sotien:lichsudata1[k].sotien,
sodu:lichsudata1[k].sodu - Number(lichsudata1[j].sotien),
ngaythang:lichsudata1[k].ngaythang,
magd:lichsudata1[k].magd,
trangthai:lichsudata1[k].trangthai,
sothe:lichsudata1[k].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[k].key] = postData;
firebase.database().ref().update(updates);
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[j].key).remove();
}
}
for (var j = 0; j < lichsudata2.length; j++) {
if(lichsudata2[j].magd == magd){
for (var k = j+1; k < lichsudata2.length; k++) {
var postData = {
sotien:lichsudata2[k].sotien,
sodu:+lichsudata2[k].sodu + Number(lichsudata2[j].sotien),
ngaythang:lichsudata2[k].ngaythang,
magd:lichsudata2[k].magd,
loaichuyen:lichsudata2[k].loaichuyen,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/' + lichsudata2[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/'+lichsudata2[j].key).remove();
}
}
var postData1 = {
sotien: sothe[i].sotien - sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else if(chedo=="Tiền tiết kiệm -> Tiền mặt"){
reftienmat.set(sotienmathientai - Number(sotienbandau));
reftietkiem.set(sotientietkiemhientai + Number(sotienbandau));
for (var j = 0; j < lichsudata.length; j++) {
if(lichsudata[j].magd == magd){
for (var k = j+1; k < lichsudata.length; k++) {
var postData = {
sotien:lichsudata[k].sotien,
sodu:+lichsudata[k].sodu - Number(lichsudata[j].sotien),
ngaythang:lichsudata[k].ngaythang,
magd:lichsudata[k].magd,
trangthai:lichsudata[k].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[j].key).remove();
}
}
for (var j = 0; j < lichsudata2.length; j++) {
if(lichsudata2[j].magd == magd){
for (var k = j+1; k < lichsudata2.length; k++) {
var postData = {
sotien:lichsudata2[k].sotien,
sodu:+lichsudata2[k].sodu + Number(lichsudata2[j].sotien),
ngaythang:lichsudata2[k].ngaythang,
magd:lichsudata2[k].magd,
loaichuyen:lichsudata2[k].loaichuyen,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/' + lichsudata2[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/'+lichsudata2[j].key).remove();
}
}
}else if(chedo=="Thẻ -> Tiền mặt"){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == sothebandau){
reftienmat.set(sotienmathientai - Number(sotienbandau));
for (var j = 0; j < lichsudata.length; j++) {
if(lichsudata[j].magd == magd){
for (var k = j+1; k < lichsudata.length; k++) {
var postData = {
sotien:lichsudata[k].sotien,
sodu:+lichsudata[k].sodu - Number(lichsudata[j].sotien),
ngaythang:lichsudata[k].ngaythang,
magd:lichsudata[k].magd,
trangthai:lichsudata[k].trangthai,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutienmat/' + lichsudata[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutienmat/'+lichsudata[j].key).remove();
}
}
for (var j = 0; j < lichsudata1.length; j++) {
if(lichsudata1[j].magd == magd){
for (var k = j+1; k < lichsudata1.length; k++) {
if(lichsudata1[k].sothe==sothebandau){
var postData = {
sotien:lichsudata1[k].sotien,
sodu:lichsudata1[k].sodu + Number(lichsudata1[j].sotien),
ngaythang:lichsudata1[k].ngaythang,
magd:lichsudata1[k].magd,
trangthai:lichsudata1[k].trangthai,
sothe:lichsudata1[k].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[k].key] = postData;
firebase.database().ref().update(updates);
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[j].key).remove();
}
}
var postData1 = {
sotien: sothe[i].sotien + sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}else if(chedo=="Thẻ -> Tiền tiết kiệm"){
for (var i = 0; i < sothe.length; i++) {
if(sothe[i].sothe == sothebandau){
reftietkiem.set(sotientietkiemhientai - Number(sotienbandau));
for (var j = 0; j < lichsudata1.length; j++) {
if(lichsudata1[j].magd == magd){
for (var k = j+1; k < lichsudata1.length; k++) {
if(lichsudata1[k].sothe==sothebandau){
var postData = {
sotien:lichsudata1[k].sotien,
sodu:lichsudata1[k].sodu + Number(lichsudata1[j].sotien),
ngaythang:lichsudata1[k].ngaythang,
magd:lichsudata1[k].magd,
trangthai:lichsudata1[k].trangthai,
sothe:lichsudata1[k].sothe
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsucard/' + lichsudata1[k].key] = postData;
firebase.database().ref().update(updates);
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsucard/'+lichsudata1[j].key).remove();
}
}
for (var j = 0; j < lichsudata2.length; j++) {
if(lichsudata2[j].magd == magd){
for (var k = j+1; k < lichsudata2.length; k++) {
var postData = {
sotien:lichsudata2[k].sotien,
sodu:+lichsudata2[k].sodu - Number(lichsudata2[j].sotien),
ngaythang:lichsudata2[k].ngaythang,
magd:lichsudata2[k].magd,
loaichuyen:lichsudata2[k].loaichuyen,
};
var updates = {};
updates['/users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/' + lichsudata2[k].key] = postData;
firebase.database().ref().update(updates);
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/lichsutietkiem/'+lichsudata2[j].key).remove();
}
}
var postData1 = {
sotien: sothe[i].sotien + sotienbandau,
sothe:sothe[i].sothe,
tenthe:sothe[i].tenthe
};
var updates1= {};
updates1['/users/'+localStorage.getItem('key')+'/tien/danhsachthe/' + sothe[i].key] = postData1;
firebase.database().ref().update(updates1);
}
}
}
firebase.database().ref('users/'+localStorage.getItem('key')+'/tien/khoanchuyen/'+key).remove();
sessionStorage.clickcount = 2;
}
<file_sep>/js/profile.js
$(document).ready(function (e) {
var listemail=[];
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
firebase.database().ref('/users').on('value',function(snapshot){
snapshot.forEach(function(childSnapshot) {
listemail.push(childSnapshot.val().email);
});
});
$('.profilename').html(localStorage.getItem("name"));
$('#left-col-name').html(localStorage.getItem("name"));
$('#profilename1').html(localStorage.getItem("name"));
$('#profilename').html(localStorage.getItem("name"));
$('#openchooseimg').on('click', function() {
$('#theFile').trigger('click');
});
$("input[type=file]").bind("change", function() {
var selected_file_name = $(this).val();
if ( selected_file_name.length > 0 ) {
$(".overlay").show();
var data;
data = new FormData();
data.append( 'name',localStorage.getItem("username"));
data.append( 'file', $( '#theFile' )[0].files[0] );
$.ajax({
url: "http://quanlychitieu.info/upload.php",
type: "POST",
data: data,
contentType: false,
cache: false,
processData:false,
success: function(data1)
{
$(".overlay").hide();
if(data1 =="Sai định dạng file")
$.notify({ message: '<h4>Sai định dạng file hoặc ảnh quá lớn</h4>'},{ type: "danger", placement: { from: "top", align: "center" }, offset: 20, spacing: 10, z_index: 1031, delay: 1000, timer: 1000, url_target: '_blank', mouse_over: null, animate: { enter: 'animated flipInY', exit: 'animated flipOutX' }, });
else
firebase.database().ref('users/'+localStorage.getItem('key')+'/avatar').set(data1);
}
});
}
});
var password;
firebase.database().ref('users/'+localStorage.getItem('key')+'/password').on('value', function(snapshot) {
password=snapshot.val();
});
firebase.database().ref('users/'+localStorage.getItem('key')+'/email').on('value', function(snapshot) {
$('#email').html('Email: '+snapshot.val());
});
$('#value').on('click',function(){
$('.err').html('');
});
$('#oldpassword').keydown(function(e){
if(e.keyCode == 13)
{
$('#newpassword').focus();
$('#value').focus();
}
});
$('#newpassword').keydown(function(e){
if(e.keyCode == 13)
{
$('#updatePassword').click();
}
});
$('#value').keydown(function(e){
if(e.keyCode == 13)
{
$('#updateEmail').click();
}
});
$('#logout').on('click',function(){
localStorage.removeItem("key");
localStorage.removeItem("name");
localStorage.removeItem("username");
localStorage.removeItem("password");
});
$('#openpassword').on('click',function(){
$('.err').html('');
$('#showemail').hide();
$('#showmatkhaumoi').show();
$('#title').html('Thay đổi mật khẩu');
$('#updatePassword').show();
$('#updateEmail').hide();
$('#oldpassword').val("");
$('#newpassword').val('');
$('#value').val('');
});
$('#openemail').on('click',function(){
$('.err').html('');
$('#showmatkhaumoi').hide();
$('#showemail').show();
$('#title').html('Thay đổi Email');
$('#updatePassword').hide();
$('#updateEmail').show();
$('#oldpassword').val("");
$('#newpassword').val('');
$('#value').val('');
});
$('#myModal').on('shown.bs.modal', function () {
$('#oldpassword').focus();
});
$('#updatePassword').on('click',function(){
oldpassword=$('#oldpassword').val();
data=$('#newpassword').val();
if(data==""){
$('.err').html('<ul><li style="color:#b72012">Mật khẩu không được trống</li</ul>');
}else if(oldpassword!=password){
$('.err').html('<ul><li style="color:#b72012">Mật khẩu cũ không đúng</li</ul>');
}else if(data.length > 30 || data.length< 6){
$('.err').html('<ul><li style="color:#b72012;"><b>Mật khẩu mới quá dài hoặc quá ngắn</b></li></ul>');
}else if(password==data){
$('.err').html('<ul><li style="color:#b72012;"><b>Mật khẩu cũ không được giống mật khẩu mới</b></li></ul>');
}else{
firebase.database().ref('users/'+localStorage.getItem('key')+'/password').set(data);
localStorage.setItem("password", CryptoJS.AES.encrypt(data, "password"));
$('#myModal').modal('toggle');
$.notify({ message: '<h4>Cập nhật mật khẩu thành công</h4>'},{ type: "success", placement: { from: "top", align: "center" }, offset: 20, spacing: 10, z_index: 1031, delay: 1000, timer: 1000, url_target: '_blank', mouse_over: null, animate: { enter: 'animated flipInY', exit: 'animated flipOutX' }, });
}
});
$('#updateEmail').on('click',function(){
isEmailUsed=false;
oldpassword=$('#oldpassword').val();
data=$('#value').val();
for (var i = 0; i < listemail.length; i++) {
if(listemail[i]==data){
isEmailUsed=true;
}
}
if(oldpassword!=password){
$('.err').html('<ul><li style="color:#b72012">Mật khẩu cũ không đúng</li</ul>');
}else if(data == ""){
$('.err').html('<ul><li style="color:#b72012;"><b>Email không được trống</b></li></ul>');
}else if(!re.test(data)){
$('.err').html('<ul><li style="color:#b72012;"><b>Email không hợp lệ</b></li></ul>');
}else if(isEmailUsed){
$('.err').html('<ul><li style="color:#b72012;"><b>Email đã được sử dụng</b></li></ul>');
}else{
firebase.database().ref('users/'+localStorage.getItem('key')+'/email').set(data);
$('#myModal').modal('toggle');
$.notify({ message: '<h4>Cập nhật email thành công</h4>'},{ type: "success", placement: { from: "top", align: "center" }, offset: 20, spacing: 10, z_index: 1031, delay: 1000, timer: 1000, url_target: '_blank', mouse_over: null, animate: { enter: 'animated flipInY', exit: 'animated flipOutX' }, });
}
});
});<file_sep>/js/home.js
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
jQuery(document).ready(function() {
//cấu hình firebase
var listusername=[],listemail=[];
var patt1 = /\s/g;
var ref=firebase.database().ref('/users');
//hiệu ứng
$('.login-form input[type="text"], .login-form input[type="password"], .login-form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
ref.on('value',function(snapshot){
snapshot.forEach(function(childSnapshot) {
listusername.push(childSnapshot.val().username);
listemail.push(childSnapshot.val().email);
});
});
$('.login-form').on('keydown', 'input', function (event) {
if (event.which == 13) {
event.preventDefault();
var $this = $(event.target);
var index = parseFloat($this.attr('data-index-login'));
$('[data-index-login="' + (index + 1).toString() + '"]').focus();
}
});
$('.login-form').on('click', function(e) {
$(this).find('input[type="text"], input[type="password"], textarea').each(function(){
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
$('.login-form').on('click', function(e) {
$('.err').html('');
});
$('.registration-form').on('click', function(e) {
$('.err2').html(' ');
});
$('#forgetemail').on('click', function(e) {
$('.err2').html('');
});
//validate login
$('#signin').on('click', function(e) {
if($('#signinusername').val()==""){
$('.err').html('<ul><li style="color:#b72012;"><b>Tài khoản không được trống</b></li></ul>');
}else if($('#signinpassword').val()== ""){
$('.err').html('<ul><li style="color:#b72012;"><b>Mật khẩu không được trống</b></li></ul>');
}else{
var $this = $(this);
$this.button('loading');
var flag=false;
if(re.test($('#signinusername').val())){
ref.orderByChild("email").equalTo($('#signinusername').val()).once("child_added", function(snapshot) {
flag=true;
var password=snapshot.val().password;
if(password!=$('#signinpassword').val()){
$('.err').html('<ul><li style="color:#b72012;"><b>Sai mật khẩu</b></li></ul>');
}else if(password==$('#signinpassword').val()){
localStorage.setItem("key", snapshot.key);
localStorage.setItem("name", snapshot.val().name);
localStorage.setItem("username", snapshot.val().username);
localStorage.setItem("password", <PASSWORD>.<PASSWORD>(snapshot.val().password, "password"));
location='index.html';
}
});
}else{
ref.orderByChild("username").equalTo($('#signinusername').val()).once("child_added", function(snapshot) {
flag=true;
var password=snapshot.val().password;
if(password!=$('#signinpassword').val()){
$('.err').html('<ul><li style="color:#b72012;"><b>Sai mật khẩu</b></li></ul>');
}else if(password==$('#signinpassword').val()){
localStorage.setItem("key", snapshot.key);
localStorage.setItem("name", snapshot.val().name);
localStorage.setItem("username", snapshot.val().username);
localStorage.setItem("password", <PASSWORD>.AES.encrypt(snapshot.val().password, "password"));
location='index.html';
}
});
}
setTimeout(function(){
$this.button('reset');
if(!flag){
$('.err').html('<ul><li style="color:#b72012;"><b>Sai tài khoản</b></li></ul>');
}
}, 1000);
}
});
$('#signinpassword').keydown(function(e){
if(e.keyCode == 13)
{
$('#signin').click();
}
});
$('.registration-form input[type="text"], .registration-form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('.registration-form').on('keydown', 'input', function (event) {
if (event.which == 13) {
event.preventDefault();
var $this = $(event.target);
var index = parseFloat($this.attr('data-index'));
$('[data-index="' + (index + 1).toString() + '"]').focus();
}
});
$('.registration-form').on('click', function(e) {
$(this).find('input[type="text"],input[type="password"]').each(function(){
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
var ref1=firebase.database().ref('/users');
$('#register').on('click', function(e) {
var isEmailUsed=false,isUsernameUsed=false;
for (var i = 0; i < listemail.length; i++) {
if(listemail[i]==$('#registeremail').val()){
isEmailUsed=true;
}
}
for (var i = 0; i < listemail.length; i++) {
if(listusername[i]==$('#registerusername').val()){
isUsernameUsed=true;
}
}
if($('#registername').val() == ""){
$('.err2').html('<ul><li style="color:#b72012;"><b>Họ tên không được trống</b></li></ul>');
return;
}else if($('#registeremail').val() == ""){
$('.err2').html('<ul><li style="color:#b72012;"><b>Email không được trống</b></li></ul>');
return;
}else if(!re.test($('#registeremail').val())){
$('.err2').html('<ul><li style="color:#b72012;"><b>Email không hợp lệ</b></li></ul>');
return;
}else if(isEmailUsed){
$('.err2').html('<ul><li style="color:#b72012;"><b>Email đã được sử dụng</b></li></ul>');
return;
}else if($('#registerusername').val()==""){
$('.err2').html('<ul><li style="color:#b72012;"><b>Tài khoản không được trống</b></li></ul>');
return;
}else if(patt1.test( $('#registerusername').val())){
$('.err2').html('<ul><li style="color:#b72012;"><b>Tài khoản không được có khoảng trắng</b></li></ul>');
return;
}else if($('#registerusername').val().length >20 ||$('#registerusername').val().length<6){
$('.err2').html('<ul><li style="color:#b72012;"><b>Tài khoản quá dài hoặc qua ngắn</b></li></ul>');
return;
}else if(isUsernameUsed){
$('.err2').html('<ul><li style="color:#b72012;"><b>Tài khoản đã được sử dụng</b></li></ul>');
return;
}else if($('#registerpass').val()== ""){
$('.err2').html('<ul><li style="color:#b72012;"><b>Mật khẩu không được trống</b></li></ul>');
return;
}else if( $('#registerpass').val().length > 30 || $('#registerpass').val().length< 6){
$('.err2').html('<ul><li style="color:#b72012;"><b>Mật khẩu quá dài hoặc quá ngắn</b></li></ul>');
return;
}else{
ref1.push().set({
username:$('#registerusername').val(),
name:$('#registername').val(),
password:$('#<PASSWORD>').val(),
email:$('#registeremail').val()
});
$('.err2').html('');
$('#registerusername').val('');
$('#registeremail').val('');
$('#registerpass').val('');
$('#registername').val('');
$.notify({ message: '<h4>Đăng ký thành công</h4>' },{ type: "success", placement: { from: "top", align: "center" }, offset: 0, spacing: 20, z_index: 1031, delay: 2000, timer: 1000, url_target: '_blank', mouse_over: null, animate: { enter: 'animated flipInY', exit: 'animated flipOutX' }, });
}
});
$('#registerpass').keydown(function(e){
if(e.keyCode == 13)
{
$('#register').click();
}
});
});
(function(){
emailjs.init("user_IBKZKU66fttwWDE8buSbk");
})();
$('#quenmk').on('click', function(e) {
if($('#forgetemail').val() == ""){
$('.err3').html('<b style="color:#b72012;float:left;margin-left:10px">Email không được trống</b>');
}else if(!re.test($('#forgetemail').val())){
$('.err3').html('<b style="color:#b72012;float:left;margin-left:10px">Email không hợp lệ</b>');
}else{
var $this = $(this);
$this.button('loading');
var flag=false;
firebase.database().ref('/users').orderByChild("email").equalTo($('#forgetemail').val()).once("child_added", function(snapshot) {
var randompassword=Math.random().toString(24).substring(7);
flag=true;
$('#myModal').modal('toggle');
emailjs.send('default_service', 'template_otoQRGnk', {"send_to":$('#forgetemail').val(),"to_name":snapshot.val().name,"message_html":randompassword});
$.notify({ message: '<h4>Gửi email thành công</h4><br><p>Bạn vui lòng kiểm tra email để lấy lại mật khẩu</p>' },{ type: "success", placement: { from: "top", align: "center" }, offset: 0, spacing: 20, z_index: 1031, delay: 2000, timer: 1000, url_target: '_blank', mouse_over: null, animate: { enter: 'animated flipInY', exit: 'animated flipOutX' }, });
var postData;
if(snapshot.val().username=="khang1995"){
postData= {
password:<PASSWORD>,
name:snapshot.val().name,
tien:snapshot.val().tien,
phong:snapshot.val().phong,
username:snapshot.val().username,
tienphong:snapshot.val().tienphong,
email:snapshot.val().email,
avatar:snapshot.val().avatar,
};
}else{
postData = {
password:<PASSWORD>,
name:snapshot.val().name,
tien:snapshot.val().tien,
username:snapshot.val().username,
email:snapshot.val().email,
avatar:snapshot.val().avatar,
};
}
var updates = {};
updates['/users/'+ snapshot.key] = postData;
firebase.database().ref().update(updates);
});
setTimeout(function(){
$this.button('reset');
if(!flag){
$('.err3').html('<b style="color:#b72012;float:left;margin-left:10px">Email không tồn tại trên hệ thống</b>');
}
}, 1000);
}
});
| 4b2adab6970b46562120622fa72812e9a145a17a | [
"JavaScript"
] | 3 | JavaScript | khang1995/Ass_INF205 | d97ba9b9d26374df1192c9fd7cb8a9b43c0d7d65 | 0f393cc0fd0e2d7d5c8853922f7cfbc680d971d3 | |
refs/heads/master | <repo_name>devqi/react-playground<file_sep>/tasks-mgmt/README.md
#
## pure react template - v1
##### Prerequisites: nodejs, npm, yarn are already installed.
##### Create necessary files for the projects:
- **yarn init** or **npm init** => generate package.json which includes basic information, such as name, version, author, license, etc.
- create a folder named **public** and add a file named **index.html** under it.
- create a folder named **src** and add a file named **index.js** under it.
- [optional] set up a web server **live-server** by using **yarn add [global] live-server** or **npm install [-g] live-server**.
- set up Babel locally
- run **yarn add babel-cli babel-preset-react babel-preset-env** to add these two to the dependency-list in package.json to allow JSX to be complied automatically. Meanwhile, **node_modules** and **yarn.lock** are added. The concrete specification can be found in [Babel Plugins](https://babeljs.io/docs/plugins/).
- add a new file **.babelrc** and configre babel presets/plugins in it.
<br>
:exclamation::exclamation::exclamation: Babel has on its own no functionality, which means Babel is a compiler that is not going to complie anything by default. Therefore, various plugins and presets need to be added to reach the compilation goal.
- set up Webpack: run **yarn add webpack** to add webpack locally.
- add a file **webpack.config.js** under the project root folder and define a simple configuration in this file according to the [configuraiton template](https://webpack.js.org/concepts/configuration/).
- install **babel-loader** and configure it in the file to handle JSX.
- [optional] install **webpack-dev-server** and configure it in **webpack.config.js**.
- add a file **.babelrc** under the project root folder to specify the babel presets and plugins.
<br>
:exclamation::exclamation::exclamation: Webpack is an asset bundler which allows us to bundle all the stuff that makes up applications and the applied 3rd-Party libraries into a single JavaScript.
<file_sep>/README.md
# react-playground
### indecision-app:
##### a TODOs app
### expensify-app:
##### an expense/income management app
<file_sep>/indecision-app/src/components/Header.js
import React from 'react';
// export default class Header extends React.Component {
// render() {
// return (
// <header>
// <h1 className='title'>Indecision App</h1>
// <h2 className='subtitle'>Put your life in control</h2>
// </header>
// );
// }
// }
const Header = () => (
<header>
<div className='container'>
<h1 className='title'>Indecision App</h1>
<h2 className='subtitle'>Put your life in control</h2>
</div>
</header>
);
export default Header;<file_sep>/indecision-app/src/components/Actions.js
import React from 'react';
// export default class OperateOption extends React.Component {
// render() {
// const btnsWhenHasOptions = <div className='operation_buttons'>
// <button className='choose_an_option' onClick={this.props.handleChooseAnOption}>What should I do?</button>
// <button className='remove_all_options' onClick={this.props.handleRemoveAllOptions}>Remove all</button>
// </div>;
// return (
// this.props.options.length > 0 ? btnsWhenHasOptions : ''
// );
// }
// }
const Actions = (props) => {
return (
<div className='operation_buttons'>
<button className='choose_an_option big-button' onClick={props.handleChooseAnOption} disabled={!(props.options.length > 0 )}>What should I do?</button>
</div>
);
}
export default Actions;
<file_sep>/indecision-app/src/components/AddOption.js
import React from 'react';
export default class AddOption extends React.Component {
constructor(props) {
super(props);
this.state = {
error: undefined
};
this.handleAddAnOption = this
.handleAddAnOption
.bind(this);
}
handleAddAnOption(e) {
e.preventDefault();
// get the content of <input>
const option = e.target.elements.option.value.trim();
// pass 'option' to the function in IndecisionApp.js
const error = this.props.handleAddAnOption(option);
this.setState(() => ({ error }));
if (!error) {
e.target.elements.option.value = '';
}
}
render() {
return (
<div>
{this.state.error && <p className='add-option-error'>{this.state.error}</p>}
<form className='add-option' onSubmit={this.handleAddAnOption}>
<input className='add-option__input' type="text" name="option"/>
<button className='button'>Add Option</button>
</form>
</div>
);
}
}<file_sep>/indecision-app/src/components/Option.js
import React from 'react';
// export default class Option extends React.Component {
// render() {
// return (
// <li>
// {this.props.option}
// <button onClick={e => this.props.handleRemoveAnOption(this.props.option) } >remove</button>
// </li>
// );
// }
// }
const Option = (props) => (
<li className='option'>
<p className='option__text'>{props.optionIndex}. {props.option}</p>
<button className='button--link' onClick={e => props.handleRemoveAnOption(props.option) } >remove</button>
</li>
);
export default Option;<file_sep>/indecision-app/src/components/Options.js
import React from 'react';
import Option from './Option';
import md5 from 'react-native-md5';
// export default class Options extends React.Component {
// render() {
// let options = this.props.options;
// return (
// <div>
// <ol>
// {
// options.map(option =>
// <Option
// key={md5.hex_md5(option + '')}
// option={option}
// handleRemoveAnOption={this.props.handleRemoveAnOption}/>
// )
// }
// </ol>
// </div>
// );
// }
// }
const Options = (props) => (
<div>
<div className='widget-header'>
<h3 className='widget-header__title'>Your Options</h3>
<button className='remove_all_options button button--link' onClick={props.handleRemoveAllOptions}>Remove all</button>
</div>
{
!(props.options.length > 0) && <p className='widget__message'>Please add an option to get started !</p>
}
<ul className='options'>
{
props.options.map((option, index) =>
<Option
key={md5.hex_md5(option + '')}
option={option}
optionIndex = {index + 1}
handleRemoveAnOption={props.handleRemoveAnOption}/>
)
}
</ul>
</div>
);
export default Options;<file_sep>/my-own-practice/src/test.js
import React from 'react';
import ReactDom from 'react-dom';
const user = {
'firstname': 'Qi',
'lastname': 'Zhang'
};
function formatUser(user) {
return user.lastname + ', ' + user.firstname;
}
class Greeting extends React.Component {
constructor(props) {
super(props);
this.state = {
date: new Date(),
isToggleOn: true
};
/**
* Must be careful about the meaning of this in JSX callbacks.
* In JavaScript, class methods are not bound by default.
* If you forget to bind this.handleClick and pass it to onClick,
* this will be undefined when the function is actually called.
*
* This is not React-specific behavior;
* it is a part of "how functions work in JavaScript".
* Generally, if you refer to a method without () after it,
* such as onClick={this.handleClick}, you should bind that method.
* https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/
*/
// This binding is necessary to make `this` work in the callback
this.handleClick = this.handleClick.bind(this);
}
componentDidMount() {
this.timerID = setInterval(
() => this.tick(),
1000
);
}
componentWillUnmount() {
clearInterval(this.timerID);
}
tick() {
this.setState({
date: new Date()
});
}
handleClick() {
this.setState( prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render(){
if(this.state.user) {
return (
<div>
<h1>Hello {formatUser(this.state.user)} !</h1>
<h2 > It is { this.state.date.toLocaleTimeString() }. </h2>
</div>
);
}
else {
return (
<div>
<h1>Hello stranger !</h1>
<h2 > It is { new Date().toLocaleTimeString() }. </h2>
<button onClick={this.handleClick}>
{this.state.isToggleOn ? "On" : "Off"}
</button>
</div>
);
}
}
}
function Clock(props) {
return (
<div>
<h1>Hello {formatUser(props.user)} !</h1>
<h2 > It is { props.date.toLocaleTimeString() }. </h2>
</div>
);
}
/**
* It works because in JavaScript,
* true && expression always evaluates to expression,
* and false && expression always evaluates to false.
*/
function Mailbox(props) {
const unreadMessages = props.unreadMessages;
return (
<div>
<h1>Hello!</h1>
{unreadMessages.length > 0 &&
<h2>
You have {unreadMessages.length} unread messages.
</h2>
}
</div>
);
}
const messages = ['React', 'Re: React', 'Re:Re: React'];
function WarningBanner(props) {
if (!props.warn) {
return null;
}
return (
<div className="warning">
Warning!
</div>
);
}
class Page extends React.Component {
constructor(props) {
super(props);
this.state = {showWarning: true}
this.handleToggleClick = this.handleToggleClick.bind(this);
}
handleToggleClick() {
this.setState(prevState => ({
showWarning: !prevState.showWarning
}));
}
render() {
return (
<div>
<WarningBanner warn={this.state.showWarning} />
<button onClick={this.handleToggleClick}>
{this.state.showWarning ? 'Hide' : 'Show'}
</button>
</div>
);
}
}
function App() {
return (
<div>
<Greeting />
<Mailbox unreadMessages={messages} />
<Page />
</div>
);
}
ReactDom.render(
<App />,
document.getElementById('root')
);
<file_sep>/expensify-app/src/components/ExpenseListItem.js
import React from 'react';
import { Link } from 'react-router-dom';
/**
* snippet#1: passed-in object destructuring
*/
const ExpenseListItem = ( {dispatch, id, description, amount, createdAt, note } ) => (
<div>
<Link to={`/edit/${id}`}>
<h3>{description}</h3>
</Link>
<p>{amount} - {createdAt}</p>
<p>{note}</p>
<hr />
</div>
);
/**
* snippet#2: normal passed-in props
*/
// const ExpenseListItem = (props) => (
// <div>
// <h3>{props.description}</h3>
// <p>{props.amount} - {props.createdAt}</p>
// <hr />
// </div>
// );
export default ExpenseListItem;<file_sep>/expensify-app/src/firebase/firebase.js
import * as firebase from 'firebase';
const config = {
apiKey: "<KEY>",
authDomain: "expensify-98a02.firebaseapp.com",
databaseURL: "https://expensify-98a02.firebaseio.com",
projectId: "expensify-98a02",
storageBucket: "expensify-98a02.appspot.com",
messagingSenderId: "321141692729"
};
firebase.initializeApp(config);
const database = firebase.database();
// database.ref('expenses').push({
// description: 'water bill',
// amount: 100,
// createdAt: 200,
// note: 'water bill for 2017'
// });
// database.ref('expenses').push({
// description: 'electricity bill',
// amount: 120,
// createdAt: 200,
// note: 'electricity bill for 2017'
// });
// database.ref('expenses').push({
// description: 'food',
// amount: 300,
// createdAt: 200,
// note: 'costs of food in 2017'
// });
const ref = database.ref('expenses');
ref.once('value').then((snapshot) => {
const expenses = [];
console.log('snapshot.key = ', snapshot.key);
snapshot.forEach((childSnapshot) => {
console.log('child-snapshot.key = ', snapshot.key);
expenses.push({
id: childSnapshot.key,
...childSnapshot.val()
});
});
console.log('expenses: ', expenses);
});
// firebase
// .database()
// .ref()
// .set({
// name: 'pandaZ',
// age: 29,
// isSingle: false,
// location: {
// city: 'Hamburg',
// country: 'Germany'
// },
// job: {
// title: 'Software Developer',
// company: 'Amazon'
// }
// }).then(
// (data) => {
// console.log('this is a success handler');
// },
// (error) => {
// console.log('this is a failure handler', error);
// });
// firebase
// .database()
// .ref('age')
// .set(31);
// firebase
// .database()
// .ref('location/city')
// .set('Frankfurt am Main');
// firebase
// .database()
// .ref('attributes/height')
// .set(165);
// firebase
// .database()
// .ref('attributes/weight')
// .set(45);
/**
* fetch data from database
*/
// const ref = database.ref();
// ref.once('value')
// .then(function (snapshot) {
// const key = snapshot.key;
// const value = snapshot.val();
// console.log(key + ' = ' + value);
// });
// const onValueChange = (snapshot) =>{
// const key = snapshot.key;
// const value = snapshot.val();
// console.log(key + ' : ' + value);
/**
* Syntax 1
*/
// const name = snapshot.child('name').val();
// const jobTitle = snapshot.child('job/title').val();
// console.log(name, 'is a ', jobTitle);
/**
* Syntax 2
*/
// const value = snapshot.val();
// console.log(`${value.name} is a ${value.job.title} at ${value.job.company}.`)
// };
// ref.on('value', onValueChange);
// setTimeout(() => {
// ref.update({
// name: 'Batman',
// 'job/title': 'Lead Consultant',
// 'job/company': 'Google'
// });
// }, 3500);
// setTimeout(() => {
// ref.off();
// }, 7000);
// setTimeout(() => {
// ref.update({
// name: 'Lee',
// 'job/title': 'Senior Consultant'
// });
// }, 10500);
///////////////////////////////////////////
// database.ref('attributes').set({
// height: 180,
// weight: 100
// }).then(
// (data) => {
// console.log('atrributes updated');
// },
// (error) => {
// console.log('atrributes failed updating', error);
// }
// );
/**
* remove a property
*
* refIsSingle.set(null) is equivalent to refIsSingle.remove()
*/
// const refIsSingle = database.ref();
// refIsSingle.remove().then(
// () => {
// console.log('remove succeeded.');
// },
// (error) => {
// console.log('remove failed.', error);
// }
// );
/**
* update some content in database
*/
// database.ref().update({
// name: 'Catfish',
// isSingle: null,
// 'location/city': 'Munich'
// });
<file_sep>/expensify-app/src/tests/actions/filters.test.js
import { setTextFilter, sortByAmount, sortByDate, setStartDate, setEndDate } from '../../actions/filters';
import moment from 'moment';
test('set text filter to be "bill"', () => {
const text = 'bill';
const action = setTextFilter(text);
expect(action).toEqual({
type: 'TEXT_FILTER',
text: 'bill'
});
});
test('set to be "sortByAmount"', () => {
const action = sortByAmount();
expect(action).toEqual({
type: 'SORT_BY_AMOUNT'
});
});
test('set to be "sortByDate"', () => {
const action = sortByDate();
expect(action).toEqual({
type: 'SORT_BY_DATE'
});
});
test('setStartDate', () => {
const start = moment(0);
const action = setStartDate(start);
expect(action).toEqual({
type: 'SET_START_DATE',
startDate: start
});
});
test('setEndDate', () => {
const end = moment(0);
const action = setEndDate(end);
expect(action).toEqual({
type: 'SET_END_DATE',
endDate: end
});
}); | bd59405dfedded501f6e78631efbd9dc9f34fcfe | [
"Markdown",
"JavaScript"
] | 11 | Markdown | devqi/react-playground | cbb603af3ff80d1b50589f075d03a56cd7ad2fbf | 71fe65b6a3ecc5013e385755723fb7edd1bfa122 | |
refs/heads/main | <file_sep>version: "3.7"
services:
client:
build:
context: ./client
dockerfile: ./Dockerfile
image: post-client
container_name: post-client
ports:
- "4444:3000"
deploy:
replicas: 3
api:
build:
context: ./server
dockerfile: ./Dockerfile
image: post-api
container_name: post-api
environment:
- PORT=3000
ports:
- "3333:3000"
deploy:
replicas: 6
nginx:
image: post-nginx
container_name: nginx
depends_on:
- api
- client
build:
context: ./nginx
dockerfile: ./Dockerfile
ports:
- "80:80"
deploy:
replicas: 1
<file_sep>import Axios from "axios";
export const axios = Axios.create({
baseURL: " https://jsonplaceholder.typicode.com",
});
export const imageApi = Axios.create({
baseURL: "https://picsum.photos/v2",
});
<file_sep>import { Module } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { join } from 'path';
import { PostsModule } from './posts/posts.module';
import { CommentsModule } from './comments/comments.module';
import { PostsService } from './posts/posts.service';
import { CommentsService } from './comments/comments.service';
@Module({
imports: [
GraphQLModule.forRoot({
dataSources: () => ({
postsAPI: new PostsService(),
commentsAPI: new CommentsService(),
}),
include: [PostsModule, CommentsModule],
autoSchemaFile: join(process.cwd(), 'src/schema.gql'),
}),
PostsModule,
CommentsModule,
],
})
export class AppModule {}
<file_sep>import { ObjectType, Field, Int } from '@nestjs/graphql';
import { IPost } from '../../types';
@ObjectType()
export class Post implements IPost {
@Field(() => Int, { description: 'Id of the User' })
userId: number;
@Field(() => Int, { description: 'Id of the Post' })
id: number;
@Field(() => String, { description: 'Title of the Post' })
title: string;
@Field(() => String, { description: 'Body of the Post' })
body: string;
}
@ObjectType()
export class PostsConnection {
@Field(() => Int)
totlaCount: number;
@Field(() => String, { nullable: true })
cursor?: string;
@Field(() => Boolean)
hasMore: boolean;
@Field(() => [Post])
posts: Post[];
}
<file_sep>- display all posts
- display a post with its comments
- a search box that filters the comments
- the search should be able to handle :
- name
- email
- body
<file_sep>## A fullstack Repository Implementing Docker Swarm
<file_sep>import { Injectable } from '@nestjs/common';
import { CommentSearch } from '../types';
import { Comment } from './entities/comment.entity';
import { RESTDataSource } from 'apollo-datasource-rest';
@Injectable()
export class CommentsService extends RESTDataSource {
private _URL = 'https://jsonplaceholder.typicode.com/comments';
constructor() {
super();
this.baseURL = this._URL;
}
async findAll() {
const result = await this.get<Comment[]>('/');
return result;
}
async findSearch(input: string, search: CommentSearch) {
const result = await this.get<Comment[]>(`/`, {
per_page: 20,
[search]: input,
});
return result;
}
}
<file_sep>## Instructions
There are several ways to run the api
### Run With Docker Compose Dev Mode
```
docker-compose -f docker-compose.dev.yml up -d
```
### Run With Docker Compose
```
docker-compose up -d
```
### Run With Docker Build Only
```
docker build . -t graphapi
docker run --name api -p 3000:3000 \
graphapi
```
### Run Project Normally
```
yarn install OR npm install
yarn start:dev OR npm start
```
<file_sep>import { Resolver, Query, Args, Int, Context } from '@nestjs/graphql';
import { Post, PostsConnection } from './entities/post.entity';
import { IDatasource } from '../types';
import { paginateResults } from '../util';
@Resolver(() => Post)
export class PostsResolver {
constructor() {}
@Query(() => PostsConnection, { name: 'posts' })
async findAll(
@Args('after', { nullable: true }) after: number,
@Context('dataSources') { postsAPI }: IDatasource,
) {
const posts = await postsAPI.findAll();
return this.paginateComments(posts, after);
}
@Query(() => Post, { name: 'post' })
findOne(
@Args('id', { type: () => Int }) id: number,
@Context('dataSources') { postsAPI }: IDatasource,
) {
return postsAPI.findOne(id);
}
paginateComments(posts: Post[], after: number) {
const paginateComments = paginateResults({
after: after,
pageSize: 20,
results: posts,
});
const postsConnected = {
totlaCount: posts.length,
posts: paginateComments,
cursor: paginateComments.length
? paginateComments[paginateComments.length - 1].id
: null,
hasMore: paginateComments.length
? paginateComments[paginateComments.length - 1].id !==
posts[paginateComments.length]?.id
: false,
} as PostsConnection;
return postsConnected;
}
}
<file_sep>import { Args, Context, Query, Resolver } from '@nestjs/graphql';
import { paginateResults } from '../util';
import { CommentSearch, IDatasource } from '../types';
import { Comment, CommentsConnection } from './entities/comment.entity';
@Resolver(() => Comment)
export class CommentsResolver {
constructor() {}
@Query(() => CommentsConnection, { name: 'comments' })
async findAll(
@Context('dataSources') { commentsAPI }: IDatasource,
@Args('after', { nullable: true }) after: number,
) {
const comments = await commentsAPI.findAll();
return this.paginateComments(comments, after);
}
@Query(() => CommentsConnection, { name: 'commentsBySearch' })
async findBySearch(
@Args('CommentSearch', { type: () => CommentSearch }) search: CommentSearch,
@Args('input') input: string,
@Args('after', { nullable: true }) after: number,
@Context('dataSources') { commentsAPI }: IDatasource,
) {
const comments = await commentsAPI.findSearch(input, search);
return this.paginateComments(comments, after);
}
paginateComments(comments: Comment[], after: number) {
const paginateComments = paginateResults({
after: after,
pageSize: 20,
results: comments,
});
const commentsConnected = {
totlaCount: comments.length,
comments: paginateComments,
cursor: paginateComments.length
? paginateComments[paginateComments.length - 1].id
: null,
hasMore: paginateComments.length
? paginateComments[paginateComments.length - 1].id !==
comments[paginateComments.length]?.id
: false,
} as CommentsConnection;
return commentsConnected;
}
}
<file_sep>export const containerVariants = {
hidden: {
opacity: 0,
},
visible: {
opacity: 1,
transition: { delay: 0.4, duration: 0.8 },
},
exit: {
x: "-100vh",
transition: { ease: "easeInOut" },
},
};
<file_sep>import { Field, Int, ObjectType } from '@nestjs/graphql';
import { IComment } from '../../types';
@ObjectType()
export class Comment implements IComment {
@Field(() => Int, { description: 'Comment Id' })
id: number;
@Field(() => Int, { description: ' Post Id' })
postId: number;
@Field(() => String, { description: 'User Name of the Commenter' })
name: string;
@Field(() => String, { description: 'Email of the Commenter' })
email: string;
@Field(() => String, { description: 'Text of the Comment' })
body: string;
}
@ObjectType()
export class CommentsConnection {
@Field(() => Int)
totlaCount: number;
@Field(() => String, { nullable: true })
cursor?: string;
@Field(() => Boolean)
hasMore: boolean;
@Field(() => [Comment])
comments: Comment[];
}
<file_sep>import { registerEnumType } from '@nestjs/graphql';
import { CommentsService } from '../comments/comments.service';
import { PostsService } from '../posts/posts.service';
export interface IPost {
userId: number;
id: number;
title: string;
body: string;
}
export interface IComment {
id: number;
postId: number;
name: string;
email: string;
body: string;
}
export enum CommentSearch {
id = 'id',
postId = 'postId',
name = 'name',
email = 'email',
body = 'body',
}
registerEnumType(CommentSearch, {
name: 'CommentSearch',
description: 'Property Type of the comment to searched ',
});
export interface IDatasource {
postsAPI: PostsService;
commentsAPI: CommentsService;
}
export type pageItem = IComment | IPost;
export type pageItems = IComment[] | IPost[];
<file_sep>import { Injectable } from '@nestjs/common';
import { RESTDataSource } from 'apollo-datasource-rest';
import { Post } from './entities/post.entity';
@Injectable()
export class PostsService extends RESTDataSource {
private _URL = 'https://jsonplaceholder.typicode.com/posts';
constructor() {
super();
this.baseURL = this._URL;
}
async findAll() {
const result = await this.get<Post[]>('/');
return result;
}
async findOne(id: number) {
const result = await this.get<Post>(`/${id}`);
return result;
}
}
<file_sep>export interface Post {
userId: number;
id: number;
title: string;
body: string;
image?: string;
}
export interface Comment {
postId: number;
id: number;
name: string;
email: string;
body: string;
}
export enum CommentSearch {
name = "name",
email = "email",
body = "body",
}
| 6888a0c7e1f9c9fe87c1d0bd884c38790ddb3cd0 | [
"Markdown",
"TypeScript",
"YAML"
] | 15 | YAML | Khaalidsub/swarm-sample | 831dfa0dc2e896b6762bae5ef73a2799acde4525 | 180a185577d08b4e6e3f319fe1baae1e9d2b2f59 | |
refs/heads/master | <repo_name>urbit/indigo-react<file_sep>/src/util.ts
export const sequence = (num: number) => Array.from(Array(num), (_, i) => i);
<file_sep>/docs/src/types.ts
export type ComponentProperties = {
id: string;
displayName: string;
snippet: string;
props: [];
};
export type ComponentEntry = {
id: string;
displayName: string;
};
export type Manifest = {
componentCount: number;
components: ComponentEntry[];
};
<file_sep>/DEVELOPMENT.md
# Development
## Getting Started
`npm install`
`npm install -g typescript` if you have never install TS
`npm run build`
There are a few ways of making new components for Indigo. Let's cover some of the core patterns.
## Component Patterns
### Single Element Component with dynamic properties
Creating a basic theme-aware component with dynamic properties from scratch.
```tsx
import styled from "styled-components";
import css, { SystemStyleObject } from "@styled-system/css";
// commonStyle includes all commonly used styled-system props
import { commonStyle, CommonStyleProps } from "./system/unions";
// Define property types and export typing
export type LabelProps = CommonStyleProps & {
gray?: boolean;
bold?: boolean;
mono?: boolean;
};
// First, a we create a style object. Then, we pass it to css(), whcih converts values like fontSize:0 to fontSize:'12px'. The conversion is based on the theme. Css() returns a function that can be passed to styled.foo() as a StyleFn, like border, color, and flexbox imported from styled-system. This method is convinient because you don't have to pass the theme as a prop and write a bunch of template string functions for each dynamic property. We also assign prop defaults in the argument field.
const style = ({ gray = false, bold = false, mono = false }: LabelProps) =>
css({
fontWeight: bold ? "bold" : "regular",
color: gray ? "gray" : "black",
fontFamily: mono ? "mono" : "sans",
display: "block",
lineHeight: "short",
fontSize: 1,
pointerEvents: "none",
userSelect: "none",
verticalAlign: "middle",
width: "100%",
} as SystemStyleObject);
// Here, we define out component. Because we want this component to use an HTML <label>, we used styled.label and pass a series of styleFns to it. These essentially 'gather' the styles defined above and styles passed through props. They are then merged in a css class which is seen in the DOM as something like `sc-jFdnav`.
export const Label = styled.label<React.PropsWithChildren<LabelProps>>(
style,
...commonStyle
);
// Add a displayName. It appears in the React devtools inspector and in errors. This is mandatory.
Label.displayName = "Label";
```
## Single Element Styled Component from Existing Component
Creating a styled component from an existing component, like one sourced from a 3rd party library.
```tsx
import { Form as FormikForm } from "formik";
import styled from "styled-components";
import { compose } from "styled-system";
import { structureStyle, StructureProps } from "./system/unions";
// Create and export property typing.
type ManagedFormProps = StructureProps;
// An existing component can be passed to styled() to create a styled component.
export const ManagedForm = styled(FormikForm)<
React.PropsWithChildren<ManagedFormProps>
>({}, ...structureStyle);
ManagedForm.displayName = "ManagedForm";
```
### Composite React Component
This is a component made from several styled components imported from Indigo.
```tsx
import * as React from "react";
import { CommonStyleProps } from "./system/unions";
import { Row } from "../Row/Row";
import { Col } from "../Col/Col";
// Create and export the main component typing
export type TwoUpProps = CommonStyleProps &
// Extend with this React typing so that the base component has div properties.
React.HTMLAttributes<HTMLDivElement> & {
// This is a special case where we overwrite `children` to be an array.
children: React.ReactNodeArray;
};
type ChildProps = CommonStyleProps & React.HTMLAttributes<HTMLDivElement>;
const Child = ({ children, ...props }: ChildProps) => (
<Col width={["100%", "100%", "50%"]} {...props}>
{children || <div />}
</Col>
);
export const TwoUp = ({ children, ...props }: TwoUpProps) => (
<Row flexDirection={["column", "row", "row"]} flexWrap="wrap" {...props}>
<Child>{children[0] || <div />}</Child>
<Child>{children[1] || <div />}</Child>
</Row>
);
TwoUp.displayName = "TwoUp";
```
## Scripts
`npm run build` Builds the library with `esbuild` and constructs typings with `tsc`
`npm run esbuild` Builds the library with `esbuild` but skips generating typings. Typings take a long time to generate, so if you havn't changed your type definitons, this can rapidly speed up iteration time for visual polish tasks.
`npm run reset` Removes node_modules and package-lock.json and npm installs fresh
### Related
| Library | Github | NPM |
| ------------ | ----------------------------------------- | ------------------------------------------------ |
| indigo-light | https://www.github.com/urbit/indigo-light | https://www.npmjs.com/package/@tlon/indigo-light |
| indigo-dark | https://www.github.com/urbit/indigo-dark | https://www.npmjs.com/package/@tlon/indigo-dark |
| indigo-react | https://www.github.com/urbit/indigo-react | https://www.npmjs.com/package/@tlon/indigo-react |
### License
MIT License © [Tlon](https://tlon.io)
<file_sep>/src/system/tokens.ts
import { SystemStyleObject } from "@styled-system/css";
type SystemStyleObjects = {
[key: string]: SystemStyleObject;
};
type SystemStyleProp =
| string
| string[]
| number[]
| (string & (string | number | symbol | null)[])
| (string & {
[x: string]: string | number | symbol | undefined;
[x: number]: string | number | symbol | undefined;
})
| undefined;
const container = {
center: {
display: "flex",
alignItems: "center",
justifyContent: "center",
} as SystemStyleObject,
centerX: {
display: "flex",
alignItems: "center",
} as SystemStyleObject,
centerY: {
display: "flex",
justifyContent: "center",
} as SystemStyleObject,
};
const button = {
state: {
primary: {
backgroundColor: "blue",
color: "white",
// "*": { fill: "white" },
borderColor: "blue",
},
primaryDisabled: {
backgroundColor: "washedBlue",
color: "lightBlue",
// "*": { fill: "lightBlue" },
borderColor: "lightBlue",
},
default: {
backgroundColor: "white",
color: "black",
// "*": { fill: "black" },
borderColor: "lightGray",
},
defaultDisabled: {
backgroundColor: "washedGray",
color: "lightGray",
// "*": { fill: "lightGray" },
borderColor: "lightGray",
},
destructivePrimary: {
backgroundColor: "red",
color: "white",
// "*": { fill: "white" },
borderColor: "red",
},
destructivePrimaryDisabled: {
backgroundColor: "washedRed",
color: "lightRed",
// "*": { fill: "lightRed" },
borderColor: "lightRed",
},
destructive: {
backgroundColor: "white",
color: "red",
// "*": { fill: "red" },
borderColor: "red",
},
destructiveDisabled: {
backgroundColor: "washedRed",
color: "lightRed",
// "*": { fill: "lightRed" },
borderColor: "lightRed",
},
} as SystemStyleObjects,
text: {
textAlign: "center",
verticalAlign: "middle",
lineHeight: "short",
fontWeight: 500,
userSelect: "none",
fontSize: 1,
fontFamily: "sans",
textDecoration: "none",
} as SystemStyleObject,
};
const action = {
state: {
default: {
color: "blue",
background: "white",
// "*": { fill: "blue" },
},
defaultDisabled: {
color: "lightGray",
background: "white",
// "*": { fill: "lightGray" },
},
destructive: {
color: "red",
background: "white",
// "*": { fill: "red" },
},
destructiveDisabled: {
color: "lightRed",
background: "white",
// "*": { fill: "lightRed" },
},
} as SystemStyleObjects,
text: {
textAlign: "left",
verticalAlign: "middle",
lineHeight: "short",
fontWeight: 500,
userSelect: "none",
fontSize: 1,
fontFamily: "sans",
textDecoration: "none",
} as SystemStyleObject,
};
const indicator = {
state: {
on: {
"*": { fill: "white" },
backgroundColor: "blue",
borderColor: "blue",
},
off: {
"*": { fill: "transparent" },
backgroundColor: "white",
borderColor: "lightGray",
},
onError: {
"*": { fill: "white" },
backgroundColor: "red",
borderColor: "red",
},
offError: {
"*": { fill: "transparent" },
backgroundColor: "washedRed",
borderColor: "red",
},
offDisabled: {
"*": { fill: "transparent" },
backgroundColor: "washedGray",
borderColor: "lightGray",
},
onDisabled: {
"*": { fill: "lightGray" },
backgroundColor: "washedGray",
borderColor: "lightGray",
},
} as SystemStyleObjects,
};
const selectorDefaults = {
display: "block",
position: "absolute",
padding: "6px",
borderRadius: "999px",
border: "1px solid",
// content property `' '` must be wrapped in quotes.
content: "' '",
};
const toggleSwitch = {
states: {
selected: {
backgroundColor: "blue",
borderColor: "transparent",
"&::before": {
// Note that `border-color` must come after `border`.
...selectorDefaults,
backgroundColor: "white",
borderColor: "transparent",
transform: "translateX(8px)",
},
},
default: {
backgroundColor: "lightGray",
borderColor: "transparent",
"&::before": {
...selectorDefaults,
borderColor: "transparent",
backgroundColor: "white",
},
},
selectedDisabled: {
backgroundColor: "lightGray",
borderColor: "transparent",
"&::before": {
...selectorDefaults,
backgroundColor: "scales.white70",
borderColor: "transparent",
transform: "translateX(8px)",
},
},
hasErrorSelected: {
backgroundColor: "red",
borderColor: "transparent",
"&::before": {
...selectorDefaults,
backgroundColor: "white",
borderColor: "transparent",
transform: "translateX(8px)",
},
},
hasError: {
backgroundColor: "red",
borderColor: "transparent",
"&::before": {
...selectorDefaults,
borderColor: "transparent",
backgroundColor: "white",
},
},
disabled: {
backgroundColor: "lightGray",
borderColor: "transparent",
"&::before": {
...selectorDefaults,
borderColor: "transparent",
backgroundColor: "scales.white70",
},
},
} as SystemStyleObjects,
};
const textInput = {
state: {
default: {
borderColor: "lightGray",
color: "black",
backgroundColor: "white",
},
disabled: {
borderColor: "lightGray",
color: "gray",
backgroundColor: "washedGray",
},
hasError: {
borderColor: "red",
color: "red",
backgroundColor: "washedRed",
},
} as SystemStyleObjects,
text: {
textAlign: "left",
lineHeight: "short",
fontWeight: 400,
fontSize: 1,
fontFamily: "sans",
textDecoration: "none",
} as SystemStyleObject,
};
export {
// Core patterns
container,
// UI Patterns
button,
action,
textInput,
toggleSwitch,
// Used for radio and checkbox
indicator,
// Types
SystemStyleProp,
// Utils
};
<file_sep>/tsconfig.json
{
"compilerOptions": {
// Signifies which target of JavaScript should be emitted?
"target": "ES2015",
// What module format should be emitted?
"module": "ES2015",
// See: https://github.com/Microsoft/TypeScript-Handbook/blob/master/pages/Module%20Resolution.md
"moduleResolution": "node",
// Output destination
"outDir": "dist",
// This lib uses JSX, so support it
"jsx": "react",
// Allow default imports from modules with no default export. This does not affect code emit, just typechecking.
"esModuleInterop": true,
// Don't typecheck libraries in node_modules
"skipLibCheck": true,
// Export type declarations and only type declrations. No extra source files to dist.
"emitDeclarationOnly": true,
"declaration": true,
// Enables --noImplicitAny, --dnoImplicitThis, --alwaysStrict, --strictBindCallApply, --strictNullChecks, --strictFunctionTypes and --strictPropertyInitialization.
"strict": true,
// Minor style enforcements
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
// The following can be set to false in development to make prototyping easier.
"noUnusedLocals": true,
"noUnusedParameters": true
},
"files": ["src/index.tsx"]
}
<file_sep>/scripts/temp_migrate.js
const fs = require("fs");
const path = require("path");
const src = __dirname + "/../src";
const exclude = [
".DS_Store",
"util.ts",
"index.tsx",
"index.ts",
"iconIndex.tsx",
];
const include = [".tsx"];
const excludeExt = [".json", ".md"];
const basicDocjs = (name) => `<${name}> </${name}>`;
const basicReadme = (name) => `
# ${name}
## Purpose
## Usage
### Related
| Library | Github | NPM |
| ------------ | ----------------------------------------- | ------------------------------------------------ |
| indigo-light | https://www.github.com/urbit/indigo-light | https://www.npmjs.com/package/@tlon/indigo-light |
| indigo-dark | https://www.github.com/urbit/indigo-dark | https://www.npmjs.com/package/@tlon/indigo-dark |
| indigo-react | https://www.github.com/urbit/indigo-react | https://www.npmjs.com/package/@tlon/indigo-react |
### License
MIT License © [Tlon](https://tlon.io)
`;
const sourceFiles = fs
.readdirSync(src)
.map((sourcePath) => path.parse(sourcePath))
// .filter((parsedPath) => include.includes(parsedPath.ext))
.filter((parsedPath) => !exclude.includes(parsedPath.base))
.filter((parsedPath) => !excludeExt.includes(parsedPath.ext));
// sourceFiles.map((parsedPath) => fs.mkdirSync(src + "/" + parsedPath.name));
console.log(sourceFiles);
sourceFiles.map((parsedPath) => {
// const oldPath = src + "/" + parsedPath.base;
// const newPath = src + "/" + parsedPath.name + "/" + parsedPath.base;
// console.log(oldPath, newPath);
// fs.renameSync(oldPath, newPath, function (err) {
// if (err) throw err;
// // console.log('Successfully renamed - AKA moved!')
// });
// const readmePath = src + "/" + parsedPath.name + "/" + "README.md";
const docsJsonPath = src + "/" + parsedPath.name + "/" + "docs.json";
const docsJsPath = src + "/" + parsedPath.name + "/" + "docs.js";
if (fs.existsSync(docsJsonPath)) {
fs.unlinkSync(docsJsonPath);
}
// fs.writeFileSync(readmePath, basicReadme(parsedPath.name), "utf8");
if (fs.existsSync(docsJsPath)) {
// do something
} else {
fs.writeFileSync(docsJsPath, basicDocjs(parsedPath.name), "utf8");
}
});
// console.log(sourceFiles)
<file_sep>/README.md
# indigo-react
[](https://www.npmjs.com/package/@tlon/indigo-react)
Indigo React is a component library for implementing the [Indigo Design System](<https://www.figma.com/community/file/822953707012850361/Indigo-(alpha)>). It's built with React, [styled-components](https://styled-components.com) and [styled-system](https://styled-system.com). It also uses [Formik](https://formik.org/) and [Reach-UI](https://reach.tech/).
## Quick Start
1. Install the library
```bash
npm install --save @tlon/indigo-react
```
2. Install peer dependencies
```bash
npm install --save @tlon/indigo-light styled-components styled-system react react-dom @reach/disclosure @reach/menu-button @reach/tabs markdown-to-jsx formik
```
If you are using Typescript, install the type definitions for several of these libraries.
```bash
npm install --save @types/styled-components @types/styled-system @types/styled-system__css
```
3. Install a theme
```bash
npm install --save @tlon/indigo-light @tlon/indigo-dark
```
## Basic Usage
```js
import * as React from "react";
import { ThemeProvider } from "styled-system";
import { Text, Reset } from "@tlon/indigo-react";
import light from "@tlon/indigo-light";
class App extends React.Component {
render() {
return (
<ThemeProvider theme={light}>
<Reset />
<Text fontSize="2">Indigo!</Text>
</ThemeProvider>
);
}
}
```
In the above, we are wrapping our application in styled-component's `ThemeProvider` and passing in our `theme` from `@tlon/indigo-light`. In practice, you should rarely need to import the theme.
The `<Text />` component accepts a fontSize prop, which is one of many style props provided by `styled-system`. Using VSCode is the best way to see the list of props each component can accept.
You can also check out the [styled-system docs](https://styled-system.com/api) for a breakdown of props.
Many of these props have corrosponding styling shortcuts, drawn from the provided theme, like `@tlon/indigo-light`. These shortcuts are also provided by `styled-system`. To see how props map to values in our theme, check out [styled-system's mapping](https://styled-system.com/table).
Take a look at the [theme](https://www.github.com/urbit/indigo-light) to get a sense for which style values can be accessed from styled props.
## Development
See [DEVELOPMENT.md](https://github.com/urbit/indigo-react/blob/master/DEVELOPMENT.md) for example cases of component patterns used to create Indigo.
### Related
| Library | Github | NPM |
| ------------ | ----------------------------------------- | ------------------------------------------------ |
| indigo-light | https://www.github.com/urbit/indigo-light | https://www.npmjs.com/package/@tlon/indigo-light |
| indigo-dark | https://www.github.com/urbit/indigo-dark | https://www.npmjs.com/package/@tlon/indigo-dark |
| indigo-react | https://www.github.com/urbit/indigo-react | https://www.npmjs.com/package/@tlon/indigo-react |
### License
MIT License © [Tlon](https://tlon.io)
<file_sep>/src/themes/dark.ts
import baseStyled, { ThemedStyledInterface } from "styled-components";
const base = {
white: "rgba(255,255,255,1)",
black: "rgba(26,26,26,1)",
red: "rgba(255,65,54,1)",
yellow: "rgba(255,199,0,1)",
green: "rgba(0,159,101,1)",
blue: "rgba(0,142,255,1)",
};
const scales = {
black05: "rgba(255,255,255,0.05)",
black10: "rgba(255,255,255,0.1)",
black20: "rgba(255,255,255,0.2)",
black30: "rgba(255,255,255,0.3)",
black40: "rgba(255,255,255,0.4)",
black50: "rgba(255,255,255,0.5)",
black60: "rgba(255,255,255,0.6)",
black70: "rgba(255,255,255,0.7)",
black80: "rgba(255,255,255,0.8)",
black90: "rgba(255,255,255,0.9)",
black100: "rgba(255,255,255,1)",
white05: "rgba(0,0,0,0.05)",
white10: "rgba(0,0,0,0.1)",
white20: "rgba(0,0,0,0.2)",
white30: "rgba(0,0,0,0.3)",
white40: "rgba(0,0,0,0.4)",
white50: "rgba(0,0,0,0.5)",
white60: "rgba(0,0,0,0.6)",
white70: "rgba(0,0,0,0.7)",
white80: "rgba(0,0,0,0.8)",
white90: "rgba(0,0,0,0.9)",
white100: "rgba(0,0,0,1)",
red05: "rgba(255,65,54,0.05)",
red10: "rgba(255,65,54,0.1)",
red20: "rgba(255,65,54,0.2)",
red30: "rgba(255,65,54,0.3)",
red40: "rgba(255,65,54,0.4)",
red50: "rgba(255,65,54,0.5)",
red60: "rgba(255,65,54,0.6)",
red70: "rgba(255,65,54,0.7)",
red80: "rgba(255,65,54,0.8)",
red90: "rgba(255,65,54,0.9)",
red100: "rgba(255,65,54,1)",
yellow05: "rgba(255,199,0,0.05)",
yellow10: "rgba(255,199,0,0.1)",
yellow20: "rgba(255,199,0,0.2)",
yellow30: "rgba(255,199,0,0.3)",
yellow40: "rgba(255,199,0,0.4)",
yellow50: "rgba(255,199,0,0.5)",
yellow60: "rgba(255,199,0,0.6)",
yellow70: "rgba(255,199,0,0.7)",
yellow80: "rgba(255,199,0,0.8)",
yellow90: "rgba(255,199,0,0.9)",
yellow100: "rgba(255,199,0,1)",
green05: "rgba(0,159,101,0.05)",
green10: "rgba(0,159,101,0.1)",
green20: "rgba(0,159,101,0.2)",
green30: "rgba(0,159,101,0.3)",
green40: "rgba(0,159,101,0.4)",
green50: "rgba(0,159,101,0.5)",
green60: "rgba(0,159,101,0.6)",
green70: "rgba(0,159,101,0.7)",
green80: "rgba(0,159,101,0.8)",
green90: "rgba(0,159,101,0.9)",
green100: "rgba(0,159,101,1)",
blue05: "rgba(0,142,255,0.05)",
blue10: "rgba(0,142,255,0.1)",
blue20: "rgba(0,142,255,0.2)",
blue30: "rgba(0,142,255,0.3)",
blue40: "rgba(0,142,255,0.4)",
blue50: "rgba(0,142,255,0.5)",
blue60: "rgba(0,142,255,0.6)",
blue70: "rgba(0,142,255,0.7)",
blue80: "rgba(0,142,255,0.8)",
blue90: "rgba(0,142,255,0.9)",
blue100: "rgba(0,142,255,1)",
};
const util = {
cyan: "#00FFFF",
magenta: "#FF00FF",
yellow: "#FFFF00",
black: "#000000",
};
export const dark = {
colors: {
white: base.black,
black: base.white,
gray: scales.black60,
lightGray: scales.black30,
washedGray: scales.black10,
red: base.red,
lightRed: scales.red30,
washedRed: scales.red10,
yellow: base.yellow,
lightYellow: scales.yellow30,
washedYellow: scales.yellow10,
green: base.green,
lightGreen: scales.green30,
washedGreen: scales.green10,
blue: base.blue,
lightBlue: scales.blue30,
washedBlue: scales.blue10,
none: "rgba(0,0,0,0)",
scales: scales,
util: util,
},
fonts: {
sans: `"Inter", "Inter UI", -apple-system, BlinkMacSystemFont, 'San Francisco', 'Helvetica Neue', Arial, sans-serif`,
mono: `"Source Code Pro", "Roboto mono", "Courier New", monospace`,
},
// font-size
fontSizes: [
12, // 0
14, // 1
16, // 2
20, // 3
24, // 4
32, // 5
48, // 6
64, // 7
],
// font-weight
fontWeights: {
thin: 300,
regular: 400,
bold: 500,
},
// line-height
lineHeights: {
min: 1.2,
short: 1.33334,
regular: 1.5,
tall: 1.66667,
},
// border, border-top, border-right, border-bottom, border-left
borders: ["none", "1px solid"],
// margin, margin-top, margin-right, margin-bottom, margin-left, padding, padding-top, padding-right, padding-bottom, padding-left, grid-gap, grid-column-gap, grid-row-gap
space: [
0, // 0
4, // 1
8, // 2
16, // 3
24, // 4
32, // 5
48, // 6
64, // 7
96, // 8
],
// border-radius
radii: [
0, // 0
2, // 1
4, // 2
8, // 3
],
// width, height, min-width, max-width, min-height, max-height
sizes: [
0, // 0
4, // 1
8, // 2
16, // 3
24, // 4
32, // 5
48, // 6
64, // 7
96, // 8
],
// z-index
zIndices: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
breakpoints: ["768px", "1024px", "1440px", "2200px"],
};
export type Theme = typeof dark;
export const styled = baseStyled as ThemedStyledInterface<Theme>;
<file_sep>/docs/src/constants.ts
export const links = {
reactNPM: "https://www.npmjs.com/package/@tlon/indigo-react",
reactGithub: "https://github.com/urbit/indigo-react",
tokensNPM: "https://www.npmjs.com/package/@tlon/indigo-light",
tokensGithub: "https://github.com/urbit/indigo-tokens",
figma: "https://www.figma.com/file/H1RAHV4KscSTnvrIiL0z8C/Indigo",
};
// @ts-ignore
export const baseURL =
process.env.NODE_ENV === "development"
? "http://localhost:1234"
: "https://indigo.urbit.org";
// @ts-ignore
// export const assetUrl = process.env.NODE_ENV === 'development'
// ? 'http://localhost:1234'
// : 'https://indigo.urbit.org'
<file_sep>/src/system/unions.ts
import {
background,
border,
color,
flexbox,
grid,
textAlign,
opacity,
layout,
position,
shadow,
space,
typography,
system,
BackgroundProps,
BorderProps,
ColorProps,
FlexboxProps,
GridProps,
LayoutProps,
PositionProps,
ShadowProps,
SpaceProps,
TypographyProps,
OpacityProps,
OverflowProps,
TextAlignProps,
} from "styled-system";
export type SystemProps = {
cursor?: string;
textOverflow?: string;
whiteSpace?: string;
textTransform?: string;
};
export type AllSystemProps = SystemProps &
BackgroundProps &
BorderProps &
ColorProps &
FlexboxProps &
GridProps &
LayoutProps &
PositionProps &
ShadowProps &
SpaceProps &
OpacityProps &
OverflowProps &
TextAlignProps &
TypographyProps;
export const allSystemStyle = [
background,
border,
color,
flexbox,
grid,
textAlign,
opacity,
layout,
position,
shadow,
space,
typography,
system({
cursor: true,
textOverflow: true,
whiteSpace: true,
textTransform: true,
}),
];
export type CommonStyleProps = SystemProps &
BorderProps &
ColorProps &
FlexboxProps &
GridProps &
LayoutProps &
SpaceProps &
TypographyProps;
export const commonStyle = [
border,
color,
flexbox,
grid,
layout,
space,
typography,
];
export type CosmeticProps = SystemProps &
BackgroundProps &
BorderProps &
ColorProps &
ShadowProps &
OpacityProps;
export const cosmeticStyle = [
background,
border,
color,
opacity,
shadow,
system({
cursor: true,
}),
];
export type StructureProps = SystemProps &
BorderProps &
FlexboxProps &
GridProps &
LayoutProps &
PositionProps &
SpaceProps &
OverflowProps;
export const structureStyle = [
border,
flexbox,
grid,
layout,
position,
space,
system({
cursor: true,
}),
];
export type TypographicProps = ColorProps &
TextAlignProps &
TypographyProps & {
textOverflow?: string;
whiteSpace?: string;
textTransform?: string;
};
export const typographicStyle = [
color,
textAlign,
typography,
system({
cursor: true,
textOverflow: true,
whiteSpace: true,
textTransform: true,
}),
];
export const listStyle = [...allSystemStyle, system({ listStyle: true })];
export type ListProps = AllSystemProps & {
listStyle?: string;
}
| 3536848bb0d23238b1841f43c522d562822dcf0c | [
"Markdown",
"TypeScript",
"JSON with Comments",
"JavaScript"
] | 10 | TypeScript | urbit/indigo-react | 0c10f7c2062702a9440e97c0cacd01aa78b7f350 | 3692c1c0ef9f01baf21b2d02d93aaf55e81b412e | |
refs/heads/master | <file_sep>$(function () {
$("#radio").buttonset();
$("input").click(function (event) {
initialize($("input").index(this) + 1);
});
//User selects with whom to play Tic-Tac-Toe
var option;
function initialize(player) {
option = player;
}
//The method below is called when a canvas is clicked
$("canvas").click(function (event) {
clicked($("canvas").index(this));
});
$("#newGame")
.button()
.click(function (event) {
event.preventDefault();
newGame();
});
//Some Global Variables
game = {
drawnNum: 0,
firstCanvasClicked: null,
originalTurn: 1,
squaresFilled: 0,
turn: 1,
winners: false,
}
x = {
winCountFriend: 0,
winCountAI: 0,
winCountUnbeatableAI: 0,
}
o = {
winCountFriend: 0,
winCountAI: 0,
winCountUnbeatableAI: 0,
}
//creates an array for all nine boxes
canvas = new Array();
for (i = 0; i < 9; i++) {
canvas[i] = i;
}
//winning combinatios
var win = ["012", "345", "678", "036", "147", "258", "048", "246"];
//Function when a square on the grid is clicked
function clicked(canvasNumber) {
if (game.winners === false) {
if (option === 1 || option === 2 || option === 3) {
$('#status').text("");
if (game.turn % 2 === 0) {
$("#XorO").html("X's Turn");
} else {
$("#XorO").html("O's Turn");
}
if (game.turn === 1) {
game.firstCanvasClicked = canvasNumber;
}
if (canvas[canvasNumber] === "X" || canvas[canvasNumber] === "O") {
alert('This square is already taken! Choose another :)');
} else if (option === 1) {
var playerTurn = game.turn % 2;
if (playerTurn === 1) {
draw(canvasNumber, "X");
checkForWinnersAndDraws("X");
} else {
draw(canvasNumber, "O");
checkForWinnersAndDraws("O");
}
} else if (option === 2) {} else if (option === 3) {
draw(canvasNumber, "X");
checkForWinnersAndDraws("X");
computerTurn();
checkForWinnersAndDraws("O");
}
game.turn++;
game.squaresFilled++;
}
}
}
function draw(canvasNumber, XorO) {
var canvasT = "canvas" + canvasNumber;
c = document.getElementById(canvasT).getContext("2d");
c.beginPath();
if (XorO === "X") {
c.moveTo(10, 10);
c.lineTo(90, 90);
c.moveTo(90, 10);
c.lineTo(10, 90);
c.stroke();
canvas[canvasNumber] = "X";
} else {
c.arc(50, 50, 40, 0, 2 * Math.PI);
c.stroke();
c.closePath();
canvas[canvasNumber] = "O";
game.drawnNum = 1;
}
}
function computerTurn() {
checkTwo("O");
checkForWinnersAndDraws("O");
checkTwo("X");
if (game.firstCanvasClicked === 4) {
if (canvas[2] === "X") {
if (canvas[3] === "X") {
draw(5, "O");
} else {
draw(0, "O");
}
} else {
draw(6, "O");
}
} else if (game.firstCanvasClicked === 0 || game.firstCanvasClicked === 2 || game.firstCanvasClicked === 6 || game.firstCanvasClicked === 8) {
if (canvas[0] === "X") {
draw(6, "O");
} else {
draw(4, "O");
}
}
}
function checkTwo(XorO) {
for (i = 0; i < 8; i++) {
if ((canvas[win[i].charAt(0)] === XorO) && (canvas[win[i].charAt(1)] === XorO)) {
if (canvas[win[i].charAt(2)] !== "O" && canvas[win[i].charAt(2)] !== "X") {
draw(win[i].charAt(2), "O");
break;
}
}
}
for (i = 0; i < 8; i++) {
if ((canvas[win[i].charAt(0)] === XorO) && (canvas[win[i].charAt(2)] === XorO)) {
if (canvas[win[i].charAt(1)] != "O" && canvas[win[i].charAt(1)] != "X") {
draw(win[i].charAt(1), "O");
break;
}
}
}
for (i = 0; i < 8; i++) {
if ((canvas[win[i].charAt(1)] === XorO) && (canvas[win[i].charAt(2)] === XorO)) {
if (canvas[win[i].charAt(0)] != "O" && canvas[win[i].charAt(0)] != "X") {
draw(win[i].charAt(0), "O");
break;
}
}
}
}
function checkForWinnersAndDraws(XorO) {
for (i = 0; i < 8; i++) {
if ((canvas[win[i].charAt(0)] === XorO) && (canvas[win[i].charAt(1)] === XorO) && (canvas[win[i].charAt(2)] === XorO) && game.winners !== true) {
game.winners = true;
$('#status').text(XorO + " wins! Start a new game?");
if (option === 1) {
if (XorO === "X") {
x.winCountFriend++;
$('#xWinCount').text("X wins: " + x.winCountFriend);
} else {
o.winCountFriend++;
$('#oWinCount').text("O wins: " + o.winCountFriend);
}
} else if (option === 2) {
if (XorO === "X") {
x.winCountFriend++;
$('#xWinCount').text("X wins: " + x.winCountAI);
}
} else {
o.winCountFriend++;
$('#oWinCount').text("O wins: " + o.winCountAI);
}
}
}
if (game.squaresFilled === 8 && game.winners === false) {
$('#status').text("It's a draw! Start a new game?");
}
}
function newGame() {
$('#status').text("Continue with current or choose a new opponent.");
game.originalTurn++;
if (game.originalTurn % 2 === 0) {
game.turn = 2;
} else {
game.turn = 1;
}
game.canvasFirstClicked = null;
game.drawnNum = 0;
game.squaresFilled = 0;
game.winners = false;
for (i = 0; i < 9; i++) {
canvas[i] = i;
var canvasT = "canvas" + i;
c = document.getElementById(canvasT).getContext("2d");
c.clearRect(0, 0, 200, 200);
}
}
}); | e05997bba2f606d1476819b88d1fd6ef6a605c08 | [
"JavaScript"
] | 1 | JavaScript | Dennis-Cherchenko/Tic-Tac-Toe | f700583ab6fd60032e9a75606f29b0515060087a | 195d8adb375877321120dc0db2542e6830c8b7bc | |
refs/heads/master | <repo_name>thegamingtiger4/mod1<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/procedures/CaptianrexsHelmetTickEventProcedure.java
package net.mcreator.thestarwarssagamod.procedures;
import net.minecraft.util.ResourceLocation;
import net.minecraft.server.MinecraftServer;
import net.minecraft.potion.Effects;
import net.minecraft.potion.EffectInstance;
import net.minecraft.entity.player.ServerPlayerEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.Entity;
import net.minecraft.advancements.AdvancementProgress;
import net.minecraft.advancements.Advancement;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.Map;
import java.util.Iterator;
@TheStarWarsSagaModModElements.ModElement.Tag
public class CaptianrexsHelmetTickEventProcedure extends TheStarWarsSagaModModElements.ModElement {
public CaptianrexsHelmetTickEventProcedure(TheStarWarsSagaModModElements instance) {
super(instance, 140);
}
public static void executeProcedure(Map<String, Object> dependencies) {
if (dependencies.get("entity") == null) {
if (!dependencies.containsKey("entity"))
System.err.println("Failed to load dependency entity for procedure CaptianrexsHelmetTickEvent!");
return;
}
Entity entity = (Entity) dependencies.get("entity");
if (entity instanceof PlayerEntity)
((PlayerEntity) entity).addExperienceLevel((int) 5);
if (((((entity instanceof LivingEntity) ? ((LivingEntity) entity).getTotalArmorValue() : 0) > 1) && (entity instanceof PlayerEntity))) {
if (entity instanceof ServerPlayerEntity) {
Advancement _adv = ((MinecraftServer) ((ServerPlayerEntity) entity).server).getAdvancementManager()
.getAdvancement(new ResourceLocation("minecraft:story/shiny_gear"));
AdvancementProgress _ap = ((ServerPlayerEntity) entity).getAdvancements().getProgress(_adv);
if (!_ap.isDone()) {
Iterator _iterator = _ap.getRemaningCriteria().iterator();
while (_iterator.hasNext()) {
String _criterion = (String) _iterator.next();
((ServerPlayerEntity) entity).getAdvancements().grantCriterion(_adv, _criterion);
}
}
}
}
if (entity instanceof LivingEntity)
((LivingEntity) entity).addPotionEffect(new EffectInstance(Effects.WATER_BREATHING, (int) 60, (int) 1, (false), (false)));
if (entity instanceof LivingEntity)
((LivingEntity) entity).addPotionEffect(new EffectInstance(Effects.NIGHT_VISION, (int) 60, (int) 1, (false), (false)));
}
}
<file_sep>/models/Modellem.java
// Made with Blockbench 3.7.4
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modellem extends EntityModel<Entity> {
private final ModelRenderer body;
private final ModelRenderer rightleg;
private final ModelRenderer cube_r1;
private final ModelRenderer cube_r2;
private final ModelRenderer cube_r3;
private final ModelRenderer cube_r4;
private final ModelRenderer cube_r5;
private final ModelRenderer cube_r6;
private final ModelRenderer cube_r7;
private final ModelRenderer cube_r8;
private final ModelRenderer leftleg;
private final ModelRenderer cube_r9;
private final ModelRenderer cube_r10;
private final ModelRenderer cube_r11;
private final ModelRenderer cube_r12;
private final ModelRenderer cube_r13;
private final ModelRenderer cube_r14;
private final ModelRenderer cube_r15;
private final ModelRenderer cube_r16;
private final ModelRenderer bodycenter2;
private final ModelRenderer bodycenter3;
private final ModelRenderer bodycenter;
public Modellem() {
textureWidth = 128;
textureHeight = 128;
body = new ModelRenderer(this);
body.setRotationPoint(13.0F, 24.0F, 0.0F);
setRotationAngle(body, 0.0F, 3.1416F, 0.0F);
rightleg = new ModelRenderer(this);
rightleg.setRotationPoint(11.36F, -80.92F, -7.48F);
body.addChild(rightleg);
rightleg.setTextureOffset(0, 0).addBox(-13.36F, 78.92F, -14.52F, 2.0F, 2.0F, 24.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-15.36F, 76.92F, -14.52F, 6.0F, 2.0F, 24.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-15.36F, 78.92F, -6.52F, 6.0F, 2.0F, 24.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-11.36F, 78.92F, -14.52F, 2.0F, 2.0F, 24.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-9.36F, 78.92F, -12.52F, 2.0F, 2.0F, 20.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-7.36F, 78.92F, -10.52F, 2.0F, 2.0F, 18.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-5.36F, 78.92F, -10.52F, 2.0F, 2.0F, 16.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-15.36F, 78.92F, -14.52F, 2.0F, 2.0F, 24.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-17.36F, 78.92F, -12.52F, 2.0F, 2.0F, 20.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-19.36F, 78.92F, -10.52F, 2.0F, 2.0F, 16.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-21.36F, 78.92F, -8.52F, 2.0F, 2.0F, 12.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-15.36F, 40.92F, -20.52F, 2.0F, 28.0F, 6.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-11.36F, 40.92F, -20.52F, 2.0F, 28.0F, 6.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-13.36F, 40.92F, -18.52F, 2.0F, 6.0F, 2.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-13.36F, 12.92F, -14.52F, 2.0F, 28.0F, 2.0F, 0.0F, false);
rightleg.setTextureOffset(0, 0).addBox(-15.36F, 12.92F, -20.52F, 6.0F, 28.0F, 6.0F, 0.0F, false);
cube_r1 = new ModelRenderer(this);
cube_r1.setRotationPoint(-17.36F, 14.92F, -18.52F);
rightleg.addChild(cube_r1);
setRotationAngle(cube_r1, -0.8727F, 0.0F, 0.0F);
cube_r1.setTextureOffset(0, 0).addBox(0.0F, -8.0F, -4.0F, 2.0F, 8.0F, 6.0F, 0.0F, false);
cube_r1.setTextureOffset(0, 0).addBox(2.0F, -22.0F, -4.0F, 6.0F, 22.0F, 6.0F, 0.0F, false);
cube_r2 = new ModelRenderer(this);
cube_r2.setRotationPoint(-11.36F, 78.92F, -8.52F);
rightleg.addChild(cube_r2);
setRotationAngle(cube_r2, 0.6109F, 0.0F, 0.0F);
cube_r2.setTextureOffset(0, 0).addBox(-2.0F, -16.0F, -4.0F, 2.0F, 16.0F, 6.0F, 0.0F, false);
cube_r3 = new ModelRenderer(this);
cube_r3.setRotationPoint(-21.36F, 80.92F, 1.48F);
rightleg.addChild(cube_r3);
setRotationAngle(cube_r3, 0.0F, -1.5708F, 0.0F);
cube_r3.setTextureOffset(0, 0).addBox(-10.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r4 = new ModelRenderer(this);
cube_r4.setRotationPoint(-19.36F, 80.92F, -8.52F);
rightleg.addChild(cube_r4);
setRotationAngle(cube_r4, 0.0F, -2.3562F, 0.0F);
cube_r4.setTextureOffset(0, 0).addBox(-10.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r5 = new ModelRenderer(this);
cube_r5.setRotationPoint(-3.36F, 80.92F, -10.52F);
rightleg.addChild(cube_r5);
setRotationAngle(cube_r5, 0.0F, -0.6109F, 0.0F);
cube_r5.setTextureOffset(0, 0).addBox(-10.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r6 = new ModelRenderer(this);
cube_r6.setRotationPoint(-1.36F, 80.92F, 1.48F);
rightleg.addChild(cube_r6);
setRotationAngle(cube_r6, 0.0F, -1.5708F, 0.0F);
cube_r6.setTextureOffset(0, 0).addBox(-10.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r7 = new ModelRenderer(this);
cube_r7.setRotationPoint(-3.36F, 80.92F, 3.48F);
rightleg.addChild(cube_r7);
setRotationAngle(cube_r7, 0.0F, 0.6109F, 0.0F);
cube_r7.setTextureOffset(0, 0).addBox(-10.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r8 = new ModelRenderer(this);
cube_r8.setRotationPoint(-13.36F, 80.92F, 7.48F);
rightleg.addChild(cube_r8);
setRotationAngle(cube_r8, 0.0F, -0.6109F, 0.0F);
cube_r8.setTextureOffset(0, 0).addBox(-10.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
leftleg = new ModelRenderer(this);
leftleg.setRotationPoint(63.5217F, -80.087F, -8.7826F);
body.addChild(leftleg);
leftleg.setTextureOffset(0, 0).addBox(-11.5217F, 78.087F, -11.2174F, 2.0F, 2.0F, 22.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-15.5217F, 76.087F, -11.2174F, 6.0F, 2.0F, 22.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-15.5217F, 78.087F, -3.2174F, 6.0F, 2.0F, 22.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-13.5217F, 78.087F, -11.2174F, 2.0F, 2.0F, 22.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-7.5217F, 78.087F, -7.2174F, 2.0F, 2.0F, 16.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-9.5217F, 78.087F, -9.2174F, 2.0F, 2.0F, 16.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-15.5217F, 78.087F, -9.2174F, 2.0F, 2.0F, 18.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-17.5217F, 78.087F, -9.2174F, 2.0F, 2.0F, 18.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-19.5217F, 78.087F, -7.2174F, 2.0F, 2.0F, 14.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-15.5217F, 40.087F, -17.2174F, 2.0F, 28.0F, 6.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-11.5217F, 40.087F, -17.2174F, 2.0F, 28.0F, 6.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-13.5217F, 40.087F, -15.2174F, 2.0F, 6.0F, 2.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-13.5217F, 12.087F, -11.2174F, 2.0F, 28.0F, 2.0F, 0.0F, false);
leftleg.setTextureOffset(0, 0).addBox(-15.5217F, 12.087F, -17.2174F, 6.0F, 28.0F, 6.0F, 0.0F, false);
cube_r9 = new ModelRenderer(this);
cube_r9.setRotationPoint(-5.5217F, 12.087F, -13.2174F);
leftleg.addChild(cube_r9);
setRotationAngle(cube_r9, -0.8727F, 0.0F, 0.0F);
cube_r9.setTextureOffset(0, 0).addBox(-4.0F, -4.0F, -4.0F, 2.0F, 8.0F, 6.0F, 0.0F, false);
cube_r9.setTextureOffset(0, 0).addBox(-10.0F, -18.0F, -4.0F, 6.0F, 22.0F, 6.0F, 0.0F, false);
cube_r10 = new ModelRenderer(this);
cube_r10.setRotationPoint(-11.5217F, 76.087F, 0.7826F);
leftleg.addChild(cube_r10);
setRotationAngle(cube_r10, 0.6109F, 0.0F, 0.0F);
cube_r10.setTextureOffset(0, 0).addBox(-2.0F, -18.0F, -10.0F, 2.0F, 18.0F, 6.0F, 0.0F, false);
cube_r11 = new ModelRenderer(this);
cube_r11.setRotationPoint(6.4783F, 80.087F, 4.7826F);
leftleg.addChild(cube_r11);
setRotationAngle(cube_r11, 0.0F, 2.4435F, 0.0F);
cube_r11.setTextureOffset(0, 0).addBox(14.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r12 = new ModelRenderer(this);
cube_r12.setRotationPoint(0.4783F, 80.087F, -19.2174F);
leftleg.addChild(cube_r12);
setRotationAngle(cube_r12, 0.0F, -2.5307F, 0.0F);
cube_r12.setTextureOffset(0, 0).addBox(14.0F, -2.0F, -12.0F, 12.0F, 2.0F, 14.0F, 0.0F, false);
cube_r13 = new ModelRenderer(this);
cube_r13.setRotationPoint(-3.5217F, 80.087F, -19.2174F);
leftleg.addChild(cube_r13);
setRotationAngle(cube_r13, 0.0F, -1.5708F, 0.0F);
cube_r13.setTextureOffset(0, 0).addBox(14.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r14 = new ModelRenderer(this);
cube_r14.setRotationPoint(-19.5217F, 80.087F, -19.2174F);
leftleg.addChild(cube_r14);
setRotationAngle(cube_r14, 0.0F, -1.5708F, 0.0F);
cube_r14.setTextureOffset(0, 0).addBox(14.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
cube_r15 = new ModelRenderer(this);
cube_r15.setRotationPoint(-25.5217F, 80.087F, 20.7826F);
leftleg.addChild(cube_r15);
setRotationAngle(cube_r15, 0.0F, 0.6109F, 0.0F);
cube_r15.setTextureOffset(0, 0).addBox(16.0F, -2.0F, -14.0F, 10.0F, 2.0F, 16.0F, 0.0F, false);
cube_r16 = new ModelRenderer(this);
cube_r16.setRotationPoint(-31.5217F, 80.087F, -3.2174F);
leftleg.addChild(cube_r16);
setRotationAngle(cube_r16, 0.0F, -0.6109F, 0.0F);
cube_r16.setTextureOffset(0, 0).addBox(14.0F, -2.0F, 0.0F, 12.0F, 2.0F, 2.0F, 0.0F, false);
bodycenter2 = new ModelRenderer(this);
bodycenter2.setRotationPoint(39.0F, -78.0F, -8.0F);
body.addChild(bodycenter2);
bodycenter2.setTextureOffset(0, 0).addBox(-31.0F, -4.0F, -10.0F, 36.0F, 4.0F, 42.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(-31.0F, -20.0F, -4.0F, 2.0F, 16.0F, 34.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(3.0F, -20.0F, -4.0F, 2.0F, 16.0F, 34.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(-31.0F, -36.0F, -4.0F, 2.0F, 16.0F, 30.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(3.0F, -36.0F, -4.0F, 2.0F, 16.0F, 30.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(-29.0F, -36.0F, -4.0F, 34.0F, 32.0F, 2.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(-31.0F, -38.0F, -4.0F, 36.0F, 2.0F, 30.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(5.0F, -24.0F, 2.0F, 4.0F, 4.0F, 4.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(-39.0F, -24.0F, 2.0F, 8.0F, 4.0F, 4.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(-41.0F, -26.0F, 0.0F, 2.0F, 8.0F, 8.0F, 0.0F, false);
bodycenter2.setTextureOffset(0, 0).addBox(9.0F, -24.0F, 2.0F, 4.0F, 4.0F, 14.0F, 0.0F, false);
bodycenter3 = new ModelRenderer(this);
bodycenter3.setRotationPoint(39.0F, -108.0F, 16.0F);
body.addChild(bodycenter3);
setRotationAngle(bodycenter3, -1.3963F, 0.0F, 0.0F);
bodycenter3.setTextureOffset(0, 0).addBox(-31.0F, -4.0F, -6.0F, 36.0F, 4.0F, 38.0F, 0.0F, false);
bodycenter = new ModelRenderer(this);
bodycenter.setRotationPoint(39.0F, -78.0F, -12.0F);
body.addChild(bodycenter);
bodycenter.setTextureOffset(0, 0).addBox(-43.0F, -4.0F, 2.0F, 60.0F, 4.0F, 4.0F, 0.0F, false);
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red,
float green, float blue, float alpha) {
body.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity e) {
super.setRotationAngles(f, f1, f2, f3, f4, f5, e);
}
}<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/block/BluecraystalBlock.java
package net.mcreator.thestarwarssagamod.block;
import net.minecraftforge.registries.ObjectHolder;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.fml.event.lifecycle.FMLClientSetupEvent;
import net.minecraftforge.common.ToolType;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.gen.placement.Placement;
import net.minecraft.world.gen.placement.CountRangeConfig;
import net.minecraft.world.gen.feature.OreFeatureConfig;
import net.minecraft.world.gen.feature.OreFeature;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.gen.ChunkGenerator;
import net.minecraft.world.dimension.DimensionType;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.IWorld;
import net.minecraft.world.IBlockReader;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.Direction;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Item;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.BlockItem;
import net.minecraft.client.renderer.RenderTypeLookup;
import net.minecraft.client.renderer.RenderType;
import net.minecraft.block.material.PushReaction;
import net.minecraft.block.material.MaterialColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.SoundType;
import net.minecraft.block.Blocks;
import net.minecraft.block.BlockState;
import net.minecraft.block.Block;
import net.mcreator.thestarwarssagamod.itemgroup.MoneyItemGroup;
import net.mcreator.thestarwarssagamod.item.BluekybershardItem;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.Random;
import java.util.List;
import java.util.Collections;
@TheStarWarsSagaModModElements.ModElement.Tag
public class BluecraystalBlock extends TheStarWarsSagaModModElements.ModElement {
@ObjectHolder("the_star_wars_saga_mod:bluecraystal")
public static final Block block = null;
public BluecraystalBlock(TheStarWarsSagaModModElements instance) {
super(instance, 165);
}
@Override
public void initElements() {
elements.blocks.add(() -> new CustomBlock());
elements.items.add(() -> new BlockItem(block, new Item.Properties().group(MoneyItemGroup.tab)).setRegistryName(block.getRegistryName()));
}
@Override
@OnlyIn(Dist.CLIENT)
public void clientLoad(FMLClientSetupEvent event) {
RenderTypeLookup.setRenderLayer(block, RenderType.getCutout());
}
public static class CustomBlock extends Block {
public CustomBlock() {
super(Block.Properties.create(Material.ROCK).sound(SoundType.GLASS).hardnessAndResistance(1f, 10f).lightValue(0).harvestLevel(2)
.harvestTool(ToolType.PICKAXE).notSolid().tickRandomly());
setRegistryName("bluecraystal");
}
@OnlyIn(Dist.CLIENT)
@Override
public boolean isEmissiveRendering(BlockState blockState) {
return true;
}
@Override
public float[] getBeaconColorMultiplier(BlockState state, IWorldReader world, BlockPos pos, BlockPos beaconPos) {
return new float[]{0f, 0.36862745098f, 0.729411764706f};
}
@Override
public boolean isNormalCube(BlockState state, IBlockReader worldIn, BlockPos pos) {
return false;
}
@Override
public boolean propagatesSkylightDown(BlockState state, IBlockReader reader, BlockPos pos) {
return true;
}
@Override
public float getEnchantPowerBonus(BlockState state, IWorldReader world, BlockPos pos) {
return 10f;
}
@Override
public boolean isReplaceable(BlockState state, BlockItemUseContext context) {
return true;
}
@Override
public MaterialColor getMaterialColor(BlockState state, IBlockReader blockAccess, BlockPos pos) {
return MaterialColor.ICE;
}
@Override
public Block.OffsetType getOffsetType() {
return Block.OffsetType.XYZ;
}
@Override
public PushReaction getPushReaction(BlockState state) {
return PushReaction.DESTROY;
}
@Override
public boolean canConnectRedstone(BlockState state, IBlockReader world, BlockPos pos, Direction side) {
return true;
}
@Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
List<ItemStack> dropsOriginal = super.getDrops(state, builder);
if (!dropsOriginal.isEmpty())
return dropsOriginal;
return Collections.singletonList(new ItemStack(BluekybershardItem.block, (int) (1)));
}
}
@Override
public void init(FMLCommonSetupEvent event) {
for (Biome biome : ForgeRegistries.BIOMES.getValues()) {
biome.addFeature(GenerationStage.Decoration.UNDERGROUND_ORES, new OreFeature(OreFeatureConfig::deserialize) {
@Override
public boolean place(IWorld world, ChunkGenerator generator, Random rand, BlockPos pos, OreFeatureConfig config) {
DimensionType dimensionType = world.getDimension().getType();
boolean dimensionCriteria = false;
if (dimensionType == DimensionType.THE_NETHER)
dimensionCriteria = true;
if (!dimensionCriteria)
return false;
return super.place(world, generator, rand, pos, config);
}
}.withConfiguration(new OreFeatureConfig(OreFeatureConfig.FillerBlockType.create("bluecraystal", "bluecraystal", blockAt -> {
boolean blockCriteria = false;
if (blockAt.getBlock() == Blocks.STONE.getDefaultState().getBlock())
blockCriteria = true;
return blockCriteria;
}), block.getDefaultState(), 16)).withPlacement(Placement.COUNT_RANGE.configure(new CountRangeConfig(3, 0, 0, 64))));
}
}
}
<file_sep>/models/Modeltank.java
// Made with Blockbench 3.7.4
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modeltank extends EntityModel<Entity> {
private final ModelRenderer tank;
private final ModelRenderer body;
private final ModelRenderer cube_r1;
private final ModelRenderer cube_r2;
private final ModelRenderer cube_r3;
private final ModelRenderer cube_r4;
private final ModelRenderer cube_r5;
private final ModelRenderer cube_r6;
private final ModelRenderer cube_r7;
private final ModelRenderer cube_r8;
private final ModelRenderer cube_r9;
private final ModelRenderer cube_r10;
private final ModelRenderer cube_r11;
private final ModelRenderer cube_r12;
private final ModelRenderer cube_r13;
private final ModelRenderer cube_r14;
private final ModelRenderer cube_r15;
public Modeltank() {
textureWidth = 512;
textureHeight = 512;
tank = new ModelRenderer(this);
tank.setRotationPoint(0.0F, 24.0F, 0.0F);
body = new ModelRenderer(this);
body.setRotationPoint(0.0F, 0.0F, 0.0F);
tank.addChild(body);
body.setTextureOffset(172, 0).addBox(-11.0F, -19.0F, -8.0F, 22.0F, 19.0F, 16.0F, 0.0F, false);
body.setTextureOffset(172, 35).addBox(-15.0F, -26.0F, -5.0F, 30.0F, 1.0F, 15.0F, 0.0F, false);
body.setTextureOffset(0, 76).addBox(11.0F, -10.0F, -29.0F, 4.0F, 10.0F, 22.0F, 0.0F, false);
body.setTextureOffset(0, 36).addBox(-15.0F, -10.0F, -29.0F, 4.0F, 10.0F, 22.0F, 0.0F, false);
body.setTextureOffset(146, 162).addBox(-11.0F, -10.0F, -29.0F, 22.0F, 10.0F, 30.0F, 0.0F, false);
body.setTextureOffset(0, 108).addBox(10.0F, -22.0F, -7.0F, 5.0F, 7.0F, 8.0F, 0.0F, false);
body.setTextureOffset(109, 6).addBox(10.0F, -24.0F, -6.0F, 5.0F, 3.0F, 8.0F, 0.0F, false);
body.setTextureOffset(26, 109).addBox(10.0F, -25.0F, -5.0F, 5.0F, 3.0F, 8.0F, 0.0F, false);
body.setTextureOffset(86, 6).addBox(-15.0F, -25.0F, -5.0F, 5.0F, 3.0F, 13.0F, 0.0F, false);
body.setTextureOffset(30, 76).addBox(-15.0F, -23.0F, -6.0F, 5.0F, 3.0F, 14.0F, 0.0F, false);
body.setTextureOffset(30, 36).addBox(-15.0F, -22.0F, -7.0F, 5.0F, 7.0F, 15.0F, 0.0F, false);
body.setTextureOffset(0, 36).addBox(-11.0F, -25.0F, 0.0F, 1.0F, 6.0F, 8.0F, 0.0F, false);
body.setTextureOffset(104, 39).addBox(10.0F, -25.0F, 0.0F, 5.0F, 10.0F, 8.0F, 0.0F, false);
body.setTextureOffset(103, 94).addBox(-18.0F, -15.0F, -2.0F, 7.0F, 3.0F, 3.0F, 0.0F, false);
body.setTextureOffset(0, 50).addBox(11.0F, -15.0F, -2.0F, 7.0F, 3.0F, 3.0F, 0.0F, false);
body.setTextureOffset(86, 86).addBox(-15.0F, -25.0F, 8.0F, 30.0F, 7.0F, 1.0F, 0.0F, false);
body.setTextureOffset(86, 6).addBox(-18.0F, -6.0F, -61.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
body.setTextureOffset(86, 86).addBox(9.0F, -6.0F, -61.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
cube_r1 = new ModelRenderer(this);
cube_r1.setRotationPoint(13.0F, -1.0F, -26.0F);
body.addChild(cube_r1);
setRotationAngle(cube_r1, 0.0F, 0.0F, -0.6109F);
cube_r1.setTextureOffset(0, 76).addBox(-1.0F, -5.0F, -40.0F, 4.0F, 6.0F, 5.0F, 0.0F, false);
cube_r2 = new ModelRenderer(this);
cube_r2.setRotationPoint(-16.0F, -2.0F, -26.0F);
body.addChild(cube_r2);
setRotationAngle(cube_r2, 0.0F, 0.0F, 0.6109F);
cube_r2.setTextureOffset(0, 87).addBox(-1.0F, -5.0F, -40.0F, 4.0F, 6.0F, 5.0F, 0.0F, false);
cube_r3 = new ModelRenderer(this);
cube_r3.setRotationPoint(-14.0F, -26.0F, 9.0F);
body.addChild(cube_r3);
setRotationAngle(cube_r3, 0.0F, -0.3054F, 0.0F);
cube_r3.setTextureOffset(18, 36).addBox(-1.0F, -14.0F, 0.0F, 1.0F, 14.0F, 1.0F, 0.0F, false);
cube_r4 = new ModelRenderer(this);
cube_r4.setRotationPoint(12.0F, -6.0F, 0.0F);
body.addChild(cube_r4);
setRotationAngle(cube_r4, 0.0F, 0.0F, 0.2182F);
cube_r4.setTextureOffset(0, 152).addBox(-3.0F, -2.0F, -61.0F, 8.0F, 3.0F, 57.0F, 0.0F, false);
cube_r5 = new ModelRenderer(this);
cube_r5.setRotationPoint(-15.0F, -6.0F, 0.0F);
body.addChild(cube_r5);
setRotationAngle(cube_r5, 0.0F, 0.0F, -0.2182F);
cube_r5.setTextureOffset(73, 162).addBox(-3.0F, -2.0F, -61.0F, 8.0F, 3.0F, 57.0F, 0.0F, false);
cube_r6 = new ModelRenderer(this);
cube_r6.setRotationPoint(23.0F, 2.0F, 1.0F);
body.addChild(cube_r6);
setRotationAngle(cube_r6, 0.0F, 0.0F, 0.1745F);
cube_r6.setTextureOffset(0, 0).addBox(-7.0F, -6.0F, -62.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
cube_r7 = new ModelRenderer(this);
cube_r7.setRotationPoint(-18.0F, 0.0F, 1.0F);
body.addChild(cube_r7);
setRotationAngle(cube_r7, 0.0F, 0.0F, -0.1745F);
cube_r7.setTextureOffset(0, 76).addBox(-7.0F, -6.0F, -62.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
cube_r8 = new ModelRenderer(this);
cube_r8.setRotationPoint(-18.0F, -12.0F, -1.0F);
body.addChild(cube_r8);
setRotationAngle(cube_r8, -0.1745F, 0.0F, 0.0F);
cube_r8.setTextureOffset(41, 58).addBox(-1.0F, -1.0F, -10.0F, 1.0F, 1.0F, 11.0F, 0.0F, false);
cube_r8.setTextureOffset(101, 107).addBox(36.0F, -1.0F, -10.0F, 1.0F, 1.0F, 11.0F, 0.0F, false);
cube_r9 = new ModelRenderer(this);
cube_r9.setRotationPoint(-18.0F, -14.0F, -1.0F);
body.addChild(cube_r9);
setRotationAngle(cube_r9, -0.1745F, 0.0F, 0.0F);
cube_r9.setTextureOffset(86, 47).addBox(-1.0F, -1.0F, -13.0F, 1.0F, 1.0F, 14.0F, 0.0F, false);
cube_r9.setTextureOffset(38, 94).addBox(36.0F, -1.0F, -13.0F, 1.0F, 1.0F, 14.0F, 0.0F, false);
cube_r10 = new ModelRenderer(this);
cube_r10.setRotationPoint(22.0F, 4.0F, -10.0F);
body.addChild(cube_r10);
setRotationAngle(cube_r10, -0.829F, 0.0F, 0.0F);
cube_r10.setTextureOffset(86, 94).addBox(-11.0F, -19.0F, -15.0F, 4.0F, 15.0F, 9.0F, 0.0F, false);
cube_r10.setTextureOffset(86, 22).addBox(-37.0F, -19.0F, -15.0F, 4.0F, 16.0F, 9.0F, 0.0F, false);
cube_r11 = new ModelRenderer(this);
cube_r11.setRotationPoint(0.0F, 1.0F, -15.0F);
body.addChild(cube_r11);
setRotationAngle(cube_r11, -1.1345F, 0.0F, 0.0F);
cube_r11.setTextureOffset(0, 0).addBox(-11.0F, -19.0F, -15.0F, 22.0F, 27.0F, 9.0F, 0.0F, false);
cube_r12 = new ModelRenderer(this);
cube_r12.setRotationPoint(11.0F, -20.0F, -8.0F);
body.addChild(cube_r12);
setRotationAngle(cube_r12, -0.5236F, 0.0F, 0.0F);
cube_r12.setTextureOffset(0, 0).addBox(-12.0F, -6.0F, 0.0F, 2.0F, 7.0F, 1.0F, 0.0F, false);
cube_r13 = new ModelRenderer(this);
cube_r13.setRotationPoint(13.0F, -20.0F, -7.0F);
body.addChild(cube_r13);
setRotationAngle(cube_r13, -0.5236F, 0.0F, 0.0F);
cube_r13.setTextureOffset(86, 62).addBox(-12.0F, -4.0F, -1.0F, 14.0F, 4.0F, 2.0F, 0.0F, false);
cube_r13.setTextureOffset(103, 22).addBox(-28.0F, -4.0F, -1.0F, 14.0F, 4.0F, 2.0F, 0.0F, false);
cube_r14 = new ModelRenderer(this);
cube_r14.setRotationPoint(-1.0F, -24.0F, -6.0F);
body.addChild(cube_r14);
setRotationAngle(cube_r14, -0.5236F, 0.0F, 0.0F);
cube_r14.setTextureOffset(86, 0).addBox(-14.0F, -2.0F, 0.0F, 30.0F, 2.0F, 1.0F, 0.0F, false);
cube_r15 = new ModelRenderer(this);
cube_r15.setRotationPoint(-1.0F, -19.0F, -8.0F);
body.addChild(cube_r15);
setRotationAngle(cube_r15, -0.5236F, 0.0F, 0.0F);
cube_r15.setTextureOffset(86, 3).addBox(-14.0F, -2.0F, 0.0F, 30.0F, 2.0F, 1.0F, 0.0F, false);
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red,
float green, float blue, float alpha) {
tank.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity e) {
super.setRotationAngles(f, f1, f2, f3, f4, f5, e);
}
}<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/world/biome/KesselBiome.java
package net.mcreator.thestarwarssagamod.world.biome;
import net.minecraftforge.registries.ObjectHolder;
import net.minecraftforge.fml.event.lifecycle.FMLCommonSetupEvent;
import net.minecraftforge.common.BiomeManager;
import net.minecraft.world.gen.surfacebuilders.SurfaceBuilderConfig;
import net.minecraft.world.gen.surfacebuilders.SurfaceBuilder;
import net.minecraft.world.gen.placement.Placement;
import net.minecraft.world.gen.placement.FrequencyConfig;
import net.minecraft.world.gen.feature.Feature;
import net.minecraft.world.gen.GenerationStage;
import net.minecraft.world.biome.DefaultBiomeFeatures;
import net.minecraft.world.biome.Biome;
import net.mcreator.thestarwarssagamod.block.KesselsandBlock;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
@TheStarWarsSagaModModElements.ModElement.Tag
public class KesselBiome extends TheStarWarsSagaModModElements.ModElement {
@ObjectHolder("the_star_wars_saga_mod:kessel")
public static final CustomBiome biome = null;
public KesselBiome(TheStarWarsSagaModModElements instance) {
super(instance, 125);
}
@Override
public void initElements() {
elements.biomes.add(() -> new CustomBiome());
}
@Override
public void init(FMLCommonSetupEvent event) {
BiomeManager.addSpawnBiome(biome);
BiomeManager.addBiome(BiomeManager.BiomeType.DESERT, new BiomeManager.BiomeEntry(biome, 10));
}
static class CustomBiome extends Biome {
public CustomBiome() {
super(new Biome.Builder().downfall(0.1f).depth(0.1f).scale(0.2f).temperature(1.5f).precipitation(Biome.RainType.RAIN)
.category(Biome.Category.NONE).waterColor(4159204).waterFogColor(329011)
.surfaceBuilder(SurfaceBuilder.DEFAULT, new SurfaceBuilderConfig(KesselsandBlock.block.getDefaultState(),
KesselsandBlock.block.getDefaultState(), KesselsandBlock.block.getDefaultState())));
setRegistryName("kessel");
addFeature(GenerationStage.Decoration.VEGETAL_DECORATION, Feature.FLOWER.withConfiguration(DefaultBiomeFeatures.DEFAULT_FLOWER_CONFIG)
.withPlacement(Placement.COUNT_HEIGHTMAP_32.configure(new FrequencyConfig(4))));
}
}
}
<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/item/AnkinslightsaberItem.java
package net.mcreator.thestarwarssagamod.item;
import net.minecraftforge.registries.ObjectHolder;
import net.minecraft.item.crafting.Ingredient;
import net.minecraft.item.SwordItem;
import net.minecraft.item.Item;
import net.minecraft.item.IItemTier;
import net.mcreator.thestarwarssagamod.itemgroup.Legoin501ItemGroup;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
@TheStarWarsSagaModModElements.ModElement.Tag
public class AnkinslightsaberItem extends TheStarWarsSagaModModElements.ModElement {
@ObjectHolder("the_star_wars_saga_mod:ankinslightsaber")
public static final Item block = null;
public AnkinslightsaberItem(TheStarWarsSagaModModElements instance) {
super(instance, 145);
}
@Override
public void initElements() {
elements.items.add(() -> new SwordItem(new IItemTier() {
public int getMaxUses() {
return 11400;
}
public float getEfficiency() {
return 5.5f;
}
public float getAttackDamage() {
return 15.5f;
}
public int getHarvestLevel() {
return 6;
}
public int getEnchantability() {
return 6;
}
public Ingredient getRepairMaterial() {
return Ingredient.EMPTY;
}
}, 3, -0.0000000000000004f, new Item.Properties().group(Legoin501ItemGroup.tab)) {
}.setRegistryName("ankinslightsaber"));
}
}
<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/entity/Ttank1Entity.java
package net.mcreator.thestarwarssagamod.entity;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraft.world.World;
import net.minecraft.world.IWorldReader;
import net.minecraft.util.math.shapes.VoxelShapes;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Hand;
import net.minecraft.util.DamageSource;
import net.minecraft.tags.FluidTags;
import net.minecraft.pathfinding.SwimmerPathNavigator;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.network.IPacket;
import net.minecraft.item.SpawnEggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.Item;
import net.minecraft.entity.projectile.PotionEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.ai.goal.SwimGoal;
import net.minecraft.entity.ai.controller.MovementController;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.Entity;
import net.minecraft.entity.CreatureEntity;
import net.minecraft.entity.CreatureAttribute;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.client.renderer.entity.model.EntityModel;
import net.minecraft.client.renderer.entity.MobRenderer;
import net.minecraft.block.BlockState;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.Random;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import com.mojang.blaze3d.matrix.MatrixStack;
@TheStarWarsSagaModModElements.ModElement.Tag
public class Ttank1Entity extends TheStarWarsSagaModModElements.ModElement {
public static EntityType entity = null;
public Ttank1Entity(TheStarWarsSagaModModElements instance) {
super(instance, 199);
FMLJavaModLoadingContext.get().getModEventBus().register(this);
}
@Override
public void initElements() {
entity = (EntityType.Builder.<CustomEntity>create(CustomEntity::new, EntityClassification.MONSTER).setShouldReceiveVelocityUpdates(true)
.setTrackingRange(64).setUpdateInterval(3).setCustomClientFactory(CustomEntity::new).size(0.6f, 1.8f)).build("ttank_1")
.setRegistryName("ttank_1");
elements.entities.add(() -> entity);
elements.items.add(() -> new SpawnEggItem(entity, -1, -1, new Item.Properties().group(ItemGroup.MISC)).setRegistryName("ttank_1_spawn_egg"));
}
@SubscribeEvent
@OnlyIn(Dist.CLIENT)
public void registerModels(ModelRegistryEvent event) {
RenderingRegistry.registerEntityRenderingHandler(entity, renderManager -> {
return new MobRenderer(renderManager, new Modeltank(), 0.5f) {
@Override
public ResourceLocation getEntityTexture(Entity entity) {
return new ResourceLocation("the_star_wars_saga_mod:textures/vechclietank_tyank_tank_tank_tank.png");
}
};
});
}
public static class CustomEntity extends CreatureEntity {
public CustomEntity(FMLPlayMessages.SpawnEntity packet, World world) {
this(entity, world);
}
public CustomEntity(EntityType<CustomEntity> type, World world) {
super(type, world);
experienceValue = 0;
setNoAI(false);
enablePersistence();
this.moveController = new MovementController(this) {
@Override
public void tick() {
if (CustomEntity.this.areEyesInFluid(FluidTags.WATER))
CustomEntity.this.setMotion(CustomEntity.this.getMotion().add(0, 0.005, 0));
if (this.action == MovementController.Action.MOVE_TO && !CustomEntity.this.getNavigator().noPath()) {
double dx = this.posX - CustomEntity.this.getPosX();
double dy = this.posY - CustomEntity.this.getPosY();
double dz = this.posZ - CustomEntity.this.getPosZ();
dy = dy / (double) MathHelper.sqrt(dx * dx + dy * dy + dz * dz);
CustomEntity.this.rotationYaw = this.limitAngle(CustomEntity.this.rotationYaw,
(float) (MathHelper.atan2(dz, dx) * (double) (180 / (float) Math.PI)) - 90, 90);
CustomEntity.this.renderYawOffset = CustomEntity.this.rotationYaw;
CustomEntity.this.setAIMoveSpeed(MathHelper.lerp(0.125f, CustomEntity.this.getAIMoveSpeed(),
(float) (this.speed * CustomEntity.this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getValue())));
CustomEntity.this.setMotion(CustomEntity.this.getMotion().add(0, CustomEntity.this.getAIMoveSpeed() * dy * 0.1, 0));
} else {
CustomEntity.this.setAIMoveSpeed(0);
}
}
};
this.navigator = new SwimmerPathNavigator(this, this.world);
}
@Override
public IPacket<?> createSpawnPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
@Override
protected void registerGoals() {
super.registerGoals();
this.goalSelector.addGoal(1, new SwimGoal(this));
}
@Override
public CreatureAttribute getCreatureAttribute() {
return CreatureAttribute.UNDEFINED;
}
@Override
public boolean canDespawn(double distanceToClosestPlayer) {
return false;
}
@Override
public void playStepSound(BlockPos pos, BlockState blockIn) {
this.playSound(
(net.minecraft.util.SoundEvent) ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation("the_star_wars_saga_mod:speeder")),
0.15f, 1);
}
@Override
public net.minecraft.util.SoundEvent getHurtSound(DamageSource ds) {
return (net.minecraft.util.SoundEvent) ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation("entity.generic.hurt"));
}
@Override
public net.minecraft.util.SoundEvent getDeathSound() {
return (net.minecraft.util.SoundEvent) ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation("entity.generic.death"));
}
@Override
public boolean attackEntityFrom(DamageSource source, float amount) {
if (source.getImmediateSource() instanceof PotionEntity)
return false;
if (source == DamageSource.CACTUS)
return false;
if (source == DamageSource.DROWN)
return false;
return super.attackEntityFrom(source, amount);
}
@Override
public boolean processInteract(PlayerEntity sourceentity, Hand hand) {
ItemStack itemstack = sourceentity.getHeldItem(hand);
boolean retval = true;
super.processInteract(sourceentity, hand);
sourceentity.startRiding(this);
double x = this.getPosX();
double y = this.getPosY();
double z = this.getPosZ();
Entity entity = this;
return retval;
}
@Override
protected void registerAttributes() {
super.registerAttributes();
if (this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED) != null)
this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(3);
if (this.getAttribute(SharedMonsterAttributes.MAX_HEALTH) != null)
this.getAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(24);
if (this.getAttribute(SharedMonsterAttributes.ARMOR) != null)
this.getAttribute(SharedMonsterAttributes.ARMOR).setBaseValue(10);
if (this.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE) == null)
this.getAttributes().registerAttribute(SharedMonsterAttributes.ATTACK_DAMAGE);
this.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(3);
}
@Override
public boolean canBreatheUnderwater() {
return true;
}
@Override
public boolean isNotColliding(IWorldReader worldreader) {
return worldreader.checkNoEntityCollision(this, VoxelShapes.create(this.getBoundingBox()));
}
@Override
public boolean isPushedByWater() {
return false;
}
@Override
public void travel(Vec3d dir) {
Entity entity = this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0);
if (this.isBeingRidden()) {
this.rotationYaw = entity.rotationYaw;
this.prevRotationYaw = this.rotationYaw;
this.rotationPitch = entity.rotationPitch * 0.5F;
this.setRotation(this.rotationYaw, this.rotationPitch);
this.jumpMovementFactor = this.getAIMoveSpeed() * 0.15F;
this.renderYawOffset = entity.rotationYaw;
this.rotationYawHead = entity.rotationYaw;
this.stepHeight = 1.0F;
if (entity instanceof LivingEntity) {
this.setAIMoveSpeed((float) this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getValue());
float forward = ((LivingEntity) entity).moveForward;
float strafe = ((LivingEntity) entity).moveStrafing;
super.travel(new Vec3d(strafe, 0, forward));
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.getPosX() - this.prevPosX;
double d0 = this.getPosZ() - this.prevPosZ;
float f1 = MathHelper.sqrt(d1 * d1 + d0 * d0) * 4.0F;
if (f1 > 1.0F)
f1 = 1.0F;
this.limbSwingAmount += (f1 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
return;
}
this.stepHeight = 0.5F;
this.jumpMovementFactor = 0.02F;
super.travel(dir);
}
public void livingTick() {
super.livingTick();
double x = this.getPosX();
double y = this.getPosY();
double z = this.getPosZ();
Random random = this.rand;
Entity entity = this;
if (true)
for (int l = 0; l < 1; ++l) {
double d0 = (x + random.nextFloat());
double d1 = (y + random.nextFloat());
double d2 = (z + random.nextFloat());
int i1 = random.nextInt(2) * 2 - 1;
double d3 = (random.nextFloat() - 0.5D) * 0.2999999985098839D;
double d4 = (random.nextFloat() - 0.5D) * 0.2999999985098839D;
double d5 = (random.nextFloat() - 0.5D) * 0.2999999985098839D;
world.addParticle(ParticleTypes.LARGE_SMOKE, d0, d1, d2, d3, d4, d5);
}
}
}
// Made with Blockbench 3.7.4
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modeltank extends EntityModel<Entity> {
private final ModelRenderer tank;
private final ModelRenderer body;
private final ModelRenderer cube_r1;
private final ModelRenderer cube_r2;
private final ModelRenderer cube_r3;
private final ModelRenderer cube_r4;
private final ModelRenderer cube_r5;
private final ModelRenderer cube_r6;
private final ModelRenderer cube_r7;
private final ModelRenderer cube_r8;
private final ModelRenderer cube_r9;
private final ModelRenderer cube_r10;
private final ModelRenderer cube_r11;
private final ModelRenderer cube_r12;
private final ModelRenderer cube_r13;
private final ModelRenderer cube_r14;
private final ModelRenderer cube_r15;
public Modeltank() {
textureWidth = 512;
textureHeight = 512;
tank = new ModelRenderer(this);
tank.setRotationPoint(0.0F, 24.0F, 0.0F);
body = new ModelRenderer(this);
body.setRotationPoint(0.0F, 0.0F, 0.0F);
tank.addChild(body);
body.setTextureOffset(172, 0).addBox(-11.0F, -19.0F, -8.0F, 22.0F, 19.0F, 16.0F, 0.0F, false);
body.setTextureOffset(172, 35).addBox(-15.0F, -26.0F, -5.0F, 30.0F, 1.0F, 15.0F, 0.0F, false);
body.setTextureOffset(0, 76).addBox(11.0F, -10.0F, -29.0F, 4.0F, 10.0F, 22.0F, 0.0F, false);
body.setTextureOffset(0, 36).addBox(-15.0F, -10.0F, -29.0F, 4.0F, 10.0F, 22.0F, 0.0F, false);
body.setTextureOffset(146, 162).addBox(-11.0F, -10.0F, -29.0F, 22.0F, 10.0F, 30.0F, 0.0F, false);
body.setTextureOffset(0, 108).addBox(10.0F, -22.0F, -7.0F, 5.0F, 7.0F, 8.0F, 0.0F, false);
body.setTextureOffset(109, 6).addBox(10.0F, -24.0F, -6.0F, 5.0F, 3.0F, 8.0F, 0.0F, false);
body.setTextureOffset(26, 109).addBox(10.0F, -25.0F, -5.0F, 5.0F, 3.0F, 8.0F, 0.0F, false);
body.setTextureOffset(86, 6).addBox(-15.0F, -25.0F, -5.0F, 5.0F, 3.0F, 13.0F, 0.0F, false);
body.setTextureOffset(30, 76).addBox(-15.0F, -23.0F, -6.0F, 5.0F, 3.0F, 14.0F, 0.0F, false);
body.setTextureOffset(30, 36).addBox(-15.0F, -22.0F, -7.0F, 5.0F, 7.0F, 15.0F, 0.0F, false);
body.setTextureOffset(0, 36).addBox(-11.0F, -25.0F, 0.0F, 1.0F, 6.0F, 8.0F, 0.0F, false);
body.setTextureOffset(104, 39).addBox(10.0F, -25.0F, 0.0F, 5.0F, 10.0F, 8.0F, 0.0F, false);
body.setTextureOffset(103, 94).addBox(-18.0F, -15.0F, -2.0F, 7.0F, 3.0F, 3.0F, 0.0F, false);
body.setTextureOffset(0, 50).addBox(11.0F, -15.0F, -2.0F, 7.0F, 3.0F, 3.0F, 0.0F, false);
body.setTextureOffset(86, 86).addBox(-15.0F, -25.0F, 8.0F, 30.0F, 7.0F, 1.0F, 0.0F, false);
body.setTextureOffset(86, 6).addBox(-18.0F, -6.0F, -61.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
body.setTextureOffset(86, 86).addBox(9.0F, -6.0F, -61.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
cube_r1 = new ModelRenderer(this);
cube_r1.setRotationPoint(13.0F, -1.0F, -26.0F);
body.addChild(cube_r1);
setRotationAngle(cube_r1, 0.0F, 0.0F, -0.6109F);
cube_r1.setTextureOffset(0, 76).addBox(-1.0F, -5.0F, -40.0F, 4.0F, 6.0F, 5.0F, 0.0F, false);
cube_r2 = new ModelRenderer(this);
cube_r2.setRotationPoint(-16.0F, -2.0F, -26.0F);
body.addChild(cube_r2);
setRotationAngle(cube_r2, 0.0F, 0.0F, 0.6109F);
cube_r2.setTextureOffset(0, 87).addBox(-1.0F, -5.0F, -40.0F, 4.0F, 6.0F, 5.0F, 0.0F, false);
cube_r3 = new ModelRenderer(this);
cube_r3.setRotationPoint(-14.0F, -26.0F, 9.0F);
body.addChild(cube_r3);
setRotationAngle(cube_r3, 0.0F, -0.3054F, 0.0F);
cube_r3.setTextureOffset(18, 36).addBox(-1.0F, -14.0F, 0.0F, 1.0F, 14.0F, 1.0F, 0.0F, false);
cube_r4 = new ModelRenderer(this);
cube_r4.setRotationPoint(12.0F, -6.0F, 0.0F);
body.addChild(cube_r4);
setRotationAngle(cube_r4, 0.0F, 0.0F, 0.2182F);
cube_r4.setTextureOffset(0, 152).addBox(-3.0F, -2.0F, -61.0F, 8.0F, 3.0F, 57.0F, 0.0F, false);
cube_r5 = new ModelRenderer(this);
cube_r5.setRotationPoint(-15.0F, -6.0F, 0.0F);
body.addChild(cube_r5);
setRotationAngle(cube_r5, 0.0F, 0.0F, -0.2182F);
cube_r5.setTextureOffset(73, 162).addBox(-3.0F, -2.0F, -61.0F, 8.0F, 3.0F, 57.0F, 0.0F, false);
cube_r6 = new ModelRenderer(this);
cube_r6.setRotationPoint(23.0F, 2.0F, 1.0F);
body.addChild(cube_r6);
setRotationAngle(cube_r6, 0.0F, 0.0F, 0.1745F);
cube_r6.setTextureOffset(0, 0).addBox(-7.0F, -6.0F, -62.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
cube_r7 = new ModelRenderer(this);
cube_r7.setRotationPoint(-18.0F, 0.0F, 1.0F);
body.addChild(cube_r7);
setRotationAngle(cube_r7, 0.0F, 0.0F, -0.1745F);
cube_r7.setTextureOffset(0, 76).addBox(-7.0F, -6.0F, -62.0F, 8.0F, 6.0F, 70.0F, 0.0F, false);
cube_r8 = new ModelRenderer(this);
cube_r8.setRotationPoint(-18.0F, -12.0F, -1.0F);
body.addChild(cube_r8);
setRotationAngle(cube_r8, -0.1745F, 0.0F, 0.0F);
cube_r8.setTextureOffset(41, 58).addBox(-1.0F, -1.0F, -10.0F, 1.0F, 1.0F, 11.0F, 0.0F, false);
cube_r8.setTextureOffset(101, 107).addBox(36.0F, -1.0F, -10.0F, 1.0F, 1.0F, 11.0F, 0.0F, false);
cube_r9 = new ModelRenderer(this);
cube_r9.setRotationPoint(-18.0F, -14.0F, -1.0F);
body.addChild(cube_r9);
setRotationAngle(cube_r9, -0.1745F, 0.0F, 0.0F);
cube_r9.setTextureOffset(86, 47).addBox(-1.0F, -1.0F, -13.0F, 1.0F, 1.0F, 14.0F, 0.0F, false);
cube_r9.setTextureOffset(38, 94).addBox(36.0F, -1.0F, -13.0F, 1.0F, 1.0F, 14.0F, 0.0F, false);
cube_r10 = new ModelRenderer(this);
cube_r10.setRotationPoint(22.0F, 4.0F, -10.0F);
body.addChild(cube_r10);
setRotationAngle(cube_r10, -0.829F, 0.0F, 0.0F);
cube_r10.setTextureOffset(86, 94).addBox(-11.0F, -19.0F, -15.0F, 4.0F, 15.0F, 9.0F, 0.0F, false);
cube_r10.setTextureOffset(86, 22).addBox(-37.0F, -19.0F, -15.0F, 4.0F, 16.0F, 9.0F, 0.0F, false);
cube_r11 = new ModelRenderer(this);
cube_r11.setRotationPoint(0.0F, 1.0F, -15.0F);
body.addChild(cube_r11);
setRotationAngle(cube_r11, -1.1345F, 0.0F, 0.0F);
cube_r11.setTextureOffset(0, 0).addBox(-11.0F, -19.0F, -15.0F, 22.0F, 27.0F, 9.0F, 0.0F, false);
cube_r12 = new ModelRenderer(this);
cube_r12.setRotationPoint(11.0F, -20.0F, -8.0F);
body.addChild(cube_r12);
setRotationAngle(cube_r12, -0.5236F, 0.0F, 0.0F);
cube_r12.setTextureOffset(0, 0).addBox(-12.0F, -6.0F, 0.0F, 2.0F, 7.0F, 1.0F, 0.0F, false);
cube_r13 = new ModelRenderer(this);
cube_r13.setRotationPoint(13.0F, -20.0F, -7.0F);
body.addChild(cube_r13);
setRotationAngle(cube_r13, -0.5236F, 0.0F, 0.0F);
cube_r13.setTextureOffset(86, 62).addBox(-12.0F, -4.0F, -1.0F, 14.0F, 4.0F, 2.0F, 0.0F, false);
cube_r13.setTextureOffset(103, 22).addBox(-28.0F, -4.0F, -1.0F, 14.0F, 4.0F, 2.0F, 0.0F, false);
cube_r14 = new ModelRenderer(this);
cube_r14.setRotationPoint(-1.0F, -24.0F, -6.0F);
body.addChild(cube_r14);
setRotationAngle(cube_r14, -0.5236F, 0.0F, 0.0F);
cube_r14.setTextureOffset(86, 0).addBox(-14.0F, -2.0F, 0.0F, 30.0F, 2.0F, 1.0F, 0.0F, false);
cube_r15 = new ModelRenderer(this);
cube_r15.setRotationPoint(-1.0F, -19.0F, -8.0F);
body.addChild(cube_r15);
setRotationAngle(cube_r15, -0.5236F, 0.0F, 0.0F);
cube_r15.setTextureOffset(86, 3).addBox(-14.0F, -2.0F, 0.0F, 30.0F, 2.0F, 1.0F, 0.0F, false);
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red, float green, float blue,
float alpha) {
tank.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void setRotationAngles(Entity e, float f, float f1, float f2, float f3, float f4) {
}
}
}
<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/procedures/ClonecommandoHelmetTickEventProcedure.java
package net.mcreator.thestarwarssagamod.procedures;
import net.minecraft.potion.Effects;
import net.minecraft.potion.EffectInstance;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.Entity;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.Map;
@TheStarWarsSagaModModElements.ModElement.Tag
public class ClonecommandoHelmetTickEventProcedure extends TheStarWarsSagaModModElements.ModElement {
public ClonecommandoHelmetTickEventProcedure(TheStarWarsSagaModModElements instance) {
super(instance, 32);
}
public static void executeProcedure(Map<String, Object> dependencies) {
if (dependencies.get("entity") == null) {
if (!dependencies.containsKey("entity"))
System.err.println("Failed to load dependency entity for procedure ClonecommandoHelmetTickEvent!");
return;
}
Entity entity = (Entity) dependencies.get("entity");
if (entity instanceof PlayerEntity)
((PlayerEntity) entity).getFoodStats().setFoodLevel((int) 20);
if (entity instanceof LivingEntity)
((LivingEntity) entity).addPotionEffect(new EffectInstance(Effects.NIGHT_VISION, (int) 60, (int) 1, (true), (false)));
}
}
<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/entity/BarcspeederEntity.java
package net.mcreator.thestarwarssagamod.entity;
import net.minecraftforge.registries.ForgeRegistries;
import net.minecraftforge.fml.network.NetworkHooks;
import net.minecraftforge.fml.network.FMLPlayMessages;
import net.minecraftforge.fml.javafmlmod.FMLJavaModLoadingContext;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.client.event.ModelRegistryEvent;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraft.world.World;
import net.minecraft.world.IWorld;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.util.math.Vec3d;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.Hand;
import net.minecraft.util.DamageSource;
import net.minecraft.particles.ParticleTypes;
import net.minecraft.network.IPacket;
import net.minecraft.nbt.CompoundNBT;
import net.minecraft.item.SpawnEggItem;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemGroup;
import net.minecraft.item.Item;
import net.minecraft.entity.projectile.PotionEntity;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.entity.passive.TameableEntity;
import net.minecraft.entity.ai.goal.RangedAttackGoal;
import net.minecraft.entity.ai.goal.OwnerHurtByTargetGoal;
import net.minecraft.entity.SpawnReason;
import net.minecraft.entity.SharedMonsterAttributes;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.IRangedAttackMob;
import net.minecraft.entity.ILivingEntityData;
import net.minecraft.entity.EntityType;
import net.minecraft.entity.EntityClassification;
import net.minecraft.entity.Entity;
import net.minecraft.entity.CreatureAttribute;
import net.minecraft.entity.AgeableEntity;
import net.minecraft.client.renderer.model.ModelRenderer;
import net.minecraft.client.renderer.entity.model.EntityModel;
import net.minecraft.client.renderer.entity.MobRenderer;
import net.minecraft.block.Blocks;
import net.minecraft.block.BlockState;
import net.mcreator.thestarwarssagamod.procedures.BarcspeederOnInitialEntitySpawnProcedure;
import net.mcreator.thestarwarssagamod.item.BowcasterItem;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.Random;
import java.util.Map;
import java.util.HashMap;
import com.mojang.blaze3d.vertex.IVertexBuilder;
import com.mojang.blaze3d.matrix.MatrixStack;
@TheStarWarsSagaModModElements.ModElement.Tag
public class BarcspeederEntity extends TheStarWarsSagaModModElements.ModElement {
public static EntityType entity = null;
public BarcspeederEntity(TheStarWarsSagaModModElements instance) {
super(instance, 81);
FMLJavaModLoadingContext.get().getModEventBus().register(this);
}
@Override
public void initElements() {
entity = (EntityType.Builder.<CustomEntity>create(CustomEntity::new, EntityClassification.CREATURE).setShouldReceiveVelocityUpdates(true)
.setTrackingRange(64).setUpdateInterval(3).setCustomClientFactory(CustomEntity::new).size(0.7999999999999999f, 2f))
.build("barcspeeder").setRegistryName("barcspeeder");
elements.entities.add(() -> entity);
elements.items
.add(() -> new SpawnEggItem(entity, -1, -1, new Item.Properties().group(ItemGroup.MISC)).setRegistryName("barcspeeder_spawn_egg"));
}
@SubscribeEvent
@OnlyIn(Dist.CLIENT)
public void registerModels(ModelRegistryEvent event) {
RenderingRegistry.registerEntityRenderingHandler(entity, renderManager -> {
return new MobRenderer(renderManager, new Modelcustomm_model(), 0.5f) {
@Override
public ResourceLocation getEntityTexture(Entity entity) {
return new ResourceLocation("the_star_wars_saga_mod:textures/texturebarcspeeder.png");
}
};
});
}
public static class CustomEntity extends TameableEntity implements IRangedAttackMob {
public CustomEntity(FMLPlayMessages.SpawnEntity packet, World world) {
this(entity, world);
}
public CustomEntity(EntityType<CustomEntity> type, World world) {
super(type, world);
experienceValue = 0;
setNoAI(false);
enablePersistence();
}
@Override
public IPacket<?> createSpawnPacket() {
return NetworkHooks.getEntitySpawningPacket(this);
}
@Override
protected void registerGoals() {
super.registerGoals();
this.goalSelector.addGoal(1, new OwnerHurtByTargetGoal(this));
this.goalSelector.addGoal(1, new RangedAttackGoal(this, 1.25, 20, 10) {
@Override
public boolean shouldContinueExecuting() {
return this.shouldExecute();
}
});
}
@Override
public CreatureAttribute getCreatureAttribute() {
return CreatureAttribute.UNDEFINED;
}
@Override
public boolean canDespawn(double distanceToClosestPlayer) {
return false;
}
@Override
public void playStepSound(BlockPos pos, BlockState blockIn) {
this.playSound(
(net.minecraft.util.SoundEvent) ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation("the_star_wars_saga_mod:speeder")),
0.15f, 1);
}
@Override
public net.minecraft.util.SoundEvent getHurtSound(DamageSource ds) {
return (net.minecraft.util.SoundEvent) ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation(""));
}
@Override
public net.minecraft.util.SoundEvent getDeathSound() {
return (net.minecraft.util.SoundEvent) ForgeRegistries.SOUND_EVENTS.getValue(new ResourceLocation(""));
}
@Override
public boolean attackEntityFrom(DamageSource source, float amount) {
if (source.getImmediateSource() instanceof PlayerEntity)
return false;
if (source.getImmediateSource() instanceof PotionEntity)
return false;
if (source == DamageSource.FALL)
return false;
if (source == DamageSource.CACTUS)
return false;
return super.attackEntityFrom(source, amount);
}
@Override
public ILivingEntityData onInitialSpawn(IWorld world, DifficultyInstance difficulty, SpawnReason reason, ILivingEntityData livingdata,
CompoundNBT tag) {
ILivingEntityData retval = super.onInitialSpawn(world, difficulty, reason, livingdata, tag);
double x = this.getPosX();
double y = this.getPosY();
double z = this.getPosZ();
Entity entity = this;
{
Map<String, Object> $_dependencies = new HashMap<>();
$_dependencies.put("entity", entity);
BarcspeederOnInitialEntitySpawnProcedure.executeProcedure($_dependencies);
}
return retval;
}
@Override
public boolean processInteract(PlayerEntity sourceentity, Hand hand) {
ItemStack itemstack = sourceentity.getHeldItem(hand);
boolean retval = true;
Item item = itemstack.getItem();
if (itemstack.getItem() instanceof SpawnEggItem) {
retval = super.processInteract(sourceentity, hand);
} else if (this.world.isRemote) {
retval = this.isTamed() && this.isOwner(sourceentity) || this.isBreedingItem(itemstack);
} else {
if (this.isTamed()) {
if (this.isOwner(sourceentity)) {
if (item.isFood() && this.isBreedingItem(itemstack) && this.getHealth() < this.getMaxHealth()) {
this.consumeItemFromStack(sourceentity, itemstack);
this.heal((float) item.getFood().getHealing());
retval = true;
} else if (this.isBreedingItem(itemstack) && this.getHealth() < this.getMaxHealth()) {
this.consumeItemFromStack(sourceentity, itemstack);
this.heal(4);
retval = true;
} else {
retval = super.processInteract(sourceentity, hand);
}
}
} else if (this.isBreedingItem(itemstack)) {
this.consumeItemFromStack(sourceentity, itemstack);
if (this.rand.nextInt(3) == 0 && !net.minecraftforge.event.ForgeEventFactory.onAnimalTame(this, sourceentity)) {
this.setTamedBy(sourceentity);
this.world.setEntityState(this, (byte) 7);
} else {
this.world.setEntityState(this, (byte) 6);
}
this.enablePersistence();
retval = true;
} else {
retval = super.processInteract(sourceentity, hand);
if (retval)
this.enablePersistence();
}
}
sourceentity.startRiding(this);
double x = this.getPosX();
double y = this.getPosY();
double z = this.getPosZ();
Entity entity = this;
return retval;
}
@Override
protected void registerAttributes() {
super.registerAttributes();
if (this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED) != null)
this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).setBaseValue(3);
if (this.getAttribute(SharedMonsterAttributes.MAX_HEALTH) != null)
this.getAttribute(SharedMonsterAttributes.MAX_HEALTH).setBaseValue(10);
if (this.getAttribute(SharedMonsterAttributes.ARMOR) != null)
this.getAttribute(SharedMonsterAttributes.ARMOR).setBaseValue(0);
if (this.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE) == null)
this.getAttributes().registerAttribute(SharedMonsterAttributes.ATTACK_DAMAGE);
this.getAttribute(SharedMonsterAttributes.ATTACK_DAMAGE).setBaseValue(3);
}
public void attackEntityWithRangedAttack(LivingEntity target, float flval) {
BowcasterItem.shoot(this, target);
}
@Override
public AgeableEntity createChild(AgeableEntity ageable) {
CustomEntity retval = (CustomEntity) entity.create(this.world);
retval.onInitialSpawn(this.world, this.world.getDifficultyForLocation(new BlockPos(retval)), SpawnReason.BREEDING,
(ILivingEntityData) null, (CompoundNBT) null);
return retval;
}
@Override
public boolean isBreedingItem(ItemStack stack) {
if (stack == null)
return false;
if (new ItemStack(Blocks.REDSTONE_TORCH, (int) (1)).getItem() == stack.getItem())
return true;
return false;
}
@Override
public void travel(Vec3d dir) {
Entity entity = this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0);
if (this.isBeingRidden()) {
this.rotationYaw = entity.rotationYaw;
this.prevRotationYaw = this.rotationYaw;
this.rotationPitch = entity.rotationPitch * 0.5F;
this.setRotation(this.rotationYaw, this.rotationPitch);
this.jumpMovementFactor = this.getAIMoveSpeed() * 0.15F;
this.renderYawOffset = entity.rotationYaw;
this.rotationYawHead = entity.rotationYaw;
this.stepHeight = 1.0F;
if (entity instanceof LivingEntity) {
this.setAIMoveSpeed((float) this.getAttribute(SharedMonsterAttributes.MOVEMENT_SPEED).getValue());
float forward = ((LivingEntity) entity).moveForward;
float strafe = ((LivingEntity) entity).moveStrafing;
super.travel(new Vec3d(strafe, 0, forward));
}
this.prevLimbSwingAmount = this.limbSwingAmount;
double d1 = this.getPosX() - this.prevPosX;
double d0 = this.getPosZ() - this.prevPosZ;
float f1 = MathHelper.sqrt(d1 * d1 + d0 * d0) * 4.0F;
if (f1 > 1.0F)
f1 = 1.0F;
this.limbSwingAmount += (f1 - this.limbSwingAmount) * 0.4F;
this.limbSwing += this.limbSwingAmount;
return;
}
this.stepHeight = 0.5F;
this.jumpMovementFactor = 0.02F;
super.travel(dir);
}
public void livingTick() {
super.livingTick();
double x = this.getPosX();
double y = this.getPosY();
double z = this.getPosZ();
Random random = this.rand;
Entity entity = this;
if (true)
for (int l = 0; l < 1; ++l) {
double d0 = (x + random.nextFloat());
double d1 = (y + random.nextFloat());
double d2 = (z + random.nextFloat());
int i1 = random.nextInt(2) * 2 - 1;
double d3 = (random.nextFloat() - 0.5D) * 0.1999999985098839D;
double d4 = (random.nextFloat() - 0.5D) * 0.1999999985098839D;
double d5 = (random.nextFloat() - 0.5D) * 0.1999999985098839D;
world.addParticle(ParticleTypes.SMOKE, d0, d1, d2, d3, d4, d5);
}
}
}
// Made with Blockbench 3.6.6
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modelcustomm_model extends EntityModel<Entity> {
private final ModelRenderer engine;
private final ModelRenderer seating;
private final ModelRenderer bb_main;
public Modelcustomm_model() {
textureWidth = 256;
textureHeight = 256;
engine = new ModelRenderer(this);
engine.setRotationPoint(0.0F, 24.0F, 0.0F);
engine.setTextureOffset(0, 0).addBox(-3.0F, -1.0F, -49.0F, 5.0F, 1.0F, 77.0F, 0.0F, false);
engine.setTextureOffset(0, 0).addBox(-5.0F, -7.0F, 3.0F, 9.0F, 7.0F, 25.0F, 0.0F, false);
engine.setTextureOffset(120, 39).addBox(-8.0F, -7.0F, 1.0F, 3.0F, 7.0F, 27.0F, 0.0F, false);
engine.setTextureOffset(87, 32).addBox(4.0F, -7.0F, -2.0F, 3.0F, 7.0F, 27.0F, 0.0F, false);
engine.setTextureOffset(123, 78).addBox(-11.0F, -7.0F, -2.0F, 6.0F, 7.0F, 28.0F, 0.0F, false);
engine.setTextureOffset(0, 78).addBox(7.0F, -7.0F, -1.0F, 3.0F, 7.0F, 23.0F, 0.0F, false);
engine.setTextureOffset(0, 78).addBox(-14.0F, -7.0F, -1.0F, 5.0F, 7.0F, 25.0F, 0.0F, false);
engine.setTextureOffset(87, 0).addBox(-4.0F, -8.0F, 3.0F, 7.0F, 7.0F, 25.0F, 0.0F, false);
engine.setTextureOffset(0, 32).addBox(-4.0F, -13.0F, 3.0F, 7.0F, 7.0F, 25.0F, 0.0F, false);
seating = new ModelRenderer(this);
seating.setRotationPoint(0.0F, 24.0F, 0.0F);
seating.setTextureOffset(0, 78).addBox(-5.0F, -3.0F, -26.0F, 9.0F, 2.0F, 54.0F, 0.0F, false);
seating.setTextureOffset(0, 0).addBox(-5.0F, -22.0F, 4.0F, 10.0F, 20.0F, 1.0F, 0.0F, false);
seating.setTextureOffset(72, 78).addBox(-5.0F, -5.0F, -13.0F, 9.0F, 5.0F, 11.0F, 0.0F, false);
seating.setTextureOffset(39, 32).addBox(-1.0F, -3.0F, -16.0F, 1.0F, 7.0F, 17.0F, 0.0F, false);
bb_main = new ModelRenderer(this);
bb_main.setRotationPoint(0.0F, 24.0F, 0.0F);
bb_main.setTextureOffset(43, 0).addBox(4.0F, -16.0F, -7.0F, 1.0F, 16.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(39, 30).addBox(-6.0F, -16.0F, -7.0F, 1.0F, 16.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(72, 78).addBox(-3.0F, -8.0F, -48.0F, 5.0F, 8.0F, 41.0F, 0.0F, false);
bb_main.setTextureOffset(12, 21).addBox(4.0F, -16.0F, -7.0F, 4.0F, 2.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(0, 21).addBox(-9.0F, -16.0F, -7.0F, 4.0F, 2.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(126, 0).addBox(1.0F, -9.0F, -52.0F, 3.0F, 5.0F, 18.0F, 0.0F, false);
bb_main.setTextureOffset(0, 108).addBox(-4.0F, -9.0F, -52.0F, 3.0F, 5.0F, 18.0F, 0.0F, false);
bb_main.setTextureOffset(0, 32).addBox(-2.0F, -5.0F, -55.0F, 5.0F, 5.0F, 7.0F, 0.0F, false);
}
@Override
public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks, float netHeadYaw, float headPitch) {
// previously the render function, render code was moved to a method below
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red, float green, float blue,
float alpha) {
engine.render(matrixStack, buffer, packedLight, packedOverlay);
seating.render(matrixStack, buffer, packedLight, packedOverlay);
bb_main.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}
}
<file_sep>/models/Modelhumanoid.java
// Made with Blockbench 3.6.6
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modelhumanoid extends EntityModel<Entity> {
private final ModelRenderer head;
private final ModelRenderer bone;
public Modelhumanoid() {
textureWidth = 32;
textureHeight = 32;
head = new ModelRenderer(this);
head.setRotationPoint(0.0F, -10.0F, 0.0F);
head.setTextureOffset(0, 0).addBox(-4.0F, 26.0F, -4.0F, 8.0F, 8.0F, 8.0F, 0.0F, false);
head.setTextureOffset(0, 16).addBox(-5.0F, 22.0F, -3.0F, 1.0F, 12.0F, 1.0F, 0.0F, false);
head.setTextureOffset(4, 16).addBox(-5.0F, 21.0F, -3.0F, 4.0F, 2.0F, 1.0F, 0.0F, false);
head.setTextureOffset(0, 0).addBox(3.0F, 33.0F, -5.0F, 1.0F, 1.0F, 1.0F, 0.0F, false);
head.setTextureOffset(0, 0).addBox(-4.0F, 33.0F, -5.0F, 1.0F, 1.0F, 1.0F, 0.0F, false);
bone = new ModelRenderer(this);
bone.setRotationPoint(0.0F, 39.0F, 0.0F);
head.addChild(bone);
}
@Override
public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks,
float netHeadYaw, float headPitch) {
// previously the render function, render code was moved to a method below
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red,
float green, float blue, float alpha) {
head.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/block/SANDBAGBlock.java
package net.mcreator.thestarwarssagamod.block;
import net.minecraftforge.registries.ObjectHolder;
import net.minecraftforge.common.IPlantable;
import net.minecraftforge.api.distmarker.OnlyIn;
import net.minecraftforge.api.distmarker.Dist;
import net.minecraft.world.storage.loot.LootContext;
import net.minecraft.world.IWorldReader;
import net.minecraft.world.IBlockReader;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.Direction;
import net.minecraft.state.properties.SlabType;
import net.minecraft.item.ItemStack;
import net.minecraft.item.Item;
import net.minecraft.item.BlockItemUseContext;
import net.minecraft.item.BlockItem;
import net.minecraft.entity.LivingEntity;
import net.minecraft.block.material.MaterialColor;
import net.minecraft.block.material.Material;
import net.minecraft.block.SoundType;
import net.minecraft.block.SlabBlock;
import net.minecraft.block.BlockState;
import net.minecraft.block.Block;
import net.mcreator.thestarwarssagamod.itemgroup.DefensiveItemGroup;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.List;
import java.util.Collections;
@TheStarWarsSagaModModElements.ModElement.Tag
public class SANDBAGBlock extends TheStarWarsSagaModModElements.ModElement {
@ObjectHolder("the_star_wars_saga_mod:sandbag")
public static final Block block = null;
public SANDBAGBlock(TheStarWarsSagaModModElements instance) {
super(instance, 85);
}
@Override
public void initElements() {
elements.blocks.add(() -> new CustomBlock());
elements.items.add(() -> new BlockItem(block, new Item.Properties().group(DefensiveItemGroup.tab)).setRegistryName(block.getRegistryName()));
}
public static class CustomBlock extends SlabBlock {
public CustomBlock() {
super(Block.Properties.create(Material.EARTH).sound(SoundType.SAND).hardnessAndResistance(4f, 19.5f).lightValue(0).slipperiness(2.9f));
setRegistryName("sandbag");
}
@Override
public float[] getBeaconColorMultiplier(BlockState state, IWorldReader world, BlockPos pos, BlockPos beaconPos) {
return new float[]{0.796078431373f, 0.647058823529f, 0.454901960784f};
}
@OnlyIn(Dist.CLIENT)
public boolean isSideInvisible(BlockState state, BlockState adjacentBlockState, Direction side) {
return adjacentBlockState.getBlock() == this ? true : super.isSideInvisible(state, adjacentBlockState, side);
}
@Override
public boolean isReplaceable(BlockState state, BlockItemUseContext context) {
return true;
}
@Override
public MaterialColor getMaterialColor(BlockState state, IBlockReader blockAccess, BlockPos pos) {
return MaterialColor.BLACK_TERRACOTTA;
}
@Override
public boolean canSustainPlant(BlockState state, IBlockReader world, BlockPos pos, Direction direction, IPlantable plantable) {
return true;
}
@Override
public boolean isLadder(BlockState state, IWorldReader world, BlockPos pos, LivingEntity entity) {
return true;
}
@Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
List<ItemStack> dropsOriginal = super.getDrops(state, builder);
if (!dropsOriginal.isEmpty())
return dropsOriginal;
return Collections.singletonList(new ItemStack(this, state.get(TYPE) == SlabType.DOUBLE ? 2 : 1));
}
}
}
<file_sep>/models/Modelporg.java
// Made with Blockbench 3.6.6
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modelporg extends EntityModel<Entity> {
private final ModelRenderer head;
private final ModelRenderer head2;
private final ModelRenderer beak1;
private final ModelRenderer beak2;
private final ModelRenderer body;
private final ModelRenderer tail;
private final ModelRenderer wing0;
private final ModelRenderer wing1;
private final ModelRenderer feather;
private final ModelRenderer leg0;
private final ModelRenderer leg1;
public Modelporg() {
textureWidth = 32;
textureHeight = 32;
head = new ModelRenderer(this);
head.setRotationPoint(0.0F, 15.7F, -2.8F);
head.setTextureOffset(2, 2).addBox(-1.0F, -1.5F, -1.0F, 2.0F, 3.0F, 2.0F, 0.0F, true);
head2 = new ModelRenderer(this);
head2.setRotationPoint(0.0F, -2.0F, -1.0F);
head2.setTextureOffset(10, 0).addBox(-1.0F, -0.5F, -2.0F, 2.0F, 1.0F, 4.0F, 0.0F, true);
beak1 = new ModelRenderer(this);
beak1.setRotationPoint(0.0F, -0.5F, -1.5F);
beak1.setTextureOffset(11, 7).addBox(-0.5F, -1.0F, -0.5F, 1.0F, 2.0F, 1.0F, 0.0F, true);
beak2 = new ModelRenderer(this);
beak2.setRotationPoint(0.0F, -1.8F, -2.5F);
beak2.setTextureOffset(16, 7).addBox(-0.5F, 0.3F, -0.5F, 1.0F, 1.0F, 1.0F, 0.0F, true);
body = new ModelRenderer(this);
body.setRotationPoint(0.0F, 16.5F, -3.0F);
body.setTextureOffset(2, 8).addBox(-1.5F, 0.0F, -1.5F, 3.0F, 6.0F, 3.0F, 0.0F, true);
tail = new ModelRenderer(this);
tail.setRotationPoint(0.0F, 21.1F, 1.2F);
tail.setTextureOffset(22, 1).addBox(-1.5F, -1.0F, -4.0F, 3.0F, 4.0F, 1.0F, 0.0F, true);
wing0 = new ModelRenderer(this);
wing0.setRotationPoint(-1.5F, 16.9F, -2.8F);
wing0.setTextureOffset(19, 8).addBox(-0.5F, 0.0F, -1.5F, 1.0F, 5.0F, 3.0F, 0.0F, true);
wing1 = new ModelRenderer(this);
wing1.setRotationPoint(1.5F, 16.9F, -2.8F);
wing1.setTextureOffset(19, 8).addBox(-0.5F, 0.0F, -1.5F, 1.0F, 5.0F, 3.0F, 0.0F, true);
feather = new ModelRenderer(this);
feather.setRotationPoint(0.0F, -2.1F, 0.2F);
feather.setTextureOffset(2, 18).addBox(0.0F, -4.0F, -2.1F, 0.0F, 5.0F, 4.0F, 0.0F, true);
leg0 = new ModelRenderer(this);
leg0.setRotationPoint(-1.0F, 22.0F, -1.0F);
leg0.setTextureOffset(14, 18).addBox(-0.5F, 0.0F, -2.5F, 1.0F, 2.0F, 1.0F, 0.0F, true);
leg1 = new ModelRenderer(this);
leg1.setRotationPoint(1.0F, 22.0F, -1.0F);
leg1.setTextureOffset(14, 18).addBox(-0.5F, 0.0F, -2.5F, 1.0F, 2.0F, 1.0F, 0.0F, true);
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red,
float green, float blue, float alpha) {
head.render(matrixStack, buffer, packedLight, packedOverlay);
head2.render(matrixStack, buffer, packedLight, packedOverlay);
beak1.render(matrixStack, buffer, packedLight, packedOverlay);
beak2.render(matrixStack, buffer, packedLight, packedOverlay);
body.render(matrixStack, buffer, packedLight, packedOverlay);
tail.render(matrixStack, buffer, packedLight, packedOverlay);
wing0.render(matrixStack, buffer, packedLight, packedOverlay);
wing1.render(matrixStack, buffer, packedLight, packedOverlay);
feather.render(matrixStack, buffer, packedLight, packedOverlay);
leg0.render(matrixStack, buffer, packedLight, packedOverlay);
leg1.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity e) {
super.setRotationAngles(f, f1, f2, f3, f4, f5, e);
this.head.rotateAngleY = f3 / (180F / (float) Math.PI);
this.head.rotateAngleX = f4 / (180F / (float) Math.PI);
this.leg0.rotateAngleX = MathHelper.cos(f * 1.0F) * 1.0F * f1;
this.leg1.rotateAngleX = MathHelper.cos(f * 1.0F) * 1.0F * f1;
}
}<file_sep>/models/Modelcustom_modeldroid.java
// Made with Blockbench 3.6.6
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modelcustom_modeldroid extends EntityModel<Entity> {
private final ModelRenderer body;
private final ModelRenderer rightleg;
private final ModelRenderer bone;
private final ModelRenderer leftleg;
private final ModelRenderer bone2;
private final ModelRenderer chest;
private final ModelRenderer slants;
private final ModelRenderer slants2;
private final ModelRenderer head;
private final ModelRenderer bone3;
private final ModelRenderer bone4;
private final ModelRenderer bone5;
private final ModelRenderer bone11;
private final ModelRenderer bone6;
private final ModelRenderer bone7;
private final ModelRenderer bone8;
private final ModelRenderer bone9;
private final ModelRenderer bone10;
public Modelcustom_modeldroid() {
textureWidth = 64;
textureHeight = 64;
body = new ModelRenderer(this);
body.setRotationPoint(0.0F, 24.0F, 0.0F);
rightleg = new ModelRenderer(this);
rightleg.setRotationPoint(0.0F, 0.0F, 0.0F);
body.addChild(rightleg);
rightleg.setTextureOffset(45, 14).addBox(-5.0F, -1.0F, -2.0F, 2.0F, 1.0F, 3.0F, 0.0F, false);
rightleg.setTextureOffset(40, 6).addBox(-5.0F, -9.0F, -1.0F, 2.0F, 9.0F, 2.0F, 0.0F, false);
bone = new ModelRenderer(this);
bone.setRotationPoint(0.0F, 0.0F, -3.0F);
rightleg.addChild(bone);
setRotationAngle(bone, -0.3054F, 0.0F, 0.0F);
bone.setTextureOffset(42, 29).addBox(-5.0F, -16.0F, -1.0F, 2.0F, 7.0F, 2.0F, 0.0F, false);
leftleg = new ModelRenderer(this);
leftleg.setRotationPoint(0.0F, 0.0F, 0.0F);
body.addChild(leftleg);
leftleg.setTextureOffset(44, 38).addBox(3.0F, -1.0F, -2.0F, 2.0F, 1.0F, 3.0F, 0.0F, false);
leftleg.setTextureOffset(16, 40).addBox(3.0F, -9.0F, -1.0F, 2.0F, 9.0F, 2.0F, 0.0F, false);
bone2 = new ModelRenderer(this);
bone2.setRotationPoint(0.0F, 0.0F, -3.0F);
leftleg.addChild(bone2);
setRotationAngle(bone2, -0.3054F, 0.0F, 0.0F);
bone2.setTextureOffset(24, 42).addBox(3.0F, -16.0F, -1.0F, 2.0F, 7.0F, 2.0F, 0.0F, false);
chest = new ModelRenderer(this);
chest.setRotationPoint(0.0F, 0.0F, 0.0F);
body.addChild(chest);
chest.setTextureOffset(24, 24).addBox(-5.0F, -17.0F, 1.0F, 10.0F, 3.0F, 2.0F, 0.0F, false);
chest.setTextureOffset(0, 4).addBox(-5.0F, -34.0F, 0.0F, 10.0F, 10.0F, 4.0F, 0.0F, false);
chest.setTextureOffset(24, 4).addBox(-5.0F, -20.0F, 1.0F, 10.0F, 1.0F, 1.0F, 0.0F, false);
chest.setTextureOffset(0, 18).addBox(-4.0F, -35.0F, 0.0F, 8.0F, 5.0F, 4.0F, 0.0F, false);
chest.setTextureOffset(26, 29).addBox(1.0F, -34.0F, 4.0F, 3.0F, 11.0F, 2.0F, 0.0F, false);
chest.setTextureOffset(16, 27).addBox(-4.0F, -34.0F, 4.0F, 3.0F, 11.0F, 2.0F, 0.0F, false);
slants = new ModelRenderer(this);
slants.setRotationPoint(0.0F, 0.0F, 0.0F);
chest.addChild(slants);
setRotationAngle(slants, -0.0873F, 0.0F, 0.0F);
slants.setTextureOffset(6, 46).addBox(-5.0F, -27.0F, -1.0F, 1.0F, 8.0F, 2.0F, 0.0F, false);
slants2 = new ModelRenderer(this);
slants2.setRotationPoint(9.0F, 0.0F, 0.0F);
chest.addChild(slants2);
setRotationAngle(slants2, -0.0873F, 0.0F, 0.0F);
slants2.setTextureOffset(32, 45).addBox(-5.0F, -27.0F, -1.0F, 1.0F, 8.0F, 2.0F, 0.0F, false);
slants2.setTextureOffset(0, 35).addBox(-10.0F, -27.0F, -1.0F, 2.0F, 10.0F, 2.0F, 0.0F, false);
head = new ModelRenderer(this);
head.setRotationPoint(0.0F, 0.0F, 0.0F);
body.addChild(head);
head.setTextureOffset(48, 26).addBox(-1.0F, -43.0F, 4.0F, 2.0F, 1.0F, 2.0F, 0.0F, false);
bone3 = new ModelRenderer(this);
bone3.setRotationPoint(0.0F, 0.0F, -9.0F);
head.addChild(bone3);
setRotationAngle(bone3, -0.2618F, 0.0F, 0.0F);
bone3.setTextureOffset(46, 0).addBox(-1.0F, -42.0F, 0.0F, 2.0F, 7.0F, 1.0F, 0.0F, false);
bone4 = new ModelRenderer(this);
bone4.setRotationPoint(0.0F, -39.0F, 0.0F);
head.addChild(bone4);
setRotationAngle(bone4, 0.2182F, 0.0F, 0.0F);
bone4.setTextureOffset(21, 11).addBox(-1.0F, -3.0F, -3.0F, 2.0F, 3.0F, 7.0F, 0.0F, false);
bone4.setTextureOffset(0, 27).addBox(-1.0F, -2.0F, -5.0F, 2.0F, 2.0F, 6.0F, 0.0F, false);
bone4.setTextureOffset(47, 18).addBox(-1.0F, -3.0F, 3.0F, 2.0F, 3.0F, 2.0F, 0.0F, false);
bone5 = new ModelRenderer(this);
bone5.setRotationPoint(0.0F, -40.0F, 7.0F);
head.addChild(bone5);
setRotationAngle(bone5, 0.2182F, 0.0F, 0.0F);
bone5.setTextureOffset(0, 27).addBox(-1.0F, -3.0F, -1.0F, 2.0F, 4.0F, 1.0F, 0.0F, false);
bone5.setTextureOffset(28, 5).addBox(1.0F, -5.6493F, -3.9289F, 0.0F, 5.0F, 1.0F, 0.0F, false);
bone11 = new ModelRenderer(this);
bone11.setRotationPoint(0.0F, -6.0F, -27.0F);
head.addChild(bone11);
setRotationAngle(bone11, -0.6981F, 0.0F, 0.0F);
bone11.setTextureOffset(32, 21).addBox(-1.0F, -42.0F, -5.0F, 2.0F, 2.0F, 1.0F, 0.0F, false);
bone6 = new ModelRenderer(this);
bone6.setRotationPoint(-7.0F, -33.0F, 0.0F);
body.addChild(bone6);
bone6.setTextureOffset(46, 23).addBox(0.0F, -1.0F, 2.0F, 3.0F, 2.0F, 1.0F, 0.0F, false);
bone6.setTextureOffset(24, 21).addBox(11.0F, -1.0F, 2.0F, 3.0F, 2.0F, 1.0F, 0.0F, false);
bone7 = new ModelRenderer(this);
bone7.setRotationPoint(0.0F, -2.0F, 1.0F);
bone6.addChild(bone7);
setRotationAngle(bone7, -0.3927F, 0.0F, 0.0F);
bone7.setTextureOffset(36, 36).addBox(-1.0F, 0.0F, 1.0F, 2.0F, 9.0F, 2.0F, 0.0F, false);
bone7.setTextureOffset(8, 35).addBox(14.0F, 0.0F, 1.0F, 2.0F, 9.0F, 2.0F, 0.0F, false);
bone8 = new ModelRenderer(this);
bone8.setRotationPoint(0.0F, 7.0F, -1.0F);
bone6.addChild(bone8);
setRotationAngle(bone8, -0.829F, -0.7418F, 0.0F);
bone8.setTextureOffset(44, 44).addBox(-1.0F, -1.0F, -1.0F, 2.0F, 6.0F, 2.0F, 0.0F, false);
bone9 = new ModelRenderer(this);
bone9.setRotationPoint(14.0F, 8.0F, -1.0F);
bone6.addChild(bone9);
setRotationAngle(bone9, -1.0036F, 1.0908F, 0.0F);
bone9.setTextureOffset(32, 6).addBox(-1.0F, -2.0F, -2.0F, 2.0F, 10.0F, 2.0F, 0.0F, false);
bone10 = new ModelRenderer(this);
bone10.setRotationPoint(5.0F, 10.0F, -9.0F);
bone6.addChild(bone10);
setRotationAngle(bone10, -0.2182F, 0.48F, 0.48F);
bone10.setTextureOffset(0, 0).addBox(-7.0F, -1.0F, 4.0F, 18.0F, 2.0F, 2.0F, 0.0F, false);
bone10.setTextureOffset(39, 17).addBox(-7.0F, -1.0F, 4.0F, 2.0F, 5.0F, 2.0F, 0.0F, false);
bone10.setTextureOffset(48, 8).addBox(-5.1153F, 0.3865F, 3.7965F, 2.0F, 2.0F, 2.0F, 0.0F, false);
bone10.setTextureOffset(36, 29).addBox(-1.1565F, 0.8836F, 3.7984F, 1.0F, 2.0F, 2.0F, 0.0F, false);
bone10.setTextureOffset(10, 27).addBox(-0.3697F, 0.3441F, 4.0983F, 1.0F, 2.0F, 2.0F, 0.0F, false);
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red,
float green, float blue, float alpha) {
body.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
public void setRotationAngles(float f, float f1, float f2, float f3, float f4, float f5, Entity e) {
super.setRotationAngles(f, f1, f2, f3, f4, f5, e);
this.leftleg.rotateAngleX = MathHelper.cos(f * 1.0F) * -1.0F * f1;
this.rightleg.rotateAngleX = MathHelper.cos(f * 1.0F) * 1.0F * f1;
}
}<file_sep>/models/Modelcustomm_model.java
// Made with Blockbench 3.6.6
// Exported for Minecraft version 1.15
// Paste this class into your mod and generate all required imports
public static class Modelcustomm_model extends EntityModel<Entity> {
private final ModelRenderer engine;
private final ModelRenderer seating;
private final ModelRenderer bb_main;
public Modelcustomm_model() {
textureWidth = 256;
textureHeight = 256;
engine = new ModelRenderer(this);
engine.setRotationPoint(0.0F, 24.0F, 0.0F);
engine.setTextureOffset(0, 0).addBox(-3.0F, -1.0F, -49.0F, 5.0F, 1.0F, 77.0F, 0.0F, false);
engine.setTextureOffset(0, 0).addBox(-5.0F, -7.0F, 3.0F, 9.0F, 7.0F, 25.0F, 0.0F, false);
engine.setTextureOffset(120, 39).addBox(-8.0F, -7.0F, 1.0F, 3.0F, 7.0F, 27.0F, 0.0F, false);
engine.setTextureOffset(87, 32).addBox(4.0F, -7.0F, -2.0F, 3.0F, 7.0F, 27.0F, 0.0F, false);
engine.setTextureOffset(123, 78).addBox(-11.0F, -7.0F, -2.0F, 6.0F, 7.0F, 28.0F, 0.0F, false);
engine.setTextureOffset(0, 78).addBox(7.0F, -7.0F, -1.0F, 3.0F, 7.0F, 23.0F, 0.0F, false);
engine.setTextureOffset(0, 78).addBox(-14.0F, -7.0F, -1.0F, 5.0F, 7.0F, 25.0F, 0.0F, false);
engine.setTextureOffset(87, 0).addBox(-4.0F, -8.0F, 3.0F, 7.0F, 7.0F, 25.0F, 0.0F, false);
engine.setTextureOffset(0, 32).addBox(-4.0F, -13.0F, 3.0F, 7.0F, 7.0F, 25.0F, 0.0F, false);
seating = new ModelRenderer(this);
seating.setRotationPoint(0.0F, 24.0F, 0.0F);
seating.setTextureOffset(0, 78).addBox(-5.0F, -3.0F, -26.0F, 9.0F, 2.0F, 54.0F, 0.0F, false);
seating.setTextureOffset(0, 0).addBox(-5.0F, -22.0F, 4.0F, 10.0F, 20.0F, 1.0F, 0.0F, false);
seating.setTextureOffset(72, 78).addBox(-5.0F, -5.0F, -13.0F, 9.0F, 5.0F, 11.0F, 0.0F, false);
seating.setTextureOffset(39, 32).addBox(-1.0F, -3.0F, -16.0F, 1.0F, 7.0F, 17.0F, 0.0F, false);
bb_main = new ModelRenderer(this);
bb_main.setRotationPoint(0.0F, 24.0F, 0.0F);
bb_main.setTextureOffset(43, 0).addBox(4.0F, -16.0F, -7.0F, 1.0F, 16.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(39, 30).addBox(-6.0F, -16.0F, -7.0F, 1.0F, 16.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(72, 78).addBox(-3.0F, -8.0F, -48.0F, 5.0F, 8.0F, 41.0F, 0.0F, false);
bb_main.setTextureOffset(12, 21).addBox(4.0F, -16.0F, -7.0F, 4.0F, 2.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(0, 21).addBox(-9.0F, -16.0F, -7.0F, 4.0F, 2.0F, 2.0F, 0.0F, false);
bb_main.setTextureOffset(126, 0).addBox(1.0F, -9.0F, -52.0F, 3.0F, 5.0F, 18.0F, 0.0F, false);
bb_main.setTextureOffset(0, 108).addBox(-4.0F, -9.0F, -52.0F, 3.0F, 5.0F, 18.0F, 0.0F, false);
bb_main.setTextureOffset(0, 32).addBox(-2.0F, -5.0F, -55.0F, 5.0F, 5.0F, 7.0F, 0.0F, false);
}
@Override
public void setRotationAngles(Entity entity, float limbSwing, float limbSwingAmount, float ageInTicks,
float netHeadYaw, float headPitch) {
// previously the render function, render code was moved to a method below
}
@Override
public void render(MatrixStack matrixStack, IVertexBuilder buffer, int packedLight, int packedOverlay, float red,
float green, float blue, float alpha) {
engine.render(matrixStack, buffer, packedLight, packedOverlay);
seating.render(matrixStack, buffer, packedLight, packedOverlay);
bb_main.render(matrixStack, buffer, packedLight, packedOverlay);
}
public void setRotationAngle(ModelRenderer modelRenderer, float x, float y, float z) {
modelRenderer.rotateAngleX = x;
modelRenderer.rotateAngleY = y;
modelRenderer.rotateAngleZ = z;
}
}<file_sep>/src/main/java/net/mcreator/thestarwarssagamod/procedures/SithstrenghProcedure.java
package net.mcreator.thestarwarssagamod.procedures;
import net.mcreator.thestarwarssagamod.TheStarWarsSagaModModElements;
import java.util.Map;
@TheStarWarsSagaModModElements.ModElement.Tag
public class SithstrenghProcedure extends TheStarWarsSagaModModElements.ModElement {
public SithstrenghProcedure(TheStarWarsSagaModModElements instance) {
super(instance, 174);
}
public static void executeProcedure(Map<String, Object> dependencies) {
}
}
| 73626aaea006de0097e97b5f3e8bb8fa7fdc4df2 | [
"Java"
] | 15 | Java | thegamingtiger4/mod1 | 5548551dbe3437e31f019cb2793b4bfdfed48911 | a38e1805f79723d692f596476bc1948379b398b1 | |
refs/heads/master | <file_sep># User Guide - `json-kotlin`
## Contents
- [Introduction](#introduction)
- [Type Mapping](#type-mapping)
- [Configuration](#configuration)
- [Serialize Kotlin object to String](#serialize-kotlin-object-to-string)
- [Deserialize String to Kotlin object](#deserialize-string-to-kotlin-object)
- [Serialize Kotlin object to `JSONValue`](#serialize-kotlin-object-to-jsonvalue)
- [Deserialize `JSONValue` to Kotlin object](#deserialize-jsonvalue-to-kotlin-object)
- [Exceptions](#exceptions)
- [Further Examples](#further-examples)
## Introduction
`json-kotlin` is a reflection-based library that converts Kotlin objects to and from their JSON representations.
It builds on an earlier Java library [`jsonutil`](https://github.com/pwall567/jsonutil) that parses JSON text into an
internal structure of `JSONValue` nodes, and converts those nodes back into text.
`json-kotlin` can serialize an arbitrary Kotlin (or Java) object into the `JSONValue` node structure ready for output,
and it can deserialize a node structure into an object of a specified (or implied) Kotlin type.
Most users of the library will not need to know about this two-stage process (string to `JSONValue` followed by
`JSONValue` to object, and vice versa) — first-time users will probably want to start with serializing Kotlin
objects to string and deserializing strings to Kotlin.
More complex uses are described in the sections covering serializing and deserializing to and from `JSONValue`.
As a native Kotlin library, `json-kotlin` will respect the "nullability" of any object being deserialized;
that is to say, it will not deserialize `null` into a `String?`.
It also has built-in support for Kotlin utility classes such as `Sequence` and `Pair`.
## Type mapping
### Custom Serialization and Deserialization
For all classes, including standard classes, the serialization and deserialization processes will first look for a
custom serialization or deserialization function.
That means that custom serializations and deserializations may be specified for any class, even classes with obvious
default representations (like `UUID` or even `Boolean`).
For more information see [Custom Serialization and Deserialization](CUSTOM.md).
### Standard Types
#### Kotlin
`json-kotlin` has built-in support for the following standard Kotlin types:
| Type | JSON Representation |
| ------------- | -------------------- |
| String | string |
| StringBuilder | string |
| CharSequence | string |
| Char | string (of length 1) |
| CharArray | string |
| Int | number |
| Long | number |
| Short | number |
| Byte | number |
| Double | number |
| Float | number |
| Boolean | boolean |
| Array | array |
| IntArray | array |
| LongArray | array |
| ShortArray | array |
| ByteArray | array |
| DoubleArray | array |
| FloatArray | array |
| BooleanArray | array |
| Collection | array |
| Iterable | array |
| Iterator | array |
| List | array |
| ArrayList | array |
| LinkedList | array |
| Set | array |
| HashSet | array |
| LinkedHashSet | array |
| Sequence | array |
| Map | object |
| HashMapMap | object |
| LinkedHashMap | object |
| Pair | array (of length 2) |
| Triple | array (of length 3) |
| Enum | string (using name) |
#### Java
The library also has built-in support for the following standard Java types:
| Type | JSON Representation |
| ------------------------------ | ----------------------------------------------------- |
| java.lang.StringBuffer | string |
| java.math.BigInteger | number ([optionally string](#bigintegerstring)) |
| java.math.BigDecimal | number ([optionally string](#bigdecimalstring)) |
| java.util.Enumeration | array |
| java.util.Bitset | array of bit indices |
| java.util.UUID | string |
| java.util.Date | string (as yyyy-mm-ddThh:mm:ss.sssZ) |
| java.util.Calendar | string (as yyyy-mm-ddThh:mm:ss.sss±hh:mm) |
| java.sql.Date | string (as yyyy-mm-dd) |
| java.sql.Time | string (as hh:mm:ss) |
| java.sql.Timestamp | string (as yyyy-mm-dd hh:mm:ss.sss) |
| java.time.Instant | string (as yyyy-mm-ddThh:mm:ss.sssZ) |
| java.time.LocalDate | string (as yyyy-mm-dd) |
| java.time.LocalTime | string (as hh:mm:ss.sss) |
| java.time.LocalDateTime | string (as yyyy-mm-ddThh:mm:ss.sss) |
| java.time.OffsetTime | string (as hh:mm:ss.sss±hh:mm) |
| java.time.OffsetDateTime | string (as yyyy-mm-ddThh:mm:ss.sss±hh:mm) |
| java.time.ZonedDateTime | string (as yyyy-mm-ddThh:mm:ss.sss±hh:mm\[name]) |
| java.time.Year | string (as yyyy) |
| java.time.YearMonth | string (as yyyy-mm) |
| java.time.MonthDay | string (as --mm-dd) |
| java.time.Duration | string (e.g. PT2M) |
| java.time.Period | string (e.g. P3M) |
| java.net.URI | string |
| java.net.URL | string |
| java.util.stream.Stream | array |
| java.util.stream.IntStream | array |
| java.util.stream.LongStream | array |
| java.util.stream.DoubleStream | array |
### Other Types
#### Serialization
Objects of other types are serialized as objects, using the public properties of the object as properties of the JSON
object.
In this case, as well as for the collection types, the serialization functions call themselves recursively, to the depth
required to represent all levels of the object.
#### Deserialization
Deserialization of classes other than those listed above is possibly the most complex aspect of the `json-kotlin`
library.
If the JSON is a string and the target class has a constructor that takes a single string parameter, that constructor is
invoked and the resulting object returned (this is the mechanism used internally for classes such as `StringBuilder` and
`URL`, but it may also be employed for user-defined classes).
Otherwise, the JSON must be an object, and the deserialization functions will construct an object of the target class,
following this pseudo-code:
```text
create a shortlist of potential constructors
for each constructor in the target class:
for each parameter in the constructor (there may be no parameters):
if there is no property in the JSON object with the same name, and the parameter has no default value,
and the parameter is not nullable:
reject the constructor
if the constructor has not been rejected add it to the shortlist
if there is no constructor in the shortlist:
FAILURE - can't construct an object of the target type from the supplied JSON
if there is more than one constructor in the shortlist:
select the constructor that uses the greatest number of properties from the JSON object
for each parameter in the selected constructor (there may be none in the case of a no-arg constructor):
if the parameter has a matching property in the JSON:
invoke the deserialization functions using the target type from the parameter and the property from the JSON
if the parameter has no matching property in the JSON, and has no default value, but is nullable:
set the parameter value to null
invoke the constructor using the parameter values derived as above
for each property in the JSON that has not been consumed by the constructor (there may be no such properties):
locate a property in the instantiated object with the same name
if no such property exists (and allowExtra not specified):
FAILURE - can't construct an object of the target type from the supplied JSON
if a property exists and has a setter (it is a var property):
invoke the deserialization functions using the target type from the property and the property from the JSON
invoke the setter function with the resulting value
if a property exists but has no setter (it is a val property):
invoke the deserialization functions using the target type from the property and the property from the JSON
invoke the getter function
if the value from the getter does not match the value from the deserialization of the JSON property:
FAILURE - can't construct an object of the target type from the supplied JSON
return the instantiated object
```
The above steps allow for a wide variety of target classes, but in the common case of a Kotlin data class with a single
constructor and no additional properties, the steps reduce to:
```text
for each parameter in the constructor:
if the parameter has a matching property in the JSON:
invoke the deserialization functions using the target type from the parameter and the property from the JSON
if the parameter has no matching property in the JSON, and has no default value, but is nullable:
set the parameter value to null
if the parameter has no matching property in the JSON, the parameter has no default value,
and the parameter is not nullable:
FAILURE - can't construct an object of the target type from the supplied JSON
invoke the constructor using the parameter values derived as above
if there are properties in the JSON that have not been consumed by the constructor (and allowExtra not specified):
FAILURE - can't construct an object of the target type from the supplied JSON
return the instantiated object
```
### `Any?`
When deserialising into the target type `Any?` (either as the initial target class or as a nested class in a recursive
invocation), `json-kotlin` will return the following types:
| Input JSON | Result Class |
| ---------------------------------------------------- | ------------------- |
| string | `String` |
| number (that will fit in an `Int`) | `Int` |
| number (longer than `Int`, but will fit in a `Long`) | `Long` |
| number (other than the above) | `BigDecimal` |
| boolean | `Boolean` |
| array | `List<Any?>` |
| object | `Map<String, Any?>` |
When the return class is `List` or `Map`, the type parameter is `Any?` but the actual type will itself be one of the
above.
### Objects
A Kotlin `object` may be the target of a deserialization operation (serialization requires no special processing).
The object instance will be returned, and all parameters in the JSON will be processed in the same way as additional
properties (those not used as constructor parameters) in the instantiation of an object.
### Sealed Classes
The library will handle [Kotlin sealed classes](https://kotlinlang.org/docs/reference/sealed-classes.html), by adding a
discriminator property to the JSON object to allow the deserialization to select the correct derived class.
The Kotlin documentation on sealed classes uses the following example:
```kotlin
sealed class Expr
data class Const(val number: Double) : Expr()
data class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
```
A `Const` instance from the example will serialize as:
```json
{"class":"Const","number":1.234}
```
and the `NotANumber` object will serialize as:
```json
{"class":"NotANumber"}
```
The discriminator property name (default "class") [may be chosen as required](#sealedclassdiscriminator).
## Configuration
Operation of the `json-kotlin` library may be parameterised by the use of the `JSONConfig` class.
This form of configuration (as opposed to constructing and tailoring a converter object which then performs the
serialization and deserialization) has a number of advantages:
- simple uses of the library (the majority) may be expressed more concisely
- the pattern allows for the use of extension functions (e.g. `string.parseJSON(config)`)
Most of the serialization and deserialization functions take a `JSONConfig` as a parameter, and use
`JSONConfig.defaultConfig` as the default if the parameter is omitted.
To create a custom `JSONConfig`:
```kotlin
val config = JSONConfig().apply {
// make changes to default settings as required
}
```
### `includeNulls`
The default behaviour is to omit `null` fields when serializing an object.
To specify that all fields are to be output, even if `null`, set the `includeNulls` variable to `true`:
```kotlin
config.includeNulls = true
```
### `allowExtra`
When deserializing a JSON object into an instance of a class, `json-kotlin` will try to find a constructor parameter or
an instance variable for each property in the object, and will raise an exception if no matching parameter or property
exists.
To allow non-matching properties to be ignored, the `allowExtra` variable may be set to `true`:
```kotlin
config.allowExtra = true
```
### `bigDecimalString`
By default `BigDecimal` objects will be serialized to and deserialized from JSON numbers.
To use strings, the `bigDecimalString` variable may be set to `true`:
```kotlin
config.bigDecimalString = true
```
### `bigIntegerString`
By default `BigInteger` objects will be serialized to and deserialized from JSON numbers.
To use strings, the `bigIntegerString` variable may be set to `true`:
```kotlin
config.bigIntegerString = true
```
### `sealedClassDiscriminator`
The default name for the discriminator property added to sealed classes is `class`.
This may be changed using the `sealedClassDiscriminator` variable:
```kotlin
config.sealedClassDiscriminator = "?" // note that it does not need to be an alphanumeric name
```
### `fromJSON`
Function to add a custom deserialization lambda.
See [Custom Serialization and Deserialization](CUSTOM.md#fromjson-lambda-in-the-jsonconfig).
### `toJSON`
Function to add a custom serialization lambda.
See [Custom Serialization and Deserialization](CUSTOM.md#tojson-lambda-in-the-jsonconfig).
### `defaultConfig`
The `defaultConfig` object that will be used when no `JSONConfig` is specified may be modified just like any other
`JSONConfig`.
To make a configuration option apply to all uses of the library in an application, you can set the value in the
default object and it will take effect for all functions where a `JSONConfig` is not specified explicitly, for example:
```kotlin
JSONConfig.defaultConfig.allowExtra = true
```
If you have made such changes to the `defaultConfig`, you can still override them by specifying a "clean" `JSONConfig`
in the function call:
```kotlin
val person: Person? = json.parseJSON(JSONConfig())
```
### Annotations
Many of the above options may applied to an individual property or to a class by the use of annotations.
See the [json-kotlin-annotations](https://github.com/pwall567/json-kotlin-annotations) project for more details.
## Serialize Kotlin object to String
### Extension Functions
The simplest way to convert any object to JSON is to use the `stringifyJSON()` extension function on the object itself
(the receiver for the function is `Any?`, so it may even be applied to `null`):
```kotlin
val obj = listOf("ABC", "DEF")
println(obj.stringifyJSON())
```
This will output:
```json
["ABC","DEF"]
```
If required, a `JSONConfig` may be provided as a parameter to the function.
Alternatively, if you have an `Appendable` (for example, a `StringBuilder` or a `Writer`), you can serialize an object
directly using the `appendJSON()` extension function on the `Appendable`:
```kotlin
File("path.to.file").writer().use {
it.appendJSON(objectToBeSerialized)
}
```
This avoids allocating a `StringBuilder` to hold the serialized data before it is output.
An optional `JSONConfig` may be supplied as a second parameter to the function.
### The `JSONStringify` object
For those who prefer to call a function with the object to be serialized as a parameter, the `JSONStringify` object has
a function `stringify` for this purpose (the word "stringify" is borrowed from the JavaScript implementation of JSON):
```kotlin
val person = Person(surname = "Smith", firstName = "Bill")
println(JSONStringify.stringify(person))
```
If required, a `JSONConfig` may be supplied as a second parameter to the function.
### The `JSONAuto` object
The `JSONAuto` object has a number of functions to help with parsing, but it also has a `stringify` function, which
operates identically to the `JSONStringify.stringify()` function above.
## Deserialize String to Kotlin object
Deserialization in all its forms requires the target type to be specified in some way.
In many cases the target type may be determined through Kotlin type inference, but there are also functions that allow
the target type to be specified explicitly as a `KType`, a `KClass` or even a Java `Class` or `Type`.
All of these functions will return `null` if the JSON string is `"null"`, and they all take a `JSONConfig` as an
optional final (or only) parameter.
The examples in this section assume the input is a JSON string as follows:
```kotlin
val json = """{"surname":"Smith","firstName":"Bill"}"""
```
### Extension Functions
The extension function `parseJSON()` may be applied to a `CharSequence` (this is an interface that is implemented by
`String`, `StringBuilder` and other classes, so the extension function may be applied to any of those classes).
There are several forms of the function, allowing the target type to be specified in different ways:
#### Implied type
The simplest form of the function is the one that uses the implied type:
```kotlin
val person: Person? = json.parseJSON()
```
Note that the result type must be specified as nullable.
Of course, if a null value would represent an error, you can use something like:
```kotlin
val person: Person = json.parseJSON() ?: throw NullPointerException("JSON should not be null")
```
#### Kotlin reified type
The same function may be invoked using the target type as type parameter:
```kotlin
val person = json.parseJSON<Person>()
```
Even though the type parameter is specified as the non-nullable type, the result type will be nullable
(in this case, the type of `person` will be `Person?`).
#### Explicit `KClass`
The class may be specified as a parameter:
```kotlin
val person = json.parseJSON(Person::class)
```
#### Explicit `KType`
The type may be specified as a parameter (note that in this case, the type parameter does not convey enough information
to determine the result type at compile time, so an `as` construction is required):
```kotlin
val person = json.parseJSON(Person::class.starProjectedType) as Person
```
### The `JSONAuto` object
The `JSONAuto` object has a number of parsing functions, allowing the input to be supplied as a `String` (actually a
`CharSequence` - see above), a `Reader`, an `InputStream` or a `File`.
For each form of input, the target type may be specified implicitly or as a `KClass`, `KType` or a Java `Type` (which
includes `Class`).
The function signatures are listed here; for more detail see the KDoc (your IDE should show this when you enter the
function name):
- `fun parse(resultType: KType, str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun <T: Any> parse(resultClass: KClass<T>, str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `inline fun <reified T: Any> parse(str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `fun parse(javaType: Type, str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun parse(resultType: KType, reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun <T: Any> parse(resultClass: KClass<T>, reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `inline fun <reified T: Any> parse(reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `fun parse(javaType: Type, reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun parse(resultType: KType, inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun <T: Any> parse(resultClass: KClass<T>, inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `inline fun <reified T: Any> parse(inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `fun parse(javaType: Type, inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun parse(resultType: KType, file: File, config: JSONConfig = JSONConfig.defaultConfig): Any?`
- `fun <T: Any> parse(resultClass: KClass<T>, file: File, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `inline fun <reified T: Any> parse(file: File, config: JSONConfig = JSONConfig.defaultConfig): T?`
- `fun parse(javaType: Type, file: File, config: JSONConfig = JSONConfig.defaultConfig): Any?`
Note that the functions that take a `File` or an `InputStream` do not include provision for specifying a character set;
if a character set other than the default (UTF-8) is required the functions taking a `Reader` may be used, for example:
```kotlin
val json = JSONAuto.parse<List<Person>>(File("path.to.json").reader(Charsets.ISO_8859_1))
```
## Serialize Kotlin object to `JSONValue`
### The `JSONSerializer` object
The `JSONSerializer` object is intended principally for use internally within the `json-kotlin` library itself
(hence the not very user-friendly name).
It has a single public function `serialize()`, which takes the object to be serialized and returns a `JSONValue`
(or `null` if the input is `null`):
```kotlin
val value: JSONValue? = JSONSerializer.serialize(anyObject)
```
As always, a `JSONConfig` may be specified as an optional final parameter.
## Deserialize `JSONValue` to Kotlin object
As with the deserialization of `String` to a Kotlin object, the functions will return `null` if the JSON string is
`"null"`, and they all take a `JSONConfig` as an optional final (or only) parameter.
The examples in this section assume the input is a `JSONValue` resulting from the following `parse()` operation
(see [`jsonutil`](https://github.com/pwall567/jsonutil) for more details):
```kotlin
val jsonValue = JSON.parse("""{"surname":"Smith","firstName":"Bill"}""")
```
### Extension Functions
There are several forms of the `deserialize()` extension function which may be applied to a `JSONValue` (actually a
`JSONValue?`, so the receiver may be null).
#### Implied type
As with deserialization from string, the simplest form of the function is the one that uses the implied type:
```kotlin
val person: Person? = jsonValue.deserialize()
```
#### Kotlin reified type
The same function may be called with the target type as an explicit type parameter:
```kotlin
val person = jsonValue.deserialize<Person>()
```
#### Explicit `KClass`
The class may be specified as a parameter:
```kotlin
val person = jsonValue.deserialize(Person::class)
```
#### Explicit `KType`
The type may be specified as a parameter (see the note about the `as` clause in the description of the string function):
```kotlin
val person = jsonValue.deserialize(Person::class.starProjectedType) as Person
```
### The `JSONDeserializer` object
Like `JSONSerializer`, the `JSONDeserializer` object is intended principally for internal use within `json-kotlin`.
And as with all the other forms of deserialization, there are several options for specifying the target type.
The `JSONDeserializer` object also has some additional functions to help with common cases.
#### Implied type
Again, the simplest form is the one that uses the implied type:
```kotlin
val person: Person? = JSONDeserializer.deserialize(jsonValue)
```
#### Kotlin reified type
And again, the same function may be called with the target type as an explicit type parameter:
```kotlin
val person = JSONDeserializer.deserialize<Person>(jsonValue)
```
#### Explicit `KClass`
The class may be specified as a parameter:
```kotlin
val person = JSONDeserializer.deserialize(Person::class, jsonValue)
```
#### Explicit `KType`
The type may be specified as a parameter (again, see the note about the `as` clause in the description of the string
function):
```kotlin
val person = JSONDeserializer.deserialize(Person::class.starProjectedType, jsonValue) as Person
```
#### Java `Type`
The Java type may also be specified as a parameter (Java `Class` is a subclass of `Type`, but like `KType`, `Type` does
not convey sufficient information to determine the result type so `as` is required):
```kotlin
val person = JSONDeserializer.deserialize(Person::class.java, jsonValue) as Person
```
#### `deserializeNonNull`
The `deserializeNonNull` function deserializes a `JSONValue` to specified `KClass`, throwing an exception if the result
would be `null`:
```kotlin
val person = JSONDeserializer.deserializeNonNull(Person::class, jsonValue)
```
Only the form of the function taking a `KClass` is provided; in the case of a `KType` the nullability of the target is
specified in the `KType` itself.
#### `deserializeAny`
This is a shortcut form of the `deserialize` function when supplied with a type parameter of `Any?`.
See [here](#any) for the effect of specifying a target type of `Any?`.
## Exceptions
Most errors in serialization or deserialization cause a `JSONKotlinException` to be thrown.
The exception has the following available properties:
| Name | Type | Description |
| --------- | ------------- | ---------------------------------------------------------------------------------- |
| `text` | `String` | The specific text for the exception, not including pointer or `cause` |
| `pointer` | `JSONPointer` | A [JSON Pointer](https://tools.ietf.org/html/rfc6901) to the location of the issue |
| `message` | `String` | The conventional exception message, including the pointer |
| `cause` | `Throwable` | The original cause of the exception |
## Further Examples
### Conditional Deserialization
A common requirement is to deserialize an input object into one of a number of child classes in a hierarchy, depending
on a value in the JSON itself.
(Kotlin sealed classes provide one mechanism for this, but their use is not always appropriate.)
An easy way to accomplish this is to deserialize the input JSON into a `JSONValue` structure, and then examine values
directly in that structure to determine the specific target type.
For example:
```kotlin
val json = JSON.parseObject(inputString) ?: throw NullPointerException("JSON must not be null")
val event = when (json["type"].toString()) {
// the toString() above is necessary because json["type"] returns a JSONValue
"open" -> JSONDeserializer.deserialize<OpenEvent>(json)
"close" -> JSONDeserializer.deserialize<CloseEvent>(json)
else -> throw JSONException("Unknown event type")
}
```
### Working with Spring
Many users will wish to use `json-kotlin` in conjunction with the
[Spring Framework](https://spring.io/projects/spring-framework).
An example `Service` class to provide default JSON serialization and deserialization for Spring applications is shown in
the [Spring and `json-kotlin`](SPRING.md) guide.
2021-01-10
<file_sep>/*
* @(#) JSONJavaTest.java
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
public class JSONJavaTest {
private static final String json = "{\"field1\":123,\"field2\":\"abcdef\"}";
private static final String complexJson =
"[{\"field1\":123,\"field2\":\"abcdef\"},{\"field1\":987,\"field2\":\"hello\"}]";
@Test
public void testJSONJavaStringify() {
JavaClass1 javaClass1 = new JavaClass1(123, "abcdef");
assertEquals(json, JSONJava.stringify(javaClass1));
}
@Test
public void testJSONJavaStringifyOfKotlinClass() {
Dummy1 dummy1 = new Dummy1("abcdefghi", 9876543);
String expected = "{\"field1\":\"abcdefghi\",\"field2\":9876543}";
assertEquals(expected, JSONJava.stringify(dummy1));
}
@Test
public void testJSONJavaParseUsingClass() {
JavaClass1 javaClass1 = new JavaClass1(123, "abcdef");
assertEquals(javaClass1, JSONJava.parse(JavaClass1.class, json));
}
@Test
public void testJSONJavaParseOfKotlinClass() {
String jsonDummy1 = "{\"field1\":\"abcdefghi\",\"field2\":9876543}";
Dummy1 expected = new Dummy1("abcdefghi", 9876543);
assertEquals(expected, JSONJava.parse(Dummy1.class, jsonDummy1));
}
@Test
public void testJSONJavaParseUsingType() throws Exception {
List<JavaClass1> javaClass1List = new ArrayList<>();
javaClass1List.add(new JavaClass1(123, "abcdef"));
javaClass1List.add(new JavaClass1(987, "hello"));
Type type = JavaClass2.class.getField("field1").getGenericType();
assertEquals(javaClass1List, JSONJava.parse(type, complexJson));
}
@Test
public void testAddToJSONMapping() {
JSONConfig config = new JSONConfig();
JSONJava.addToJSONMapping(config, Dummy1.class, new Dummy1ToJSON());
JSONObject expected = JSONObject.create().putValue("a", "xyz").putValue("b", 888);
assertEquals(expected, JSONSerializer.INSTANCE.serialize(new Dummy1("xyz", 888), config));
}
@Test
public void testAddFromJSONMapping() {
JSONConfig config = new JSONConfig();
JSONJava.addFromJSONMapping(config, Dummy1.class, new Dummy1FromJSON());
Dummy1 expected = new Dummy1("xyz", 888);
JSONObject json = JSONObject.create().putValue("a", "xyz").putValue("b", 888);
assertEquals(expected, JSONDeserializer.INSTANCE.deserialize(Dummy1.class, json, config));
}
public static class Dummy1ToJSON implements JSONJava.ToJSONMapping<Dummy1> {
@Override
public JSONValue invoke(Dummy1 obj) {
return obj == null ? null :
JSONObject.create().putValue("a", obj.getField1()).putValue("b", obj.getField2());
}
}
public static class Dummy1FromJSON implements JSONJava.FromJSONMapping<Dummy1> {
@Override
public Dummy1 invoke(JSONValue json) {
if (json == null)
return null;
if (!(json instanceof JSONObject))
fail();
JSONObject jsonObject = (JSONObject)json;
return new Dummy1(jsonObject.getString("a"), jsonObject.getInt("b"));
}
}
}
<file_sep>/*
* @(#) JSONKotlinExceptionTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.test.Test
import kotlin.test.assertFailsWith
import kotlin.test.expect
import net.pwall.json.JSONKotlinException.Companion.fail
import net.pwall.json.pointer.JSONPointer
class JSONKotlinExceptionTest {
@Test fun `should create simple exception`() {
val e = JSONKotlinException("Test message")
expect("Test message") { e.text }
expect("Test message") { e.message }
expect(null) { e.pointer }
expect(null) { e.cause }
}
@Test fun `should create exception with root pointer`() {
val e = JSONKotlinException("Test message", JSONPointer.root)
expect("Test message") { e.text }
expect("Test message") { e.message }
expect(JSONPointer.root) { e.pointer }
expect(null) { e.cause }
}
@Test fun `should create exception with pointer`() {
val e = JSONKotlinException("Test message", JSONPointer.root.child(0).child("ace"))
expect("Test message") { e.text }
expect("Test message at /0/ace") { e.message }
expect(JSONPointer("/0/ace")) { e.pointer }
expect(null) { e.cause }
}
@Test fun `should create exception with cause`() {
val nested = JSONException("Nested")
val e = JSONKotlinException("Test message", nested)
expect("Test message") { e.text }
expect("Test message") { e.message }
expect(null) { e.pointer }
expect(nested) { e.cause }
}
@Test fun `should create exception with pointer and cause`() {
val nested = JSONException("Nested")
val e = JSONKotlinException("Test message", JSONPointer.root.child(0).child("ace"), nested)
expect("Test message") { e.text }
expect("Test message at /0/ace") { e.message }
expect(JSONPointer("/0/ace")) { e.pointer }
expect(nested) { e.cause }
}
@Test fun `should throw simple exception`() {
val e = assertFailsWith<JSONKotlinException> { fail("Test message") }
expect("Test message") { e.text }
expect("Test message") { e.message }
expect(null) { e.pointer }
expect(null) { e.cause }
}
@Test fun `should throw exception with root pointer`() {
val e = assertFailsWith<JSONKotlinException> { fail("Test message", JSONPointer.root) }
expect("Test message") { e.text }
expect("Test message") { e.message }
expect(JSONPointer.root) { e.pointer }
expect(null) { e.cause }
}
@Test fun `should throw exception with pointer`() {
val e = assertFailsWith<JSONKotlinException> { fail("Test message", JSONPointer.root.child(0).child("ace")) }
expect("Test message") { e.text }
expect("Test message at /0/ace") { e.message }
expect(JSONPointer("/0/ace")) { e.pointer }
expect(null) { e.cause }
}
@Test fun `should throw exception with cause`() {
val nested = JSONException("Nested")
val e = assertFailsWith<JSONKotlinException> { fail("Test message", nested) }
expect("Test message") { e.text }
expect("Test message") { e.message }
expect(null) { e.pointer }
expect(nested) { e.cause }
}
@Test fun `should throw exception with pointer and cause`() {
val nested = JSONException("Nested")
val e = assertFailsWith<JSONKotlinException> {
fail("Test message", JSONPointer.root.child(0).child("ace"), nested)
}
expect("Test message") { e.text }
expect("Test message at /0/ace") { e.message }
expect(JSONPointer("/0/ace")) { e.pointer }
expect(nested) { e.cause }
}
}
<file_sep>/*
* @(#) JSONTypeRef.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import java.lang.reflect.ParameterizedType
/**
* Implementation of the [TypeReference](https://gafter.blogspot.com/2006/12/super-type-tokens.html) pattern.
*
* @author <NAME> (with acknowledgements to the author of the above-referenced article)
* @param T the target type
*/
open class JSONTypeRef<T>(nullable: Boolean = false) {
/** The type reference */
val refType = (this::class.java.genericSuperclass as ParameterizedType).actualTypeArguments[0].toKType(nullable)
companion object {
/**
* Create a [JSONTypeRef] for the target type.
*
* @param T the target type
* @return the [JSONTypeRef]
*/
inline fun <reified T> create(nullable: Boolean = false): JSONTypeRef<T> = object : JSONTypeRef<T>(nullable) {}
}
}
<file_sep>/*
* @(#) JSONKotlinException.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import net.pwall.json.pointer.JSONPointer
/**
* Exception class for errors in serialization and deserialization.
*
* @author <NAME>
*/
class JSONKotlinException(val text: String, val pointer: JSONPointer? = null) : JSONException(text) {
constructor(text: String, pointer: JSONPointer, nested: Exception) : this(text, pointer) {
initCause(nested)
}
constructor(text: String, nested: Exception) : this(text) {
initCause(nested)
}
override val message: String
get() = when (pointer) {
null,
JSONPointer.root -> text
else -> "$text at $pointer"
}
companion object {
// the name "fail" may clash with "kotlin.test.fail", so these functions are marked "internal"
internal fun fail(text: String, pointer: JSONPointer? = null): Nothing {
throw JSONKotlinException(text, pointer)
}
internal fun fail(text: String, pointer: JSONPointer, nested: Exception): Nothing {
throw JSONKotlinException(text, pointer, nested)
}
internal fun fail(text: String, nested: Exception): Nothing {
throw JSONKotlinException(text, nested)
}
}
}
<file_sep>/*
* @(#) JSONFun.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.KTypeProjection
import kotlin.reflect.full.createType
import kotlin.reflect.full.starProjectedType
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
import java.lang.reflect.WildcardType
import java.math.BigDecimal
import java.math.BigInteger
import net.pwall.json.JSONKotlinException.Companion.fail
/** Type alias for `JSONInt` to make it closer to Kotlin standard class names. */
typealias JSONInt = JSONInteger
/** Type alias to simplify the definition of `fromJSON` mapping functions. */
typealias FromJSONMapping = (JSONValue?) -> Any?
/** Type alias to simplify the definition of `toJSON` mapping functions. */
typealias ToJSONMapping = (Any?) -> JSONValue?
/**
* More Kotlin-like conversion function name.
*
* @return the value as a [BigInteger]
*/
fun JSONNumberValue.toBigInteger(): BigInteger = bigIntegerValue()
/**
* More Kotlin-like conversion function name.
*
* @return the value as a [BigDecimal]
*/
fun JSONNumberValue.toBigDecimal(): BigDecimal = bigDecimalValue()
/**
* Convert a [CharSequence] ([String], [StringBuilder] etc.) to a [JSONValue].
*
* @receiver the [CharSequence] to be converted
* @return the [JSONValue]
*/
fun CharSequence.asJSONValue(): JSONValue = JSONString(this)
/**
* Convert a [Char] to a [JSONValue].
*
* @receiver the [Char] to be converted
* @return the [JSONValue]
*/
fun Char.asJSONValue(): JSONValue = JSONString(StringBuilder().append(this))
/**
* Convert an [Int] to a [JSONValue].
*
* @receiver the [Int] to be converted
* @return the [JSONValue]
*/
fun Int.asJSONValue(): JSONValue = JSONInt.valueOf(this)
/**
* Convert a [Long] to a [JSONValue].
*
* @receiver the [Long] to be converted
* @return the [JSONValue]
*/
fun Long.asJSONValue(): JSONValue = JSONLong.valueOf(this)
/**
* Convert a [Short] to a [JSONValue].
*
* @receiver the [Short] to be converted
* @return the [JSONValue]
*/
fun Short.asJSONValue(): JSONValue = JSONInt.valueOf(this.toInt())
/**
* Convert a [Byte] to a [JSONValue].
*
* @receiver the [Byte] to be converted
* @return the [JSONValue]
*/
fun Byte.asJSONValue(): JSONValue = JSONInt.valueOf(this.toInt())
/**
* Convert a [Float] to a [JSONValue].
*
* @receiver the [Float] to be converted
* @return the [JSONValue]
*/
fun Float.asJSONValue(): JSONValue = JSONFloat.valueOf(this)
/**
* Convert a [Double] to a [JSONValue].
*
* @receiver the [Double] to be converted
* @return the [JSONValue]
*/
fun Double.asJSONValue(): JSONValue = JSONDouble.valueOf(this)
/**
* Convert a [Boolean] to a [JSONValue].
*
* @receiver the [Boolean] to be converted
* @return the [JSONValue]
*/
fun Boolean.asJSONValue(): JSONValue = JSONBoolean.valueOf(this)
/**
* Convert any object to a [JSONValue].
*
* @receiver the object to be converted
* @param config an optional [JSONConfig] to customise the conversion
* @return the [JSONValue]
*/
fun Any?.asJSONValue(config: JSONConfig = JSONConfig.defaultConfig): JSONValue? = JSONSerializer.serialize(this, config)
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param str a [CharSequence] ([String], [StringBuilder] etc.)
* @return the [Pair]
*/
infix fun String.isJSON(str: CharSequence?): Pair<String, JSONValue?> = this to str?.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param ch a [Char]
* @return the [Pair]
*/
infix fun String.isJSON(ch: Char): Pair<String, JSONValue?> = this to ch.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param i an [Int]
* @return the [Pair]
*/
infix fun String.isJSON(i: Int): Pair<String, JSONValue?> = this to i.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param i a [Long]
* @return the [Pair]
*/
infix fun String.isJSON(i: Long): Pair<String, JSONValue?> = this to i.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param s a [Short]
* @return the [Pair]
*/
infix fun String.isJSON(s: Short): Pair<String, JSONValue?> = this to s.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param b a [Byte]
* @return the [Pair]
*/
infix fun String.isJSON(b: Byte): Pair<String, JSONValue?> = this to b.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param f a [Float]
* @return the [Pair]
*/
infix fun String.isJSON(f: Float): Pair<String, JSONValue?> = this to f.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param d a [Double]
* @return the [Pair]
*/
infix fun String.isJSON(d: Double): Pair<String, JSONValue?> = this to d.asJSONValue()
/**
* Create a [Pair] of [String] and [JSONValue]? for use with [makeJSON].
*
* @receiver the [String]
* @param b a [Boolean]
* @return the [Pair]
*/
infix fun String.isJSON(b: Boolean): Pair<String, JSONValue?> = this to b.asJSONValue()
/**
* Create a [JSONObject] from a list of [Pair]s of [String]s and [JSONValue]s.
*
* @param pairs the list of pairs
* @return the [JSONObject]
*/
fun makeJSON(vararg pairs: Pair<String, JSONValue?>) = JSONObject().apply { putAll(pairs) }
/**
* Deserialize JSON from string ([CharSequence]) to a specified [KType].
*
* @receiver the JSON in string form
* @param resultType the target type
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun CharSequence.parseJSON(resultType: KType, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONAuto.parse(resultType, this, config)
/**
* Deserialize JSON from string ([CharSequence]) to a specified [KClass].
*
* @receiver the JSON in string form
* @param resultClass the target class
* @param config an optional [JSONConfig] to customise the conversion
* @param T the target class
* @return the converted object
*/
fun <T: Any> CharSequence.parseJSON(resultClass: KClass<T>, config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONAuto.parse(resultClass, this, config)
/**
* Deserialize JSON from string ([CharSequence]) to a the inferred [KClass].
*
* @receiver the JSON in string form
* @param config an optional [JSONConfig] to customise the conversion
* @param T the target class
* @return the converted object
*/
inline fun <reified T: Any> CharSequence.parseJSON(config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONAuto.parse(this, config)
/**
* Stringify any object to JSON.
*
* @receiver the object to be converted to JSON (`null` will be converted to `"null"`).
* @param config an optional [JSONConfig] to customise the conversion
* @return the JSON string
*/
fun Any?.stringifyJSON(config: JSONConfig = JSONConfig.defaultConfig): String = JSONStringify.stringify(this, config)
/**
* Helper method to create a [KType] for a parameterised type, for use as the target type of a deserialization.
*
* @param mainClass the parameterised class
* @param paramClasses the parameter classes
* @param nullable `true` if the [KType] is to be nullable
* @return the [KType]
*/
fun targetKType(mainClass: KClass<*>, vararg paramClasses: KClass<*>, nullable: Boolean = false): KType =
mainClass.createType(paramClasses.map { KTypeProjection.covariant(it.starProjectedType) }, nullable)
/**
* Helper method to create a [KType] for a parameterised type, for use as the target type of a deserialization.
*
* @param mainClass the parameterised class
* @param paramTypes the parameter types
* @param nullable `true` if the [KType] is to be nullable
* @return the [KType]
*/
fun targetKType(mainClass: KClass<*>, vararg paramTypes: KType, nullable: Boolean = false): KType =
mainClass.createType(paramTypes.map { KTypeProjection.covariant(it) }, nullable)
/**
* Convert a Java [Type] to a Kotlin [KType]. This allows Java [Type]s to be used as the target type of a
* deserialization operation.
*
* @receiver the Java [Type] to be converted
* @param nullable `true` if the [KType] is to be nullable
* @return the resulting Kotlin [KType]
* @throws JSONKotlinException if the [Type] can not be converted
*/
fun Type.toKType(nullable: Boolean = false): KType = when (this) {
is Class<*> -> this.kotlin.createType(nullable = nullable)
is ParameterizedType -> (this.rawType as Class<*>).kotlin.createType(this.actualTypeArguments.map {
when (it) {
is WildcardType ->
if (it.lowerBounds?.firstOrNull() == null)
KTypeProjection.covariant(it.upperBounds[0].toKType(true))
else
KTypeProjection.contravariant(it.lowerBounds[0].toKType(true))
else -> KTypeProjection.invariant(it.toKType(true))
} }, nullable)
else -> fail("Can't handle type: $this")
}
/**
* Deserialize a [JSONValue] to the nominated [KType].
*
* @receiver the [JSONValue] (or `null`)
* @param resultType the target [KType]
* @param config an optional [JSONConfig] to customise the conversion
* @throws JSONKotlinException if the value can not be converted
*/
fun JSONValue?.deserialize(resultType: KType, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(resultType, this, config)
/**
* Deserialize a [JSONValue] to the nominated [KClass].
*
* @receiver the [JSONValue] (or `null`)
* @param resultClass the target [KClass]
* @param config an optional [JSONConfig] to customise the conversion
* @param T the target class
* @throws JSONKotlinException if the value can not be converted
*/
fun <T: Any> JSONValue?.deserialize(resultClass: KClass<T>, config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONDeserializer.deserialize(resultClass, this, config)
/**
* Deserialize a [JSONValue] to the inferred class.
*
* @receiver the [JSONValue] (or `null`)
* @param config an optional [JSONConfig] to customise the conversion
* @param T the target class
* @throws JSONKotlinException if the value can not be converted
*/
inline fun <reified T: Any> JSONValue?.deserialize(config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONDeserializer.deserialize(this, config)
/**
* Deserialize a [JSONValue] to the nominated Java [Type].
*
* @receiver the [JSONValue] (or `null`)
* @param javaType the target [Type]
* @param config an optional [JSONConfig] to customise the conversion
* @throws JSONKotlinException if the value can not be converted
*/
fun JSONValue?.deserialize(javaType: Type, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(javaType, this, config)
<file_sep>/*
* @(#) JSONSerializerTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.math.abs
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlin.test.expect
import kotlin.test.Test
import java.math.BigDecimal
import java.math.BigInteger
import java.net.URI
import java.net.URL
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.MonthDay
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.Period
import java.time.Year
import java.time.YearMonth
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.util.BitSet
import java.util.Calendar
import java.util.TimeZone
import java.util.UUID
import java.util.stream.IntStream
import java.util.stream.Stream
class JSONSerializerTest {
@Test fun `null should return null`() {
assertNull(JSONSerializer.serialize(null))
}
@Test fun `JSONValue should be returned as-is`() {
val json = JSONInt(12345)
assertSame(json, JSONSerializer.serialize(json))
}
@Test fun `String should return JSONString`() {
val str = "Hello JSON!"
expect(JSONString(str)) { JSONSerializer.serialize(str) }
}
@Test fun `StringBuilder should return JSONString`() {
val str = "Hello JSON!"
val sb = StringBuilder(str)
expect(JSONString(str)) { JSONSerializer.serialize(sb) }
}
@Test fun `Char should return JSONString`() {
val char = 'Q'
expect(JSONString("Q")) { JSONSerializer.serialize(char) }
}
@Test fun `Int should return JSONInt`() {
val i = 123456
val actual = JSONSerializer.serialize(i)
assertTrue(actual is JSONInt)
assertTrue(intEquals(i, actual.value))
// Note - these assertions are complicated because JSONInt.equals() returns true
// for any comparison with another numeric JSON types where the values are equal
}
@Test fun `Int (negative) should return JSONInt`() {
val i = -8888
val actual = JSONSerializer.serialize(i)
assertTrue(actual is JSONInt)
assertTrue(intEquals(i, actual.value))
}
@Test fun `Long should return JSONLong`() {
val i = 12345678901234
val actual = JSONSerializer.serialize(i)
assertTrue(actual is JSONLong)
assertTrue(longEquals(i, actual.value))
}
@Test fun `Long (negative) should return JSONLong`() {
val i = -987654321987654321
val actual = JSONSerializer.serialize(i)
assertTrue(actual is JSONLong)
assertTrue(longEquals(i, actual.value))
}
@Test fun `Short should return JSONInt`() {
val i: Short = 1234
val actual = JSONSerializer.serialize(i)
assertTrue(actual is JSONInt)
assertTrue(intEquals(i.toInt(), actual.value))
}
@Test fun `Byte should return JSONInt`() {
val i: Byte = 123
val actual = JSONSerializer.serialize(i)
assertTrue(actual is JSONInt)
assertTrue(intEquals(i.toInt(), actual.value))
}
@Test fun `Float should return JSONFloat`() {
val f = 0.1234F
val actual = JSONSerializer.serialize(f)
assertTrue(actual is JSONFloat)
assertTrue(floatEquals(f, actual.value))
}
@Test fun `Float (negative) should return JSONFloat`() {
val f = -88.987F
val actual = JSONSerializer.serialize(f)
assertTrue(actual is JSONFloat)
assertTrue(floatEquals(f, actual.value))
}
@Test fun `Double should return JSONDouble`() {
val d = 987.654321
val actual = JSONSerializer.serialize(d)
assertTrue(actual is JSONDouble)
assertTrue(doubleEquals(d, actual.value))
}
@Test fun `Double (exponent notation) should return JSONDouble`() {
val d = 1e40
val actual = JSONSerializer.serialize(d)
assertTrue(actual is JSONDouble)
assertTrue(doubleEquals(d, actual.value))
}
@Test fun `Boolean should return JSONBoolean`() {
val t = true
assertSame(JSONBoolean.TRUE, JSONSerializer.serialize(t))
val f = false
assertSame(JSONBoolean.FALSE, JSONSerializer.serialize(f))
}
@Test fun `CharArray should return JSONString`() {
val ca = charArrayOf('H', 'e', 'l', 'l', 'o', '!')
expect(JSONString("Hello!")) { JSONSerializer.serialize(ca) }
}
@Test fun `Array of Char should return JSONString`() {
val ca = arrayOf('H', 'e', 'l', 'l', 'o', '!')
expect(JSONString("Hello!")) { JSONSerializer.serialize(ca) }
}
@Test fun `Array of Int should return JSONArray`() {
val array = arrayOf(123, 2345, 0, 999)
val expected = JSONArray().apply {
addValue(123)
addValue(2345)
addValue(0)
addValue(999)
}
expect(expected) { JSONSerializer.serialize(array) }
}
@Test fun `Array of Int nullable should return JSONArray`() {
val array = arrayOf(123, null, 0, 999)
val expected = JSONArray().apply {
addValue(123)
addNull()
addValue(0)
addValue(999)
}
expect(expected) { JSONSerializer.serialize(array) }
}
@Test fun `Array of String should return JSONArray`() {
val array = arrayOf("Hello", "Kotlin")
val expected = JSONArray().apply {
addValue("Hello")
addValue("Kotlin")
}
expect(expected) { JSONSerializer.serialize(array) }
}
@Test fun `Iterator of String should return JSONArray`() {
val iterator = listOf("Hello", "Kotlin").iterator()
val expected = JSONArray().apply {
addValue("Hello")
addValue("Kotlin")
}
expect(expected) { JSONSerializer.serialize(iterator) }
}
@Test fun `Enumeration of String should return JSONArray`() {
val list = listOf("Hello", "Kotlin")
val expected = JSONArray().apply {
addValue("Hello")
addValue("Kotlin")
}
expect(expected) { JSONSerializer.serialize(ListEnum(list)) }
}
@Test fun `List of String should return JSONArray`() {
val list = listOf("Hello", "Kotlin")
val expected = JSONArray().apply {
addValue("Hello")
addValue("Kotlin")
}
expect(expected) { JSONSerializer.serialize(list) }
}
@Test fun `Sequence of String should return JSONArray`() {
val seq = listOf("Hello", "Kotlin").asSequence()
val expected = JSONArray().apply {
addValue("Hello")
addValue("Kotlin")
}
expect(expected) { JSONSerializer.serialize(seq) }
}
@Test fun `Map of String to Int should return JSONObject`() {
val map = mapOf("abc" to 1, "def" to 4, "ghi" to 999)
val expected = JSONObject().apply {
putValue("abc", 1)
putValue("def", 4)
putValue("ghi", 999)
}
expect(expected) { JSONSerializer.serialize(map) }
}
@Test fun `Map of String to String nullable should return JSONObject`() {
val map = mapOf("abc" to "hello", "def" to null, "ghi" to "goodbye")
val expected = JSONObject().apply {
putValue("abc", "hello")
putNull("def")
putValue("ghi", "goodbye")
}
expect(expected) { JSONSerializer.serialize(map) }
}
@Test fun `Class with toJSON() should serialize as JSONObject`() {
val obj = DummyFromJSON(23)
val expected = JSONObject().apply {
putValue("dec", "23")
putValue("hex", "17")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Enum should serialize as JSONString`() {
val eee = DummyEnum.GAMMA
expect(JSONString("GAMMA")) { JSONSerializer.serialize(eee) }
}
@Test fun `Calendar should return JSONString`() {
val cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")).apply {
set(Calendar.YEAR, 2019)
set(Calendar.MONTH, 3)
set(Calendar.DAY_OF_MONTH, 25)
set(Calendar.HOUR_OF_DAY, 18)
set(Calendar.MINUTE, 52)
set(Calendar.SECOND, 47)
set(Calendar.MILLISECOND, 123)
set(Calendar.ZONE_OFFSET, 10 * 60 * 60 * 1000)
}
expect(JSONString("2019-04-25T18:52:47.123+10:00")) { JSONSerializer.serialize(cal) }
}
@Test fun `Date should return JSONString`() {
val cal = Calendar.getInstance().apply {
set(Calendar.YEAR, 2019)
set(Calendar.MONTH, 3)
set(Calendar.DAY_OF_MONTH, 25)
set(Calendar.HOUR_OF_DAY, 18)
set(Calendar.MINUTE, 52)
set(Calendar.SECOND, 47)
set(Calendar.MILLISECOND, 123)
set(Calendar.ZONE_OFFSET, 10 * 60 * 60 * 1000)
}
val date = cal.time
// NOTE - Java implementations are inconsistent - some will normalise the time to UTC
// while others preserve the time zone as supplied. The test below allows for either.
val expected1 = JSONString("2019-04-25T18:52:47.123+10:00")
val expected2 = JSONString("2019-04-25T08:52:47.123Z")
val result = JSONSerializer.serialize(date)
expect(true) { result == expected1 || result == expected2 }
}
@Test fun `java-sql-Date should return JSONString`() {
val str = "2019-04-25"
val date = java.sql.Date.valueOf(str)
expect(JSONString(str)) { JSONSerializer.serialize(date) }
}
@Test fun `java-sql-Time should return JSONString`() {
val str = "22:41:19"
val time = java.sql.Time.valueOf(str)
expect(JSONString(str)) { JSONSerializer.serialize(time) }
}
@Test fun `java-sql-Timestamp should return JSONString`() {
val str = "2019-04-25 22:41:19.5"
val timestamp = java.sql.Timestamp.valueOf(str)
expect(JSONString(str)) { JSONSerializer.serialize(timestamp) }
}
@Test fun `Instant should return JSONString`() {
val str = "2019-04-25T21:01:09.456Z"
val inst = Instant.parse(str)
expect(JSONString(str)) { JSONSerializer.serialize(inst) }
}
@Test fun `LocalDate should return JSONString`() {
val date = LocalDate.of(2019, 4, 25)
expect(JSONString("2019-04-25")) { JSONSerializer.serialize(date) }
}
@Test fun `LocalDateTime should return JSONString`() {
val date = LocalDateTime.of(2019, 4, 25, 21, 6, 5)
expect(JSONString("2019-04-25T21:06:05")) { JSONSerializer.serialize(date) }
}
@Test fun `LocalTime should return JSONString`() {
val date = LocalTime.of(21, 6, 5)
expect(JSONString("21:06:05")) { JSONSerializer.serialize(date) }
}
@Test fun `OffsetTime should return JSONString`() {
val time = OffsetTime.of(21, 6, 5, 456000000, ZoneOffset.ofHours(10))
expect(JSONString("21:06:05.456+10:00")) { JSONSerializer.serialize(time) }
}
@Test fun `OffsetDateTime should return JSONString`() {
val time = OffsetDateTime.of(2019, 4, 25, 21, 6, 5, 456000000, ZoneOffset.ofHours(10))
expect(JSONString("2019-04-25T21:06:05.456+10:00")) { JSONSerializer.serialize(time) }
}
@Test fun `ZonedDateTime should return JSONString`() {
val zdt = ZonedDateTime.of(2019, 4, 25, 21, 16, 23, 123000000, ZoneId.of("Australia/Sydney"))
expect(JSONString("2019-04-25T21:16:23.123+10:00[Australia/Sydney]")) { JSONSerializer.serialize(zdt) }
}
@Test fun `Year should return JSONString`() {
val year = Year.of(2019)
expect(JSONString("2019")) { JSONSerializer.serialize(year) }
}
@Test fun `YearMonth should return JSONString`() {
val yearMonth = YearMonth.of(2019, 4)
expect(JSONString("2019-04")) { JSONSerializer.serialize(yearMonth) }
}
@Test fun `MonthDay should return JSONString`() {
val month = MonthDay.of(4, 23)
expect(JSONString("--04-23")) { JSONSerializer.serialize(month) }
}
@Test fun `Duration should return JSONString`() {
val duration = Duration.ofHours(2)
expect(JSONString("PT2H")) { JSONSerializer.serialize(duration) }
}
@Test fun `Period should return JSONString`() {
val period = Period.ofMonths(3)
expect(JSONString("P3M")) { JSONSerializer.serialize(period) }
}
@Test fun `UUID should return JSONString`() {
val uuidString = "12ce3730-2d97-11e7-aeed-67b0e6bf0ed7"
val uuid = UUID.fromString(uuidString)
expect(JSONString(uuidString)) { JSONSerializer.serialize(uuid) }
}
@Test fun `URI should return JSONString`() {
val uriString = "http://pwall.net"
val uri = URI(uriString)
expect(JSONString(uriString)) { JSONSerializer.serialize(uri) }
}
@Test fun `URL should return JSONString`() {
val urlString = "http://pwall.net"
val url = URL(urlString)
expect(JSONString(urlString)) { JSONSerializer.serialize(url) }
}
@Test fun `BigInteger should return JSONLong`() {
val bigIntLong = 123456789012345678L
val bigInteger = BigInteger.valueOf(bigIntLong)
expect(JSONLong(bigIntLong)) { JSONSerializer.serialize(bigInteger) }
}
@Test fun `BigInteger should return JSONString when config option selected`() {
val bigIntString = "123456789012345678"
val bigInteger = BigInteger(bigIntString)
val config = JSONConfig().apply {
bigIntegerString = true
}
expect(JSONString(bigIntString)) { JSONSerializer.serialize(bigInteger, config) }
}
@Test fun `BigDecimal should return JSONDecimal`() {
val bigDecString = "12345678901234567890.88888"
val bigDecimal = BigDecimal(bigDecString)
expect(JSONDecimal(bigDecString)) { JSONSerializer.serialize(bigDecimal) }
}
@Test fun `BigDecimal should return JSONString when config option selected`() {
val bigDecString = "12345678901234567890.88888"
val bigDecimal = BigDecimal(bigDecString)
val config = JSONConfig().apply {
bigDecimalString = true
}
expect(JSONString(bigDecString)) { JSONSerializer.serialize(bigDecimal, config) }
}
@Test fun `BitSet should return JSONArray`() {
val bitSet = BitSet(4)
bitSet.set(1)
bitSet.set(3)
val expected = JSONArray().apply {
addValue(1)
addValue(3)
}
expect(expected) { JSONSerializer.serialize(bitSet) }
}
@Test fun `Simple data class should return JSONObject`() {
val obj = Dummy1("abc", 123)
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("field2", 123)
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Simple data class with extra property should return JSONObject`() {
val obj = Dummy2("abc", 123)
obj.extra = "qqqqq"
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("field2", 123)
putValue("extra", "qqqqq")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Simple data class with optional field should omit null field`() {
val obj = Dummy2("abc", 123)
obj.extra = null
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("field2", 123)
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Simple data class with optional field should include null field when config set`() {
val obj = Dummy2("abc", 123)
obj.extra = null
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("field2", 123)
putNull("extra")
}
val config = JSONConfig().apply {
includeNulls = true
}
expect(expected) { JSONSerializer.serialize(obj, config) }
}
@Test fun `Derived class should return JSONObject`() {
val obj = Derived()
obj.field1 = "qwerty"
obj.field2 = 98765
obj.field3 = 0.012
val expected = JSONObject().apply {
putValue("field1", "qwerty")
putValue("field2", 98765)
putValue("field3", 0.012)
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Annotated class should return JSONObject using specified name`() {
val obj = DummyWithNameAnnotation()
obj.field1 = "qwerty"
obj.field2 = 98765
val expected = JSONObject().apply {
putValue("field1", "qwerty")
putValue("fieldX", 98765)
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Annotated data class should return JSONObject using specified name`() {
val obj = DummyWithParamNameAnnotation("abc", 123)
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("fieldX", 123)
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Annotated data class with custom annotation should return JSONObject using specified name`() {
val obj = DummyWithCustomNameAnnotation("abc", 123)
val config = JSONConfig().apply {
addNameAnnotation(CustomName::class, "symbol")
}
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("fieldX", 123)
}
expect(expected) { JSONSerializer.serialize(obj, config) }
}
@Test fun `Nested class should return nested JSONObject`() {
val obj1 = Dummy1("asdfg", 987)
val obj3 = Dummy3(obj1, "what?")
val expected1 = JSONObject().apply {
putValue("field1", "asdfg")
putValue("field2", 987)
}
val expected = JSONObject().apply {
put("dummy1", expected1)
putValue("text", "what?")
}
expect(expected) { JSONSerializer.serialize(obj3) }
}
@Test fun `Class with @JSONIgnore should return JSONObject skipping field`() {
val obj = DummyWithIgnore("alpha", "beta", "gamma")
val expected = JSONObject().apply {
putValue("field1", "alpha")
putValue("field3", "gamma")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Class with custom ignore annotation should return JSONObject skipping field`() {
val obj = DummyWithCustomIgnore("alpha", "beta", "gamma")
val config = JSONConfig().apply {
addIgnoreAnnotation(CustomIgnore::class)
}
val expected = JSONObject().apply {
putValue("field1", "alpha")
putValue("field3", "gamma")
}
expect(expected) { JSONSerializer.serialize(obj, config) }
}
@Test fun `Class with @JSONIncludeIfNull should include null field`() {
val obj = DummyWithIncludeIfNull("alpha", null, "gamma")
val expected = JSONObject().apply {
putValue("field1", "alpha")
putNull("field2")
putValue("field3", "gamma")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Class with custom include if null annotation should include null field`() {
val obj = DummyWithCustomIncludeIfNull("alpha", null, "gamma")
val config = JSONConfig().apply {
addIncludeIfNullAnnotation(CustomIncludeIfNull::class)
}
val expected = JSONObject().apply {
putValue("field1", "alpha")
putNull("field2")
putValue("field3", "gamma")
}
expect(expected) { JSONSerializer.serialize(obj, config) }
}
@Test fun `Class with @JSONIncludeAllProperties should include null field`() {
val obj = DummyWithIncludeAllProperties("alpha", null, "gamma")
val expected = JSONObject().apply {
putValue("field1", "alpha")
putNull("field2")
putValue("field3", "gamma")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Class with custom include all properties annotation should include null field`() {
val obj = DummyWithCustomIncludeAllProperties("alpha", null, "gamma")
val config = JSONConfig().apply {
addIncludeAllPropertiesAnnotation(CustomIncludeAllProperties::class)
}
val expected = JSONObject().apply {
putValue("field1", "alpha")
putNull("field2")
putValue("field3", "gamma")
}
expect(expected) { JSONSerializer.serialize(obj, config) }
}
@Test fun `Pair should return JSONArray`() {
val pair = "xyz" to "abc"
val expected = JSONArray().apply {
add(JSONString("xyz"))
add(JSONString("abc"))
}
expect(expected) { JSONSerializer.serialize(pair) }
}
@Test fun `Triple should return JSONArray`() {
val triple = Triple("xyz","abc","def")
val expected = JSONArray().apply {
add(JSONString("xyz"))
add(JSONString("abc"))
add(JSONString("def"))
}
expect(expected) { JSONSerializer.serialize(triple) }
}
@Test fun `Heterogenous Triple should return JSONArray`() {
val triple = Triple("xyz",88,"def")
val expected = JSONArray().apply {
add(JSONString("xyz"))
add(JSONInt(88))
add(JSONString("def"))
}
expect(expected) { JSONSerializer.serialize(triple) }
}
@Test fun `object should return JSONObject()`() {
val obj = DummyObject
expect(JSONObject().putValue("field1", "abc")) { JSONSerializer.serialize(obj) }
}
@Test fun `nested object should return JSONObject()`() {
val obj = NestedDummy()
val nested = JSONObject().putValue("field1", "abc")
expect(JSONObject().putJSON("obj", nested)) { JSONSerializer.serialize(obj) }
}
@Test fun `class with constant val should serialize correctly`() {
val constClass = DummyWithVal()
expect(JSONObject().putValue("field8", "blert")) { JSONSerializer.serialize(constClass) }
}
@Test fun `java class should serialize correctly`() {
val javaClass1 = JavaClass1(1234, "Hello!")
val expected = JSONObject().apply {
putValue("field1", 1234)
putValue("field2", "Hello!")
}
expect(expected) { JSONSerializer.serialize(javaClass1) }
}
@Test fun `List derived class should serialize to JSONArray`() {
val obj = DummyList(listOf(LocalDate.of(2019, 10, 6), LocalDate.of(2019, 10, 5)))
val expected = JSONArray().apply {
addValue("2019-10-06")
addValue("2019-10-05")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `Map derived class should serialize to JSONObject`() {
val obj = DummyMap(emptyMap()).apply {
put("aaa", LocalDate.of(2019, 10, 6))
put("bbb", LocalDate.of(2019, 10, 5))
}
val expected = JSONObject().apply {
putValue("aaa", "2019-10-06")
putValue("bbb", "2019-10-05")
}
expect(expected) { JSONSerializer.serialize(obj) }
}
@Test fun `sealed class should serialize with extra member to indicate derived class`() {
val expected = JSONObject().apply {
putValue("class", "Const")
putValue("number", 2.0)
}
expect(expected) { JSONSerializer.serialize(Const(2.0)) }
}
@Test fun `sealed class object should serialize correctly`() {
val expected = JSONObject().apply {
putValue("class", "NotANumber")
}
expect(expected) { JSONSerializer.serialize(NotANumber) }
}
@Test fun `sealed class should serialize with custom discriminator`() {
val config = JSONConfig().apply {
sealedClassDiscriminator = "?"
}
val expected = JSONObject().apply {
putValue("?", "Const")
putValue("number", 2.0)
}
expect(expected) { JSONSerializer.serialize(Const(2.0), config) }
}
@Test fun `should fail on use of circular reference`() {
val circular1 = Circular1()
val circular2 = Circular2()
circular1.ref = circular2
circular2.ref = circular1
val exception = assertFailsWith<JSONKotlinException> {
JSONSerializer.serialize(circular1)
}
expect("Circular reference: field ref in Circular2") { exception.message }
}
@Test fun `should omit null members`() {
val dummy5 = Dummy5(null, 123)
val serialized = JSONSerializer.serialize(dummy5)
expect(true) { serialized is JSONObject }
expect(1) { (serialized as JSONObject).size }
}
@Test fun `should serialize Java Stream of strings`() {
val stream = Stream.of("abc", "def")
val serialized = JSONSerializer.serialize(stream)
expect(true) { serialized is JSONSequence<*> }
with(serialized as JSONSequence<*>) {
expect(2) { size }
expect(JSONString("abc")) { get(0) }
expect(JSONString("def")) { get(1) }
}
}
@Test fun `should serialize Java IntStream`() {
val stream = IntStream.of(987, 654, 321)
val serialized = JSONSerializer.serialize(stream)
expect(true) { serialized is JSONSequence<*> }
with(serialized as JSONSequence<*>) {
expect(3) { size }
expect(JSONInt(987)) { get(0) }
expect(JSONInt(654)) { get(1) }
expect(JSONInt(321)) { get(2) }
}
}
private fun intEquals(a: Int, b: Int): Boolean {
return a == b
}
private fun longEquals(a: Long, b: Long): Boolean {
return a == b
}
private fun floatEquals(a: Float, b: Float): Boolean {
return abs(a - b) < 0.0000001
}
private fun doubleEquals(a: Double, b: Double): Boolean {
return abs(a - b) < 0.000000001
}
}
<file_sep>/*
* @(#) JSONConfigTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.full.createType
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.expect
import kotlin.test.Test
import kotlin.test.assertTrue
import kotlin.test.fail
class JSONConfigTest {
private val stringType = String::class.createType()
@Test fun `add fromJSON mapping should return the function`() {
val config = JSONConfig()
expect(8192) { config.readBufferSize }
expect(Charsets.UTF_8) { config.charset }
assertNull(config.findFromJSONMapping(stringType))
assertNull(config.findFromJSONMapping(String::class))
config.fromJSON { json -> json?.toString() }
assertNotNull(config.findFromJSONMapping(stringType))
assertNotNull(config.findFromJSONMapping(String::class))
}
@Test fun `fromJSON mapping should map simple data class`() {
val config = JSONConfig().apply {
fromJSON { json ->
if (json !is JSONObject)
fail("Must be JSONObject")
Dummy1(json.getString("a"), json.getInt("b"))
}
}
val json = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
expect(Dummy1("xyz", 888)) { JSONDeserializer.deserialize(Dummy1::class.createType(), json, config) }
}
@Test fun `fromJSON mapping should not interfere with other deserialization`() {
val config = JSONConfig().apply {
fromJSON { json ->
if (json !is JSONObject)
fail("Must be JSONObject")
Dummy1(json.getString("a"), json.getInt("b"))
}
}
val json = JSONArray(JSONString("AAA"), JSONString("BBB"))
val result = JSONDeserializer.deserialize<List<Any>>(json, config)
expect(listOf("AAA", "BBB")) { result }
}
@Test fun `fromJSON mapping should map nested class`() {
val config = JSONConfig().apply {
fromJSON { json ->
if (json !is JSONObject)
fail("Must be JSONObject")
Dummy1(json.getString("a"), json.getInt("b"))
}
}
val json1 = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
val json2 = JSONObject().apply {
put("dummy1", json1)
putValue("text", "Hello!")
}
expect(Dummy3(Dummy1("xyz", 888), "Hello!")) {
JSONDeserializer.deserialize(Dummy3::class.createType(), json2, config)
}
}
@Test fun `add toJSON mapping should return the function`() {
val config = JSONConfig()
assertNull(config.findToJSONMapping(stringType))
assertNull(config.findToJSONMapping(String::class))
config.toJSON<String> { str -> JSONString(str ?: fail("String expected")) }
assertNotNull(config.findToJSONMapping(stringType))
assertNotNull(config.findToJSONMapping(String::class))
}
@Test fun `toJSON mapping should map simple data class`() {
val config = JSONConfig().apply {
toJSON<Dummy1> { obj ->
obj?.let {
JSONObject().apply {
putValue("a", it.field1)
putValue("b", it.field2)
}
}
}
}
val expected = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
expect(expected) { JSONSerializer.serialize(Dummy1("xyz", 888), config) }
}
@Test fun `toJSON mapping should map nested class`() {
val config = JSONConfig().apply {
toJSON<Dummy1> { obj ->
obj?.let {
JSONObject().apply {
putValue("a", it.field1)
putValue("b", it.field2)
}
}
}
}
val dummy1 = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
val expected = JSONObject().apply {
putJSON("dummy1", dummy1)
putValue("text", "Hi there!")
}
expect(expected) { JSONSerializer.serialize(Dummy3(Dummy1("xyz", 888), "Hi there!"), config) }
}
@Test fun `toJSON mapping should be transferred on combineMappings`() {
val config = JSONConfig().apply {
toJSON<Dummy1> { obj ->
obj?.let {
JSONObject().apply {
putValue("a", it.field1)
putValue("b", it.field2)
}
}
}
}
val config2 = JSONConfig().apply {
combineMappings(config)
}
val expected = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
expect(expected) { JSONSerializer.serialize(Dummy1("xyz", 888), config2) }
}
@Test fun `toJSON mapping should be transferred on combineAll`() {
val config = JSONConfig().apply {
toJSON<Dummy1> { obj ->
obj?.let {
JSONObject().apply {
putValue("a", it.field1)
putValue("b", it.field2)
}
}
}
}
val config2 = JSONConfig().apply {
combineAll(config)
}
val expected = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
expect(expected) { JSONSerializer.serialize(Dummy1("xyz", 888), config2) }
}
@Test fun `JSONName annotation should be transferred on combineAll`() {
val obj = DummyWithCustomNameAnnotation("abc", 123)
val config = JSONConfig().apply {
addNameAnnotation(CustomName::class, "symbol")
}
val config2 = JSONConfig().apply {
combineAll(config)
}
val expected = JSONObject().apply {
putValue("field1", "abc")
putValue("fieldX", 123)
}
expect(expected) { JSONSerializer.serialize(obj, config2) }
}
@Test fun `Switch settings and numeric values should be transferred on combineAll`() {
val config = JSONConfig().apply {
bigIntegerString = true
bigDecimalString = true
includeNulls = true
allowExtra = true
streamOutput = true
readBufferSize = 16384
stringifyInitialSize = 512
}
val config2 = JSONConfig().apply {
combineAll(config)
}
expect(true) { config2.bigIntegerString }
expect(true) { config2.bigDecimalString }
expect(true) { config2.includeNulls }
expect(true) { config2.allowExtra }
expect(true) { config2.streamOutput }
expect(16384) { config2.readBufferSize }
expect(512) { config2.stringifyInitialSize }
}
@Test fun `toJSON mapping of nullable type should be selected correctly`() {
val config = JSONConfig().apply {
toJSON(Dummy1::class.createType(nullable = true)) { JSONString("A") }
}
expect(JSONString("A")) { JSONSerializer.serialize(Dummy1("X", 0), config) }
}
@Test fun `toJSON mapping of non-nullable type should be selected correctly`() {
val config = JSONConfig().apply {
toJSON(Dummy1::class.createType(nullable = false)) { JSONString("A") }
}
expect(JSONString("A")) { JSONSerializer.serialize(Dummy1("X", 0), config) }
}
@Test fun `toJSON mapping should select correct function among derived classes`() {
val config = JSONConfig().apply {
toJSON<DummyA> { JSONString("A") }
toJSON<DummyB> { JSONString("B") }
toJSON<DummyC> { JSONString("C") }
toJSON<DummyD> { JSONString("D") }
}
expect(JSONString("A")) { JSONSerializer.serialize(DummyA(), config)}
expect(JSONString("B")) { JSONSerializer.serialize(DummyB(), config)}
expect(JSONString("C")) { JSONSerializer.serialize(DummyC(), config)}
expect(JSONString("D")) { JSONSerializer.serialize(DummyD(), config)}
}
@Test fun `toJSON mapping should select correct function when order is reversed`() {
val config = JSONConfig().apply {
toJSON<DummyD> { JSONString("D") }
toJSON<DummyC> { JSONString("C") }
toJSON<DummyB> { JSONString("B") }
toJSON<DummyA> { JSONString("A") }
}
expect(JSONString("A")) { JSONSerializer.serialize(DummyA(), config)}
expect(JSONString("B")) { JSONSerializer.serialize(DummyB(), config)}
expect(JSONString("C")) { JSONSerializer.serialize(DummyC(), config)}
expect(JSONString("D")) { JSONSerializer.serialize(DummyD(), config)}
}
@Test fun `toJSON mapping should select correct function when exact match not present`() {
val config = JSONConfig().apply {
toJSON<DummyA> { JSONString("A") }
toJSON<DummyB> { JSONString("B") }
toJSON<DummyC> { JSONString("C") }
}
expect(JSONString("A")) { JSONSerializer.serialize(DummyA(), config)}
expect(JSONString("B")) { JSONSerializer.serialize(DummyB(), config)}
expect(JSONString("C")) { JSONSerializer.serialize(DummyC(), config)}
expect(JSONString("C")) { JSONSerializer.serialize(DummyD(), config)}
}
@Test fun `fromJSON mapping should select correct function among derived classes`() {
val config = JSONConfig().apply {
fromJSON { if (it == JSONString("A")) DummyA() else fail() }
fromJSON { if (it == JSONString("B")) DummyB() else fail() }
fromJSON { if (it == JSONString("C")) DummyC() else fail() }
fromJSON { if (it == JSONString("D")) DummyD() else fail() }
}
assertTrue(JSONDeserializer.deserialize(DummyA::class.createType(), JSONString("A"), config) is DummyA)
assertTrue(JSONDeserializer.deserialize(DummyB::class.createType(), JSONString("B"), config) is DummyB)
assertTrue(JSONDeserializer.deserialize(DummyC::class.createType(), JSONString("C"), config) is DummyC)
assertTrue(JSONDeserializer.deserialize(DummyD::class.createType(), JSONString("D"), config) is DummyD)
}
@Test fun `fromJSON mapping should select correct function when order is reversed`() {
val config = JSONConfig().apply {
fromJSON { if (it == JSONString("D")) DummyD() else fail() }
fromJSON { if (it == JSONString("C")) DummyC() else fail() }
fromJSON { if (it == JSONString("B")) DummyB() else fail() }
fromJSON { if (it == JSONString("A")) DummyA() else fail() }
}
assertTrue(JSONDeserializer.deserialize(DummyA::class.createType(), JSONString("A"), config) is DummyA)
assertTrue(JSONDeserializer.deserialize(DummyB::class.createType(), JSONString("B"), config) is DummyB)
assertTrue(JSONDeserializer.deserialize(DummyC::class.createType(), JSONString("C"), config) is DummyC)
assertTrue(JSONDeserializer.deserialize(DummyD::class.createType(), JSONString("D"), config) is DummyD)
}
@Test fun `fromJSON mapping should select correct function when exact match not present`() {
val config = JSONConfig().apply {
fromJSON { if (it == JSONString("B")) DummyB() else fail() }
fromJSON { if (it == JSONString("C")) DummyC() else fail() }
fromJSON { if (it == JSONString("D")) DummyD() else fail() }
}
assertTrue(JSONDeserializer.deserialize(DummyA::class.createType(), JSONString("B"), config) is DummyB)
assertTrue(JSONDeserializer.deserialize(DummyB::class.createType(), JSONString("B"), config) is DummyB)
assertTrue(JSONDeserializer.deserialize(DummyC::class.createType(), JSONString("C"), config) is DummyC)
assertTrue(JSONDeserializer.deserialize(DummyD::class.createType(), JSONString("D"), config) is DummyD)
}
@Test fun `toJSON mapping with JSONConfig toJSONString should use toString`() {
val config = JSONConfig().apply {
toJSONString<Dummy9>()
}
expect(JSONString("abcdef")) { JSONSerializer.serialize(Dummy9("abcdef"), config) }
}
@Test fun `fromJSON mapping with JSONConfig fromJSONString should use String constructor`() {
val config = JSONConfig().apply {
fromJSONString<Dummy9>()
}
expect(Dummy9("abcdef")) { JSONDeserializer.deserialize<Dummy9>(JSONString("abcdef"), config) }
}
@Test fun `multiple JSONConfig mappings using apply should work correctly`() {
val config = JSONConfig().apply {
toJSON<Dummy1> { obj ->
obj?.let {
JSONObject().apply {
putValue("a", it.field1)
putValue("b", it.field2)
}
}
}
fromJSON { json ->
require(json is JSONObject) { "Must be JSONObject" }
Dummy1(json.getString("a"), json.getInt("b"))
}
toJSON<Dummy3> { obj ->
obj?.let {
JSONObject().let { json ->
json["dummy1"] = JSONSerializer.serialize(it.dummy1, this)
json.putValue("text", it.text)
}
}
}
fromJSON { json ->
require(json is JSONObject) { "Must be JSONObject" }
Dummy3(JSONDeserializer.deserialize(json.getObject("dummy1"), this) ?: fail(), json.getString("text"))
}
}
val json1 = JSONObject().apply {
putValue("a", "xyz")
putValue("b", 888)
}
val dummy1 = Dummy1("xyz", 888)
expect(json1) { JSONSerializer.serialize(dummy1, config) }
expect(dummy1) { JSONDeserializer.deserialize<Dummy1>(json1, config) }
val json3 = JSONObject().apply {
put("dummy1", json1)
putValue("text", "excellent")
}
val dummy3 = Dummy3(dummy1, "excellent")
expect(json3) { JSONSerializer.serialize(dummy3, config) }
expect(dummy3) { JSONDeserializer.deserialize<Dummy3>(json3, config) }
}
}
<file_sep># json-kotlin
[](https://travis-ci.com/github/pwall567/json-kotlin)
[](https://opensource.org/licenses/MIT)
[](https://github.com/JetBrains/kotlin/releases/tag/v1.7.21)
[](https://search.maven.org/search?q=g:%22net.pwall.json%22%20AND%20a:%22json-kotlin%22)
JSON serialization and deserialization for Kotlin.
This document provides introductory information on the `json-kotlin` library; fuller information is available in the
[User Guide](USERGUIDE.md).
## IMPORTANT
This project is in the process of being superseded by [`kjson`](https://github.com/pwall567/kjson).
New users are encouraged to use that project instead of this one; existing users are encouraged to migrate when
convenient.
This library will continue to be maintained, but enhancements will be added to the new library first, for example
[an improved way of specifying polymorphic class deserialization](https://github.com/pwall567/kjson/blob/main/CUSTOM.md#fromjsonpolymorphic).
## Background
This library provides JSON serialization and deserialization functionality for Kotlin.
It uses Kotlin reflection to serialize and deserialize arbitrary objects, and it includes code to handle most of the
Kotlin standard library classes.
When instantiating deserialized objects it does not require the class to have a no-argument constructor, and unlike some
JSON libraries it does not use the `sun.misc.Unsafe` class to force instantiation.
## Supported Classes
Support is included for the following standard Kotlin classes:
- `String`, `StringBuilder`, `CharSequence`, `Char`, `CharArray`
- `Int`, `Long`, `Short`, `Byte`, `Double`, `Float`
- `Array`, `IntArray`, `LongArray`, `ShortArray`, `ByteArray`, `DoubleArray`, `FloatArray`
- `Boolean`, `BooleanArray`
- `Collection`, `List`, `ArrayList`, `LinkedList`, `Set`, `HashSet`, `LinkedHashSet`, `Sequence`
- `Map`, `HashMap`, `LinkedHashMap`
- `Pair`, `Triple`
- `Enum`
Also, support is included for the following standard Java classes:
- `java.math.BigDecimal`, `java.math.BigInteger`
- `java.net.URI`, `java.net.URL`
- `java.util.Enumeration`, `java.util.Bitset`, `java.util.UUID`, `java.util.Date`, `java.util.Calendar`
- `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`
- `java.time.Instant`, `java.time.LocalDate`, `java.time.LocalTime`, `java.time.LocalDateTime`,
`java.time.OffsetTime`, `java.time.OffsetDateTime`, `java.time.ZonedDateTime`, `java.time.Year`,
`java.time.YearMonth`, `java.time.MonthDay`, `java.time.Duration`, `java.time.Period`
- `java.util.stream.Stream`, `java.util.stream.IntStream`, `java.util.stream.LongStream`,
`java.util.stream.DoubleStream`
## Quick Start
### Serialization
To serialize any object (say, a `data class`):
```kotlin
val json = dataClassInstance.stringifyJSON()
```
The result `json` is a `String` serialized from the object, recursively serializing any nested objects, collections
etc.
The JSON object will contain serialized forms of all of the properties of the object (as declared in `val` and `var`
statements).
For example, given the class:
```kotlin
data class Example(val abc: String, val def: Int, val ghi: List<String>)
```
and the instantiation:
```kotlin
val example = Example("hello", 12345, listOf("A", "B"))
```
then
```kotlin
val json = example.stringifyJSON()
```
will yield:
```json
{"abc":"hello","def":12345,"ghi":["A","B"]}
```
### Deserialization
Deserialization is slightly more complicated, because the target data type must be specified to the function.
This can be achieved in a number of ways (the following examples assume `jsonString` is a `String` containing JSON):
The type can be inferred from the context:
```kotlin
val example: Example? = jsonString.parseJSON()
```
The type may be specified as a type parameter:
```kotlin
val example = jsonString.parseJSON<Example>()
```
The type may be specified as a `KClass`:
```kotlin
val example = jsonString.parseJSON(Example::class)
```
The type may be specified as a `KType`:
```kotlin
val example = jsonString.parseJSON(Example::class.starProjectedType) as Example
```
(This form is generally only needed when deserializing parameterized types where the parameter types can not be
inferred; the `as` expression is needed because `KType` does not convey inferred type information.)
Because of the limitations caused by [type erasure](https://kotlinlang.org/docs/reference/generics.html#type-erasure),
when deserializing parameterized types (like generic collections), the above forms will not always convey sufficient
information.
For these cases, the `JSONDelegate` class provides a valuable mechanism:
```kotlin
val listExample: List<Example> by JSONDelegate(jsonList)
```
or:
```kotlin
val listExample by JSONDelegate<List<Example>>(jsonList)
```
## Sealed Classes
The library will handle Kotlin sealed classes.
See the [User Guide](USERGUIDE.md#sealed-classes) for more details.
## Customization
### Annotations
#### Change the name used for a property
When serializing or deserializing a Kotlin object, the property name discovered by reflection will be used as the name
in the JSON object.
An alternative name may be specified if required, by the use of the `@JSONName` annotation:
```kotlin
data class Example(val abc: String, @JSONName("xyz") val def: Int)
```
#### Ignore a property on serialization
If it is not necessary (or desirable) to output a particular field, the `@JSONIgnore` annotation may be used to prevent
serialization:
```kotlin
data class Example(val abc: String, @Ignore val def: Int)
```
#### Include properties when null
If a property is `null`, the default behaviour when serializing is to omit the property from the output object.
If this behaviour is not desired, the property may be annotated with the `@JSONIncludeIfNull` annotation to indicate
that it is to be included even if `null`:
```kotlin
data class Example(@JSONIncludeIfNull val abc: String?, val def: Int)
```
To indicate that all properties in a class are to be included in the output even if null, the
`@JSONIncludeAllProperties` may be used on the class:
```kotlin
@JSONIncludeAllProperties
data class Example(val abc: String?, val def: Int)
```
And to specify that all properties in all classes are to be output if null, the `includeNulls` flag may be set in the
`JSONConfig`:
```kotlin
val config = JSONConfig().apply {
includeNulls = true
}
val json = example.stringifyJSON(config)
```
#### Allow extra properties in a class to be ignored
The default behaviour when extra properties are found during deserialization is to throw an exception.
To allow (and ignore) any extra properties, the `@JSONAllowExtra` annotation may be added to the class:
```kotlin
@JSONAllowExtra
data class Example(val abc: String, val def: Int)
```
To allow (and ignore) extra properties throughout the deserialization process, the `allowExtra` flag may be set in the
`JSONConfig`:
```kotlin
val config = JSONConfig().apply {
allowExtra = true
}
val json = example.stringifyJSON(config)
```
#### Using existing tags from other software
If you have classes that already contain annotations for the above purposes, you can tell `json-kotlin` to use
those annotations by specifying them in a `JSONConfig`:
```kotlin
val config = JSONConfig().apply {
addNameAnnotation(MyName::class, "name")
addIgnoreAnnotation(MyIgnore::class)
addIncludeIfNullAnnotation(MyIncludeIfNull::class)
addIncludeAllPropertiesAnnotation(MyIncludeAllProperties::class)
addAllowExtraPropertiesAnnotation(MyAllowExtraProperties::class)
}
val json = example.stringifyJSON(config)
```
The `JSONConfig` may be supplied as an optional final argument on most `json-kotlin` function calls (see the KDoc or
source for more details).
### Custom Serialization
The `JSONConfig` is also used to specify custom serialization:
```kotlin
val config = JSONConfig().apply {
toJSON<Example> { obj ->
obj?.let {
JSONObject().apply {
putValue("custom1", it.abc)
putValue("custom2", it.def)
}
}
}
}
```
Or deserialization:
```kotlin
val config = JSONConfig().apply {
fromJSON { json ->
require(json is JSONObject) { "Must be JSONObject" }
Example(json.getString("custom1"), json.getInt("custom2"))
}
}
```
The `toJSON` function must supply a lambda will the signature `(Any?) -> JSONValue?` and the `fromJSON` function must
supply a lambda with the signature `(JSONValue?) -> Any?`.
`JSONValue` is the interface implemented by each node in the `jsonutil` library (see below).
Both `toJSON` and `fromJSON` may be specified repeatedly in the same `JSONConfig` to cover multiple classes.
## Mixed Kotlin and Java
If you need to serialize or deserialize a Kotlin class from Java, the `JSONJava` class provides this capability while
still retaining all the Kotlin functionality, like Kotlin-specific classes and nullability checking:
```
String json = JSONJava.stringify(example);
```
Or:
```
Example example = JSONJava.parse(Example.class, json);
```
## More Detail
The deserialization functions operate as a two-stage process.
The JSON string is first parsed into an internal form using the
[`jsonutil`](https://github.com/pwall567/jsonutil) library ([Javadoc](https://pwall.net/oss/jsonutil/));
the resulting tree of `JSONValue` objects is then traversed to create the desired classes.
(Note that the
[`json-stream`](https://github.com/pwall567/json-stream) library and its non-blocking coroutine-aware version
[`json-co-stream`](https://github.com/pwall567/json-co-stream) may be used to parse a stream of JSON data on-the-fly,
and in this case, each object may be converted to the required target form as its last character is read.)
It is possible to perform serialization using the same two-stage approach, but from version 3.2 of this library onwards,
the `JSONStringify` functions are used to stringify direct to a string, or, if the `appendJSON()` function is used, to
any form of `Appendable` including the various `Writer` classes.
As always, the KDoc, the source or the unit test classes provide more information.
This information is of significance when custom serialization and deserialization are required.
Regardless of whether the `JSONStringify` functions are used to output directly to a string, the custom serialization
is still required to create the internal `JSONValue`-based form.
This ensures that errant serialization functions don't disrupt the remainder of the JSON, for example by omitting a
trailing quote or bracket character.
## Breaking changes
**Version 2.0** introduced a change to `JSONConfig` which makes it incompatible with earlier versions - the functions to
add information to the `JSONConfig` object (e.g. serialization and deserialization mappings) no longer return the object
itself for chaining purposes.
The recommended approach to perform repeat actions such as this is to use the Kotlin `apply {}` function.
If there is anyone affected by this change (unlikely, I know!) version 1.2 is still available.
Also, **version 3.8** changed the visibility of an internal function in `JSONDeserializer` from `public` to `private`
(and changed its signature, although that's hardly relevant if it's no longer public).
It was never intended that this function would be part of the published API, so the "major version" has not been
incremented as would normally be the case for a breaking change.
**Version 4.0** changes the content of error messages in exceptions, and thus may be a breaking change for any code that
is dependent on the precise text of the message.
In particular:
- Most messages now include a `JSONPointer` when appropriate, showing the location in the JSON where the error occurred.
- Errors on deserialization of objects using constructor parameters now include more detail.
## Dependency Specification
The latest version of the library is 4.8, and it may be obtained from the Maven Central repository.
### Maven
```xml
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>json-kotlin</artifactId>
<version>4.8</version>
</dependency>
```
### Gradle
```groovy
implementation 'net.pwall.json:json-kotlin:4.8'
```
### Gradle (kts)
```kotlin
implementation("net.pwall.json:json-kotlin:4.8")
```
<NAME>
2023-07-10
<file_sep>/*
* @(#) JSONAutoTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.full.starProjectedType
import kotlin.test.expect
import kotlin.test.Test
import java.lang.reflect.Type
/**
* Tests for [JSONAuto]. These tests are somewhat rudimentary because [JSONAuto] simply delegates requests to
* [JSONSerializer] and [JSONDeserializer], and those classes are extensively tested separately.
*
* @author <NAME>
*/
class JSONAutoTest {
@Test fun `JSONAuto should correctly stringify an object`() {
val obj = Dummy1("abdef", 54321)
val expected = JSONObject().apply {
putValue("field1", "abdef")
putValue("field2", 54321)
}
expect(expected) { JSON.parse(JSONAuto.stringify(obj)) }
}
@Test fun `JSONAuto should parse a string to create an object`() {
val json = """{"field1":"abdef","field2":54321}"""
val expected: Dummy1? = Dummy1("abdef", 54321)
expect(expected) { JSONAuto.parse(json) }
}
@Test fun `JSONAuto should parse a string to create an object with explicit type`() {
val json = """{"field1":"abdef","field2":54321}"""
expect(Dummy1("abdef", 54321)) { JSONAuto.parse(Dummy1::class.starProjectedType, json) }
}
@Test fun `JSONAuto should parse List using parameterised type`() {
val json = """[{"field1":"abcdef","field2":567},{"field1":"qwerty","field2":9999}]"""
val expected = listOf(Dummy1("abcdef", 567), Dummy1("qwerty", 9999))
expect(expected) { JSONAuto.parse<List<Dummy1>>(json) }
}
@Test fun `JSONAuto should parse List using Java Type`() {
val json = """[{"field1":567,"field2":"abcdef"},{"field1":9999,"field2":"qwerty"}]"""
val type: Type = JavaClass2::class.java.getField("field1").genericType
expect(listOf(JavaClass1(567, "abcdef"), JavaClass1(9999, "qwerty"))) { JSONAuto.parse(type, json) }
}
}
<file_sep># Custom Serialization and Deserialization - `json-kotlin`
## Background
The library will use the obvious JSON serializations for the main Kotlin data types — `String`, `Int`, `Boolean`
etc.
For arrays and collections, it wil use the JSON array or object syntax, recursively calling the library to process the
items.
Also, there are a number of standard classes for which there is an obvious JSON representation, for example `LocalDate`
and `UUID` (for a complete list, see the [User Guide](USERGUIDE.md#type-mapping)).
But the dominant use of `json-kotlin` is expected to be for the serialization and deserialization of user-defined
classes, particularly Kotlin data classes.
In these cases, the library will serialize or deserialize the Kotlin object as a JSON object using the Kotlin property
names, recursively invoking the library to serialize or deserialize the properties (see the
[User Guide](USERGUIDE.md#deserialization) for more details).
If this is not the required behaviour, custom serialization and deserialization may be used to tailor the JSON
representation to the form needed.
## Serialization
Custom serialization converts the object to a `JSONValue`; the library will convert the `JSONValue` to string form if
that is required.
There are two ways of specifying custom serialization.
### `toJSON` function in the class
If the class of an object to be serialized has a member function named `toJSON`, taking no parameters and returning a
`JSONValue`, that function will be used for serialization.
For example:
```kotlin
class Person(val firstName: String, val surname: String) {
fun toJSON(): JSONValue {
return JSONString("$firstName|$surname")
}
}
```
Note that the result need not be a `JSONObject` (although it generally will be).
### `toJSON` lambda in the `JSONConfig`
There are many cases, for example when the class is part of an external library, when the above technique is not
possible.
Also, some architectural rules may demand that there be no external dependencies in the principal classes of the
published API of a system.
In such cases, a `toJSON` lambda may be specified in the [`JSONConfig`](USERGUIDE.md#configuration).
For example, if the `Person` class above did not have a `toJSON` function:
```kotlin
config.toJSON<Person> { person ->
JSONString("${person.firstName}|${person.surname}")
}
```
The type may be specified as a type parameter (as above), or as type variable:
```kotlin
val personType = Person::class.starProjectedType
config.toJSON(personType) { p ->
val person = p as Person // this is necessary because there is insufficient type information in this case
JSONString("${person.firstName}|${person.surname}")
}
```
### `toJSONString`
This is a shortcut for `toJSON` where the lambda simply returns a `JSONString` containing a `toString()` of the object.
For Example:
```kotlin
config.toJSONString<Person>()
```
## Deserialization
Custom deserialization converts a `JSONValue` to an object of the specified (or implied) type.
If the source is a string, it will already have been converted to a structure of `JSONValue` objects.
### `fromJSON` function in the companion object
If the target class has a companion object with a function taking a `JSONValue` and returning an object of the target
class, that function will be used for deserialization.
For example:
```kotlin
class Person(val firstName: String, val surname: String) {
fun toJSON(): JSONValue {
return JSONString("$firstName|$surname")
}
companion object {
@Suppress("unused")
fun fromJSON(json: JSONValue): DummyFromJSON {
require(json is JSONString) { "Can't deserialize ${json::class} as Person" }
val names = json.get().split('|')
require(names.length == 2) { "Person string has incorrect format" }
return Person(names[0], names[1])
}
}
}
```
### `fromJSON` lambda in the `JSONConfig`
Again, it may not be possible to modify the class, so a `fromJSON` lambda may be specified in the `JSONConfig`.
The above example may be specified as:
```kotlin
config.fromJSON { json ->
require(json is JSONString) { "Can't deserialize ${json::class} as Person" }
val names = json.get().split('|')
require(names.length == 2) { "Person string has incorrect format" }
Person(names[0], names[1])
}
```
The result type in this example is implied by the return type of the lambda.
As with `toJSON`, the type may be specified explicitly:
```kotlin
val personType = Person::class.starProjectedType
config.fromJSON(personType) { json ->
require(json is JSONString) { "Can't deserialize ${json::class} as Person" }
val names = json.get().split('|')
require(names.length == 2) { "Person string has incorrect format" }
Person(names[0], names[1])
}
```
2021-01-03
<file_sep>/*
* @(#) JSONSerializerFunctionsTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2020, 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.test.Test
import kotlin.test.assertFalse
import kotlin.test.assertNotNull
import kotlin.test.assertNull
import kotlin.test.assertTrue
import kotlin.test.expect
import java.time.Instant
import java.util.Calendar
import net.pwall.json.JSONSerializerFunctions.findToJSON
import net.pwall.json.JSONSerializerFunctions.formatISO8601
import net.pwall.json.JSONSerializerFunctions.isSealedSubclass
import net.pwall.json.JSONSerializerFunctions.isToStringClass
class JSONSerializerFunctionsTest {
@Test fun `should find toJSON when it is present`() {
assertNotNull(DummyFromJSON::class.findToJSON())
}
@Test fun `should return null when toJSON is not present`() {
assertNull(Dummy1::class.findToJSON())
}
@Test fun `should return true when class is a subclass of a sealed class`() {
assertTrue(NotANumber::class.isSealedSubclass())
}
@Test fun `should return false when class is not a subclass of a sealed class`() {
assertFalse(Dummy1::class.isSealedSubclass())
}
@Test fun `should recognise a toString-able class`() {
assertTrue(Instant::class.isToStringClass())
}
@Test fun `should recognise a not-toString-able class`() {
assertFalse(Dummy1::class.isToStringClass())
}
@Test fun `should correctly format Calendar`() {
val cal = Calendar.getInstance().apply {
set(Calendar.YEAR, 2020)
set(Calendar.MONTH, 3)
set(Calendar.DAY_OF_MONTH, 23)
set(Calendar.HOUR_OF_DAY, 19)
set(Calendar.MINUTE, 25)
set(Calendar.SECOND, 31)
set(Calendar.MILLISECOND, 123)
set(Calendar.ZONE_OFFSET, 10 * 60 * 60 * 1000)
}
expect("2020-04-23T19:25:31.123+10:00") { cal.formatISO8601() }
}
@Test fun `should perform reflection on system classes`() {
val map: Map<String, String> = emptyMap()
assertNull(map::class.findToJSON())
val int = 1
assertNull(int::class.findToJSON())
val lambda: (Int) -> Int = { it }
assertNull(lambda::class.findToJSON())
val str = "???"
assertNull(str::class.findToJSON())
}
}
<file_sep># Spring and `json-kotlin`
## Default Spring Serialization and Deserialization
Many users will seek to use `json-kotlin` in conjunction with the
[Spring Framework](https://spring.io/projects/spring-framework).
If a class of the following form is present in the classpath scanned by Spring, it will be used by the framework as the
default JSON serialization and deserialization function for Spring Boot etc.
```kotlin
package my.example
import java.io.Reader
import java.io.Writer
import java.lang.reflect.Type
import org.springframework.http.MediaType
import org.springframework.http.converter.json.AbstractJsonHttpMessageConverter
import org.springframework.stereotype.Service
import net.pwall.json.JSONAuto
import net.pwall.json.JSONConfig
import net.pwall.json.JSONString
import net.pwall.json.JSONStringify.appendJSON
import my.custom.type.Money
@Service
class JSONConverter : AbstractJsonHttpMessageConverter() {
override fun canRead(mediaType: MediaType?): Boolean {
return mediaType != null && mediaType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)
}
override fun canWrite(mediaType: MediaType?): Boolean {
return mediaType != null && mediaType.equalsTypeAndSubtype(MediaType.APPLICATION_JSON)
}
override fun readInternal(resolvedType: Type, reader: Reader): Any? {
return JSONAuto.parse(resolvedType, reader, config)
}
override fun writeInternal(o: Any, type: Type?, writer: Writer) {
writer.appendJSON(o, config)
}
companion object {
/**
* JSONConfig containing specific configuration for this application.
*
* It is placed in a companion object to allow it to be used from other parts of the application, e.g.
* val event = jsonString.parseJSON<Event>(JSONConverter.config)
*/
val config = JSONConfig().apply {
allowExtra = true // example configuration setting
toJSONString<Money>() // example custom serialization
fromJSON { json -> // example custom deserialization
require(json is JSONString) { "JSON representation of Money must be string" }
Money.of(json.value)
}
}
}
}
```
2021-01-03
<file_sep>/*
* @(#) JSONStringify.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KProperty
import kotlin.reflect.full.staticProperties
import kotlin.reflect.jvm.isAccessible
import java.math.BigDecimal
import java.math.BigInteger
import java.util.BitSet
import java.util.Calendar
import java.util.Date
import java.util.Enumeration
import java.util.stream.BaseStream
import net.pwall.json.JSONKotlinException.Companion.fail
import net.pwall.json.JSONSerializerFunctions.findToJSON
import net.pwall.json.JSONSerializerFunctions.formatISO8601
import net.pwall.json.JSONSerializerFunctions.isSealedSubclass
import net.pwall.json.JSONSerializerFunctions.isToStringClass
import net.pwall.util.Strings
/**
* JSON Auto serialize for Kotlin - serialize direct to `String`.
*
* @author <NAME>
*/
object JSONStringify {
/**
* Serialize an object to JSON. (The word "stringify" is borrowed from the JavaScript implementation of JSON.)
*
* @param obj the object
* @param config an optional [JSONConfig] to customise the conversion
* @return the JSON form of the object
*/
fun stringify(obj: Any?, config: JSONConfig = JSONConfig.defaultConfig) : String {
return when (obj) {
null -> "null"
else -> StringBuilder(config.stringifyInitialSize).apply {
appendJSON(obj, config)
}.toString()
}
}
/**
* Append the serialized form of an object to an [Appendable] in JSON.
*
* @receiver the [Appendable] (e.g. [StringBuilder])
* @param obj the object
* @param config an optional [JSONConfig] to customise the conversion
*/
fun Appendable.appendJSON(obj: Any?, config: JSONConfig = JSONConfig.defaultConfig) {
appendJSON(obj, config, mutableSetOf())
}
private fun Appendable.appendJSON(obj: Any?, config: JSONConfig, references: MutableSet<Any>) {
if (obj == null) {
append("null")
return
}
config.findToJSONMapping(obj::class)?.let {
JSON.appendJSON(this, it(obj))
return
}
when (obj) {
is JSONValue -> obj.appendJSON(this)
is CharSequence -> appendJSONString(obj)
is CharArray -> {
append('"')
for (ch in obj)
appendJSONChar(ch)
append('"')
}
is Char -> {
append('"')
appendJSONChar(obj)
append('"')
}
is Number -> appendJSONNumber(obj, config, references)
is Boolean -> append(if (obj) "true" else "false")
is Array<*> -> appendJSONArray(obj, config, references)
is Pair<*, *> -> appendJSONPair(obj, config, references)
is Triple<*, *, *> -> appendJSONTriple(obj, config, references)
else -> appendJSONObject(obj, config, references)
}
}
private fun Appendable.appendJSONNumber(number: Number, config: JSONConfig, references: MutableSet<Any>) {
when (number) {
is Int -> Strings.appendInt(this, number)
is Short, is Byte -> Strings.appendInt(this, number.toInt())
is Long -> Strings.appendLong(this, number)
is Float, is Double -> append(number.toString())
is BigInteger -> {
if (config.bigIntegerString) {
append('"')
append(number.toString())
append('"')
}
else
append(number.toString())
}
is BigDecimal -> {
if (config.bigDecimalString) {
append('"')
append(number.toString())
append('"')
}
else
append(number.toString())
}
else -> appendJSONObject(number, config, references)
}
}
private fun Appendable.appendJSONArray(array: Array<*>, config: JSONConfig, references: MutableSet<Any>) {
if (array.isArrayOf<Char>()) {
append('"')
for (ch in array)
appendJSONChar(ch as Char)
append('"')
}
else {
append('[')
if (array.isNotEmpty()) {
for (i in array.indices) {
if (i > 0)
append(',')
appendJSON(array[i], config, references)
}
}
append(']')
}
}
private fun Appendable.appendJSONPair(pair: Pair<*, *>, config: JSONConfig, references: MutableSet<Any>) {
append('[')
appendJSON(pair.first, config, references)
append(',')
appendJSON(pair.second, config, references)
append(']')
}
private fun Appendable.appendJSONTriple(pair: Triple<*, *, *>, config: JSONConfig, references: MutableSet<Any>) {
append('[')
appendJSON(pair.first, config, references)
append(',')
appendJSON(pair.second, config, references)
append(',')
appendJSON(pair.third, config, references)
append(']')
}
private fun Appendable.appendJSONObject(obj: Any, config: JSONConfig, references: MutableSet<Any>) {
val objClass = obj::class
if (objClass.isToStringClass() || obj is Enum<*>) {
appendJSONString(obj.toString())
return
}
objClass.findToJSON()?.let {
try {
it.call(obj).appendJSON(this)
return
}
catch (e: Exception) {
fail("Error in custom toJSON - ${objClass.simpleName}", e)
}
}
when (obj) {
is Iterable<*> -> appendJSONIterator(obj.iterator(), config, references)
is Iterator<*> -> appendJSONIterator(obj, config, references)
is Sequence<*> -> appendJSONIterator(obj.iterator(), config, references)
is Enumeration<*> -> appendJSONEnumeration(obj, config, references)
is BaseStream<*, *> -> appendJSONIterator(obj.iterator(), config, references)
is Map<*, *> -> appendJSONMap(obj, config, references)
is Calendar -> appendJSONString(obj.formatISO8601())
is Date -> appendJSONString((Calendar.getInstance().apply { time = obj }).formatISO8601())
is BitSet -> appendJSONBitSet(obj)
else -> {
try {
references.add(obj)
append('{')
var continuation = false
if (objClass.isSealedSubclass()) {
appendJSONString(config.sealedClassDiscriminator)
append(':')
appendJSONString(objClass.simpleName ?: "null")
continuation = true
}
val includeAll = config.hasIncludeAllPropertiesAnnotation(objClass.annotations)
val statics: Collection<KProperty<*>> = objClass.staticProperties
if (objClass.isData && objClass.constructors.isNotEmpty()) {
// data classes will be a frequent use of serialization, so optimise for them
val constructor = objClass.constructors.first()
for (parameter in constructor.parameters) {
val member = objClass.members.find { it.name == parameter.name }
if (member is KProperty<*>)
continuation = appendUsingGetter(member, parameter.annotations, obj, config, references,
includeAll, continuation)
}
// now check whether there are any more properties not in constructor
for (member in objClass.members) {
if (member is KProperty<*> && !statics.contains(member) &&
!constructor.parameters.any { it.name == member.name })
continuation = appendUsingGetter(member, member.annotations, obj, config, references,
includeAll, continuation)
}
}
else {
for (member in objClass.members) {
if (member is KProperty<*> && !statics.contains(member)) {
val combinedAnnotations = ArrayList(member.annotations)
objClass.constructors.firstOrNull()?.parameters?.find { it.name == member.name }?.let {
combinedAnnotations.addAll(it.annotations)
}
continuation = appendUsingGetter(member, combinedAnnotations, obj, config, references,
includeAll, continuation)
}
}
}
append('}')
}
finally {
references.remove(obj)
}
}
}
}
private fun Appendable.appendUsingGetter(member: KProperty<*>, annotations: List<Annotation>?, obj: Any,
config: JSONConfig, references: MutableSet<Any>, includeAll: Boolean, continuation: Boolean): Boolean {
if (!config.hasIgnoreAnnotation(annotations)) {
val name = config.findNameFromAnnotation(annotations) ?: member.name
val wasAccessible = member.isAccessible
member.isAccessible = true
try {
val v = member.getter.call(obj)
if (v != null && v in references)
fail("Circular reference: field ${member.name} in ${obj::class.simpleName}")
if (v != null || config.hasIncludeIfNullAnnotation(annotations) || config.includeNulls || includeAll) {
if (continuation)
append(',')
appendJSONString(name)
append(':')
appendJSON(v, config, references)
return true
}
}
catch (e: JSONException) {
throw e
}
catch (e: Exception) {
fail("Error getting property ${member.name} from ${obj::class.simpleName}", e)
}
finally {
member.isAccessible = wasAccessible
}
}
return continuation
}
private fun Appendable.appendJSONIterator(iterator: Iterator<*>, config: JSONConfig, references: MutableSet<Any>) {
append('[')
if (iterator.hasNext()) {
while (true) {
appendJSON(iterator.next(), config, references)
if (!iterator.hasNext())
break
append(',')
}
}
append(']')
}
private fun Appendable.appendJSONEnumeration(enumeration: Enumeration<*>, config: JSONConfig,
references: MutableSet<Any>) {
append('[')
if (enumeration.hasMoreElements()) {
while (true) {
appendJSON(enumeration.nextElement(), config, references)
if (!enumeration.hasMoreElements())
break
append(',')
}
}
append(']')
}
private fun Appendable.appendJSONMap(map: Map<*, *>, config: JSONConfig, references: MutableSet<Any>) {
append('{')
map.entries.iterator().let {
if (it.hasNext()) {
while (true) {
val ( key, value ) = it.next()
appendJSONString(key.toString())
append(':')
appendJSON(value, config, references)
if (!it.hasNext())
break
append(',')
}
}
}
append('}')
}
private fun Appendable.appendJSONBitSet(bitSet: BitSet) {
append('[')
var continuation = false
for (i in 0 until bitSet.length()) {
if (bitSet.get(i)) {
if (continuation)
append(',')
Strings.appendInt(this, i)
continuation = true
}
}
append(']')
}
private fun Appendable.appendJSONString(cs: CharSequence) {
append('"')
for (ch in cs)
appendJSONChar(ch)
append('"')
}
private fun Appendable.appendJSONChar(ch: Char) {
when (ch) {
'"', '\\' -> append('\\').append(ch)
in ' '..'\u007F' -> append(ch)
'\n' -> append("\\n")
'\t' -> append("\\t")
'\r' -> append("\\r")
'\b' -> append("\\b")
'\u000C' -> append("\\f")
else -> {
append("\\u")
Strings.appendHex(this, ch)
}
}
}
}
<file_sep>/*
* @(#) JSONDelegate.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.properties.ReadOnlyProperty
import kotlin.reflect.KProperty
/**
* A delegate class to create a property from a JSON string.
*
* @constructor
* @param json the string to be parsed
* @param config an optional [JSONConfig] to customise the conversion
* @param T the target type
* @author <NAME>
*/
class JSONDelegate<out T>(val json: String, val config: JSONConfig = JSONConfig.defaultConfig) :
ReadOnlyProperty<Any?, T> {
private var value: Any? = UNINITIALISED
/**
* Get the value of the property - the first time through this will parse the supplied string and store it for
* subsequent references.
*
* This function is not intended to be thread- or coroutine-safe, but if it is used by multiple processes in
* parallel the worst that can happen (in very rare cases) is that the string will be re-parsed unnecessarily.
*
* @param thisRef a reference to the containing object - not used
* @param property the property descriptor - used to get the type
*/
@Suppress("UNCHECKED_CAST")
override operator fun getValue(thisRef: Any?, property: KProperty<*>): T {
if (value === UNINITIALISED)
value = JSONAuto.parse(property.returnType, json, config)
return value as T
}
private object UNINITIALISED
}
<file_sep>/*
* @(#) JSONConfig.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KClass
import kotlin.reflect.KProperty
import kotlin.reflect.KType
import kotlin.reflect.full.createType
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.isSuperclassOf
import kotlin.reflect.full.isSubtypeOf
import kotlin.reflect.full.isSupertypeOf
import kotlin.reflect.typeOf
import net.pwall.json.JSONKotlinException.Companion.fail
import net.pwall.json.annotation.JSONAllowExtra
import net.pwall.json.annotation.JSONIgnore
import net.pwall.json.annotation.JSONIncludeAllProperties
import net.pwall.json.annotation.JSONIncludeIfNull
import net.pwall.json.annotation.JSONName
/**
* Configuration class for JSON Auto serialize / deserialize for Kotlin.
*
* @author <NAME>
*/
@OptIn(ExperimentalStdlibApi::class)
class JSONConfig {
/** Name of property to store sealed class subclass name as discriminator */
var sealedClassDiscriminator = defaultSealedClassDiscriminator
set(newValue) {
if (newValue.isNotEmpty()) field = newValue else fail("Sealed class discriminator invalid")
}
/** Read buffer size (for `json-ktor`), arbitrarily limited to multiple of 16, not greater than 256K */
var readBufferSize = defaultBufferSize
set (newValue) {
if ((newValue and 15) == 0 && newValue in 16..(256 * 1024))
field = newValue
else
fail("Read buffer size invalid - $newValue")
}
/** Initial allocation size for stringify operations, arbitrarily limited to 16 to 256K */
var stringifyInitialSize = defaultStringifyInitialSize
set (newValue) {
if (newValue in 16..(256 * 1024))
field = newValue
else
fail("Stringify initial allocation size invalid - $newValue")
}
/** Character set (for `json-ktor` and `json-ktor-client`) */
var charset = defaultCharset
/** Switch to control how `BigInteger` is serialized / deserialized: `true` -> string, `false` -> number */
var bigIntegerString = defaultBigIntegerString
/** Switch to control how `BigDecimal` is serialized / deserialized: `true` -> string, `false` -> number */
var bigDecimalString = defaultBigDecimalString
/** Switch to control whether null fields in objects are output as "null": `true` -> yes, `false` -> no */
var includeNulls = defaultIncludeNulls
/** Switch to control whether extra fields are allowed on deserialization: `true` -> yes, `false` -> no */
var allowExtra = defaultAllowExtra
/** Switch to control whether `json-ktor` uses streamed output */
var streamOutput = defaultStreamOutput
private val fromJSONMap: MutableMap<KType, FromJSONMapping> = LinkedHashMap()
private val toJSONMap: MutableMap<KType, ToJSONMapping> = LinkedHashMap()
private val nameAnnotations: MutableList<Pair<KClass<*>, KProperty.Getter<String>>> =
arrayListOf(namePropertyPair(JSONName::class, "name"))
private val ignoreAnnotations: MutableList<KClass<*>> = arrayListOf(JSONIgnore::class, Transient::class)
private val includeIfNullAnnotations: MutableList<KClass<*>> = arrayListOf(JSONIncludeIfNull::class)
private val includeAllPropertiesAnnotations: MutableList<KClass<*>> = arrayListOf(JSONIncludeAllProperties::class)
private val allowExtraPropertiesAnnotations: MutableList<KClass<*>> = arrayListOf(JSONAllowExtra::class)
/**
* Find a `fromJSON` mapping function that will create the specified [KType], or the closest subtype of it.
*
* @param type the target type
* @return the mapping function, or `null` if not found
*/
fun findFromJSONMapping(type: KType): FromJSONMapping? {
if (type.classifier == Any::class)
return null
var best: Map.Entry<KType, FromJSONMapping>? = null
for (entry in fromJSONMap.entries) {
if (entry.key.isSubtypeOf(type) && best.let { it == null || it.key.isSubtypeOf(entry.key) })
best = entry
}
return best?.value
}
/**
* Find a `fromJSON` mapping function that will create the specified [KClass], or the closest subclass of it.
*
* @param targetClass the target class
* @return the mapping function, or `null` if not found
*/
fun findFromJSONMapping(targetClass: KClass<*>): FromJSONMapping? {
if (targetClass == Any::class)
return null
var best: KClass<*>? = null
var nullable = false
var result: FromJSONMapping? = null
for (entry in fromJSONMap.entries) {
val classifier = entry.key.classifier as KClass<*>
if (classifier.isSubclassOf(targetClass) && best.let {
it == null ||
if (it == classifier) !nullable else it.isSubclassOf(classifier) }) {
best = classifier
nullable = entry.key.isMarkedNullable
result = entry.value
}
}
return result
}
/**
* Find a `toJSON` mapping function that will accept the specified [KType], or the closest supertype of it.
*
* @param type the source type
* @return the mapping function, or `null` if not found
*/
fun findToJSONMapping(type: KType): ToJSONMapping? {
var best: Map.Entry<KType, ToJSONMapping>? = null
for (entry in toJSONMap.entries) {
if (entry.key.isSupertypeOf(type) && best.let { it == null || it.key.isSupertypeOf(entry.key) })
best = entry
}
return best?.value
}
/**
* Find a `toJSON` mapping function that will accept the specified [KClass], or the closest superclass of it.
*
* @param sourceClass the source class
* @return the mapping function, or `null` if not found
*/
fun findToJSONMapping(sourceClass: KClass<*>): ToJSONMapping? {
var best: KClass<*>? = null
var nullable = false
var result: ToJSONMapping? = null
for (entry in toJSONMap.entries) {
val classifier = entry.key.classifier as KClass<*>
if (classifier.isSuperclassOf(sourceClass) && best.let {
it == null ||
if (it == classifier) nullable else it.isSuperclassOf(classifier) }) {
best = classifier
nullable = entry.key.isMarkedNullable
result = entry.value
}
}
return result
}
/**
* Add custom mapping from JSON to the specified type.
*
* @param type the target type
* @param mapping the mapping function
*/
fun fromJSON(type: KType, mapping: FromJSONMapping) {
fromJSONMap[type] = mapping
}
/**
* Add custom mapping from JSON to the specified type, using a constructor that takes a single [String] parameter.
*
* @param type the target type
*/
fun fromJSONString(type: KType) {
fromJSONMap[type] = { json ->
when (json) {
null -> if (type.isMarkedNullable) null else fail("Can't deserialize null as $type")
is JSONString -> {
val resultClass = type.classifier as? KClass<*> ?: fail("Can't deserialize $type")
val constructor = resultClass.constructors.find {
it.parameters.size == 1 && it.parameters[0].type == stringType
}
constructor?.call(json.toString()) ?: fail("Can't deserialize $type")
}
else -> fail("Can't deserialize ${json::class.simpleName} as $type")
}
}
}
/**
* Add custom mapping from a specified type to JSON.
*
* @param type the source type
* @param mapping the mapping function
*/
fun toJSON(type: KType, mapping: ToJSONMapping) {
toJSONMap[type] = mapping
}
/**
* Add custom mapping from a specified type to JSON using the `toString()` function to create a JSON string.
*
* @param type the source type
*/
fun toJSONString(type: KType) {
toJSONMap[type] = { obj -> obj?.let { JSONString(it.toString())} }
}
/**
* Add custom mapping from JSON to the inferred type.
*
* @param mapping the mapping function
* @param T the type to be mapped
*/
inline fun <reified T: Any> fromJSON(noinline mapping: (JSONValue?) -> T?) {
fromJSON(typeOf<T>(), mapping)
}
/**
* Add custom mapping from JSON to the inferred type, using a constructor that takes a single [String] parameter.
*
* @param T the type to be mapped
*/
inline fun <reified T: Any> fromJSONString() {
fromJSONString(typeOf<T>())
}
/**
* Add custom mapping from an inferred type to JSON.
*
* @param mapping the mapping function
* @param T the type to be mapped
*/
inline fun <reified T: Any> toJSON(noinline mapping: (T?) -> JSONValue?) {
toJSON(typeOf<T>()) { mapping(it as T?) }
}
/**
* Add custom mapping from an inferred type to JSON using the `toString()` function to create a JSON string.
*
* @param T the type to be mapped
*/
inline fun <reified T: Any> toJSONString() {
toJSONString(typeOf<T>())
}
/**
* Add an annotation specification to the list of annotations that specify the name to be used when serializing or
* deserializing a property.
*
* @param nameAnnotationClass the annotation class to specify the name
* @param argumentName the name of the argument to the annotation that holds the name
* @param T the annotation class
*/
fun <T: Annotation> addNameAnnotation(nameAnnotationClass: KClass<T>, argumentName: String) {
nameAnnotations.add(namePropertyPair(nameAnnotationClass, argumentName))
}
private fun <T: Annotation> namePropertyPair(nameAnnotationClass: KClass<T>, argumentName: String):
Pair<KClass<*>, KProperty.Getter<String>> {
return nameAnnotationClass to findAnnotationStringProperty(nameAnnotationClass, argumentName).getter
}
@Suppress("UNCHECKED_CAST")
private fun <T: Annotation> findAnnotationStringProperty(annotationClass: KClass<T>, argumentName: String):
KProperty<String> {
for (member in annotationClass.members) {
if (member is KProperty<*> && member.name == argumentName && member.returnType == stringType) {
return member as KProperty<String>
}
}
throw IllegalArgumentException(
"Annotation class ${annotationClass.simpleName} does not have a String property \"$argumentName\"")
}
/**
* Find the name to be used when serializing or deserializing a property, from the annotations supplied.
*
* @param annotations the [Annotation]s (from the parameter, or the property, or both)
* @return the name to be used, or `null` if no annotation found
*/
fun findNameFromAnnotation(annotations: List<Annotation>?): String? {
if (annotations != null) {
for (entry in nameAnnotations) {
for (annotation in annotations) {
if (annotation::class.isSubclassOf(entry.first))
return entry.second.call(annotation)
}
}
}
return null
}
/**
* Add an annotation specification to the list of annotations that specify that the property is to be ignored when
* serializing or deserializing.
*
* @param ignoreAnnotationClass the annotation class
* @param T the annotation class
*/
fun <T: Annotation> addIgnoreAnnotation(ignoreAnnotationClass: KClass<T>) {
ignoreAnnotations.add(ignoreAnnotationClass)
}
/**
* Test whether a property has an annotation to indicate that it is to be ignored when serializing or deserializing.
*
* @param annotations the [Annotation]s (from the parameter, or the property, or both)
* @return `true` if an "ignore" annotation appears in the supplied list
*/
fun hasIgnoreAnnotation(annotations: List<Annotation>?) = hasBooleanAnnotation(ignoreAnnotations, annotations)
/**
* Add an annotation specification to the list of annotations that specify that the property is to be included when
* serializing or deserializing even if `null`.
*
* @param includeIfNullAnnotationClass the annotation class
* @param T the annotation class
*/
fun <T: Annotation> addIncludeIfNullAnnotation(includeIfNullAnnotationClass: KClass<T>) {
includeIfNullAnnotations.add(includeIfNullAnnotationClass)
}
/**
* Test whether a property has an annotation to indicate that it is to be included when serializing or deserializing
* even if `null`.
*
* @param annotations the [Annotation]s (from the parameter, or the property, or both)
* @return `true` if an "include if null" annotation appears in the supplied list
*/
fun hasIncludeIfNullAnnotation(annotations: List<Annotation>?) =
hasBooleanAnnotation(includeIfNullAnnotations, annotations)
/**
* Add an annotation specification to the list of annotations that specify that all properties in a class are to be
* included when serializing even if `null`.
*
* @param ignoreAllPropertiesAnnotationClass the annotation class
* @param T the annotation class
*/
fun <T: Annotation> addIncludeAllPropertiesAnnotation(ignoreAllPropertiesAnnotationClass: KClass<T>) {
includeAllPropertiesAnnotations.add(ignoreAllPropertiesAnnotationClass)
}
/**
* Test whether a property has an annotation to indicate that it is to be included when serializing even if `null`.
*
* @param annotations the [Annotation]s (from the class)
* @return `true` if an "include all properties" annotation appears in the supplied list
*/
fun hasIncludeAllPropertiesAnnotation(annotations: List<Annotation>?) =
hasBooleanAnnotation(includeAllPropertiesAnnotations, annotations)
/**
* Add an annotation specification to the list of annotations that specify that extra properties in a class are to
* be ignored when deserializing.
*
* @param allowExtraPropertiesAnnotationClass the annotation class
* @param T the annotation class
*/
fun <T: Annotation> addAllowExtraPropertiesAnnotation(allowExtraPropertiesAnnotationClass: KClass<T>) {
allowExtraPropertiesAnnotations.add(allowExtraPropertiesAnnotationClass)
}
/**
* Test whether a property has an annotation to indicate that extra properties in a class are to be ignored when
* deserializing.
*
* @param annotations the [Annotation]s (from the class)
* @return `true` if an "allow extra properties" annotation appears in the supplied list
*/
fun hasAllowExtraPropertiesAnnotation(annotations: List<Annotation>?) =
hasBooleanAnnotation(allowExtraPropertiesAnnotations, annotations)
/**
* Test whether a property has a boolean annotation matching the specified list.
*
* @param annotationList the list of pre-configured annotation classes.
* @param annotations the [Annotation]s (from the parameter, or the property, or both)
* @return `true` if an "ignore" annotation appears in the supplied list
*/
private fun hasBooleanAnnotation(annotationList: List<KClass<*>>, annotations: List<Annotation>?): Boolean {
if (annotations != null) {
for (entry in annotationList) {
for (annotation in annotations) {
if (annotation::class.isSubclassOf(entry))
return true
}
}
}
return false
}
/**
* Combine another `JSONConfig` into this one.
*
* @param config the other `JSONConfig`
*/
fun combineAll(config: JSONConfig) {
sealedClassDiscriminator = config.sealedClassDiscriminator
readBufferSize = config.readBufferSize
stringifyInitialSize = config.stringifyInitialSize
charset = config.charset
bigIntegerString = config.bigIntegerString
bigDecimalString = config.bigDecimalString
includeNulls = config.includeNulls
allowExtra = config.allowExtra
streamOutput = config.streamOutput
fromJSONMap.putAll(config.fromJSONMap)
toJSONMap.putAll(config.toJSONMap)
nameAnnotations.addAll(config.nameAnnotations)
ignoreAnnotations.addAll(config.ignoreAnnotations)
includeIfNullAnnotations.addAll(config.includeIfNullAnnotations)
includeAllPropertiesAnnotations.addAll(config.includeAllPropertiesAnnotations)
allowExtraPropertiesAnnotations.addAll(config.allowExtraPropertiesAnnotations)
}
/**
* Combine custom mappings from another `JSONConfig` into this one.
*
* @param config the other `JSONConfig`
*/
fun combineMappings(config: JSONConfig) {
fromJSONMap.putAll(config.fromJSONMap)
toJSONMap.putAll(config.toJSONMap)
}
companion object {
val stringType = String::class.createType()
const val defaultSealedClassDiscriminator = "class"
const val defaultBufferSize = DEFAULT_BUFFER_SIZE
const val defaultStringifyInitialSize = 1024
const val defaultBigIntegerString = false
const val defaultBigDecimalString = false
const val defaultIncludeNulls = false
const val defaultAllowExtra = false
const val defaultStreamOutput = false
val defaultCharset = Charsets.UTF_8
val defaultConfig = JSONConfig()
}
}
<file_sep>/*
* @(#) JSONAuto.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KClass
import kotlin.reflect.KType
import kotlin.reflect.typeOf
import java.io.File
import java.io.InputStream
import java.io.Reader
import java.lang.reflect.Type
@OptIn(ExperimentalStdlibApi::class)
object JSONAuto {
/**
* Serialize an object to JSON. (The word "stringify" is borrowed from the JavaScript implementation of JSON.)
*
* @param obj the object
* @param config an optional [JSONConfig] to customise the conversion
* @return the JSON form of the object
*/
fun stringify(obj: Any?, config: JSONConfig = JSONConfig.defaultConfig): String =
JSONStringify.stringify(obj, config)
/**
* Deserialize JSON from string ([CharSequence]) to a specified [KType].
*
* @param resultType the target type
* @param str the JSON in string form
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(resultType: KType, str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(resultType, JSON.parse(str), config)
/**
* Deserialize JSON from string ([CharSequence]) to a specified [KClass].
*
* @param resultClass the target class
* @param str the JSON in string form
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun <T: Any> parse(resultClass: KClass<T>, str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONDeserializer.deserialize(resultClass, JSON.parse(str), config)
/**
* Deserialize JSON from string ([CharSequence]) to the inferred [KType].
*
* @param str the JSON in string form
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
inline fun <reified T: Any> parse(str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): T? =
parse(typeOf<T>(), str, config) as T?
/**
* Deserialize JSON from string ([CharSequence]) to a specified Java [Type].
*
* @param javaType the target type
* @param str the JSON in string form
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(javaType: Type, str: CharSequence, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(javaType, JSON.parse(str), config)
/**
* Deserialize JSON from a [Reader] to a specified [KType].
*
* @param resultType the target type
* @param reader the JSON in the form of a [Reader]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(resultType: KType, reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(resultType, JSON.parse(reader), config)
/**
* Deserialize JSON from a [Reader] to a specified [KClass].
*
* @param resultClass the target class
* @param reader the JSON in the form of a [Reader]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun <T: Any> parse(resultClass: KClass<T>, reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONDeserializer.deserialize(resultClass, JSON.parse(reader), config)
/**
* Deserialize JSON from a [Reader] to the inferred [KType].
*
* @param reader the JSON in the form of a [Reader]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
inline fun <reified T: Any> parse(reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): T? =
parse(typeOf<T>(), reader, config) as T?
/**
* Deserialize JSON from a [Reader] to a specified Java [Type].
*
* @param javaType the target type
* @param reader the JSON in the form of a [Reader]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(javaType: Type, reader: Reader, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(javaType, JSON.parse(reader), config)
/**
* Deserialize JSON from an [InputStream] to a specified [KType].
*
* @param resultType the target type
* @param inputStream the JSON in the form of an [InputStream]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(resultType: KType, inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(resultType, JSON.parse(inputStream), config)
/**
* Deserialize JSON from an [InputStream] to a specified [KClass].
*
* @param resultClass the target class
* @param inputStream the JSON in the form of an [InputStream]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun <T: Any> parse(resultClass: KClass<T>, inputStream: InputStream,
config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONDeserializer.deserialize(resultClass, JSON.parse(inputStream), config)
/**
* Deserialize JSON from an [InputStream] to the inferred [KType].
*
* @param inputStream the JSON in the form of an [InputStream]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
inline fun <reified T: Any> parse(inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): T? =
parse(typeOf<T>(), inputStream, config) as T?
/**
* Deserialize JSON from an [InputStream] to a specified Java [Type].
*
* @param javaType the target type
* @param inputStream the JSON in the form of an [InputStream]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(javaType: Type, inputStream: InputStream, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(javaType, JSON.parse(inputStream), config)
/**
* Deserialize JSON from a [File] to a specified [KType].
*
* @param resultType the target type
* @param file the JSON in the form of a [File]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(resultType: KType, file: File, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(resultType, JSON.parse(file), config)
/**
* Deserialize JSON from a [File] to a specified [KClass].
*
* @param resultClass the target class
* @param file the JSON in the form of a [File]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun <T: Any> parse(resultClass: KClass<T>, file: File, config: JSONConfig = JSONConfig.defaultConfig): T? =
JSONDeserializer.deserialize(resultClass, JSON.parse(file), config)
/**
* Deserialize JSON from a [File] to the inferred [KType].
*
* @param file the JSON in the form of a [File]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
inline fun <reified T: Any> parse(file: File, config: JSONConfig = JSONConfig.defaultConfig): T? =
parse(typeOf<T>(), file, config) as T?
/**
* Deserialize JSON from a [File] to a specified Java [Type].
*
* @param javaType the target type
* @param file the JSON in the form of a [File]
* @param config an optional [JSONConfig] to customise the conversion
* @return the converted object
*/
fun parse(javaType: Type, file: File, config: JSONConfig = JSONConfig.defaultConfig): Any? =
JSONDeserializer.deserialize(javaType, JSON.parse(file), config)
}
<file_sep># Change Log
The format is based on [Keep a Changelog](http://keepachangelog.com/).
## [4.8] - 2023-07-10
### Changed
- `pom.xml`: updated dependency versions
## [4.7.5] - 2023-01-08
### Changed
- `pom.xml`: bumped dependency versions
## [4.7.4] - 2022-11-21
### Changed
- `pom.xml`: bumped dependency versions
## [4.7.3] - 2022-11-08
### Changed
- `pom.xml`: bumped dependency versions
- `pom.xml`: updated to Kotlin 1.6.10
## [4.7.2] - 2022-10-16
### Changed
- `pom.xml`: bumped dependency versions
## [4.7.1] - 2022-04-18
### Changed
- `pom.xml`: bumped dependency version
## [4.7] - 2022-02-20
### Changed
- `pom.xml`: bumped dependency versions
## [4.6] - 2022-02-11
### Changed
- `JSONSerializerFunctions`: fixed bug in serialization of some internal Kotlin classes
## [4.5] - 2021-11-07
### Changed
- `pom.xml`: updated to Kotlin 1.5.20
## [4.4] - 2021-09-16
### Changed
- `JSONDeserializer`: improved type determination for parameterised types with upper bound
- `pom.xml`: bumped dependency versions
## [4.3] - 2021-05-04
### Changed
- several: switched to use `typeOf()`
- `pom.xml`: added compiler switch
- `JSONDeserializer`, `JSONDeserializerFunctions`: add validation of UUID (workaround for Java bug)
## [4.2] - 2021-04-19
### Changed
- `pom.xml`: updated dependency versions
- `JSONFun.kt`: removed `value` extension variables (no longer necessary)
## [4.1] - 2021-02-28
### Changed
- `JSONDeserializer`: added duplicate check on deserialization of `Set`
## [4.0] - 2021-01-10
### Added
- `JSONKotlinException`: New exception class
### Changed
- several: switched to use `JSONKotlinException`
- `JSONDeserializer`: make use of pointer on error messages
- `JSONDeserializer`: improved error messages on deserializing objects
## [3.16] - 2021-01-07
### Changed
- `JSONFun.kt`: added `value` extension variables for `JSONValue` primitive types
## [3.15] - 2021-01-03
### Added
- `USERGUIDE.md`
- `CUSTOM.md`
### Changed
- `pom.xml`: updated dependency versions
- `JSONDeserializer`: simplified `deserializeAny`
- `JSONSerializer`, `JSONDeserializer`, `JSONStringify`: added support for Java Streams
- `JSONConfig`: bug fix in `combineAll`
## [3.14] - 2020-11-30
### Changed
- `JSONFun`: additional extension functions on `JSONValue`
- `JSONConfig`: bug fix on `fromJSON`
- `JSONDeserializer`: minor bug fix
## [3.13] - 2020-11-25
### Changed
- `JSONAuto`: added more helper functions
## [3.12] - 2020-11-25
### Changed
- `JSONDeserializer`: modified to allow use by `YAMLSequence` and `YAMLMapping`
- `README.md`: added badges
### Added
- `travis.yml`
## [3.11] - 2020-09-16
### Changed
- `pom.xml`: updated to Kotlin 1.4.0
## [3.10.1] - 2020-08-25
### Changed
- `pom.xml`: fixed generation of sources jar
- `JSONJava`, `JSONJavaTest`: moved to kotlin directory (to allow sources jar generation)
## [3.10] - 2020-08-25
### Changed
- `JSONDeserializer`: further improvements to handling of parameterized types
## [3.9] - 2020-08-20
### Changed
- `JSONConfig`: changed `toJSON` and `fromJSON` to use `JSONTypeRef`
## [3.8] - 2020-07-12
### Changed
- `JSONDeserializer`: improved handling of parameterized types
## [3.7] - 2020-07-07
### Changed
- `JSONDeserializerFunctions`: added `hasSingleParameter` and `findParameterName` (moved from `JSONDeserializer`)
- `JSONDeserializer`: improved deserialization of objects with missing parameters
## [3.6] - 2020-05-03
### Added
- `JSONDeserializerFunctions`: (split out from `JSONDeserializer`)
### Changed
- `JSONDeserializerFunctions`: improved handling of `fromJSON` (in companion object)
## [3.5] - 2020-04-23
### Changed
- `JSONConfig`: added `streamOutput` switch (for `json-ktor`)
- `JSONSerializerFunctions`: changed `toJsonCache` handling (more efficient)
- `JSONSerializer`, `JSONSerializerFunctions`: improved handling of classes output by `toString()`
- `JSONDeserializer`, `JSONSerializerFunctions`: add classes from `java.time` package
## [3.4.1] - 2020-04-21
### Changed
- `pom.xml`: updated dependency versions
## [3.4] - 2020-04-18
### Changed
- `JSONSerializer`, `JSONStringify`: added checks for circular references
## [3.3] - 2020-04-18
### Added
- `JSONSerializerFunctions`: common functionality for `JSONSerializer`, `JSONStringify` etc. (split out from
`JSONSerializer`)
### Changed
- `JSONDeserializer`: added check for `@JSONIgnore`
### Removed
- `TestAnnotatedClasses.kt`, `TestSealedClasses.kt`: moved to `json-kotlin-test-classes`
## [3.2] - 2020-04-13
### Changed
- `JSONConfig`, `JSONAuto`, `JSONFun`, `JSONSerializer`: accommodate JSONStringify
- `JSONTypeRef`: added `nullable` parameter
### Added
- `JSONStringify`: stringify without intermediate JSONValue tree
## [3.1] - 2020-04-05
### Changed
- `JSONConfig`, `JSONSerializer`: added `includeNulls` switch
- `JSONConfig`, `JSONSerializer`: added annotations to specify that null properties are to be included
- `JSONConfig`, `JSONDeserializer`: added `allowExtra` switch
- `JSONConfig`, `JSONDeserializer`: added annotations to specify that extra properties are to be ignored
### Added
- `JSONIncludeIfNull`: Annotation class
- `JSONIncludeAllProperties`: Annotation class
- `JSONAllowExtra`: Annotation class
## [3.0] - 2020-01-27
### Added
- `JSONTypeRef`: implementation of the [TypeReference](https://gafter.blogspot.com/2006/12/super-type-tokens.html)
pattern
### Changed
- `JSONAuto`, `JSONDeserializer`: changed to use `JSONTypeRef`
- `JSONFun`: improved `toKType`
- `JSONConfig`: added switches to select handling of `BigInteger` and `BigDecimal`
- Several: switched to version 3.0 of `jsonutil` - improved handling of decimal fractions (`JSONDecimal`)
## [2.1] - 2019-12-11
### Changed
- `JSONFun`: added new `targetKType` that takes nested `KType`
- `JSONFun`: added `CharSequence.parseListJSON()`, `CharSequence.parseSetJSON()` and `CharSequence.parseMapJSON()`
### Added
- `JSONDelegate`: delegate class to assist in deserializing parameterized classes.
## [2.0] - 2019-11-17
### Changed
- `JSONConfig`: Sealed class discriminator property may now be specified
- `JSONConfig`: Modifying functions that used to return `this` for chaining no longer do so (breaking change)
## [1.2] - 2019-11-11
### Changed
- `JSONSerializer`: Added serialization of sealed classes
- `JSONDeserializer`: Added deserialization of sealed classes
- Tests: switched to use of external repository (to avoid compilation order issues)
## [1.1] - 2019-11-03
### Changed
- Updated version to 1.0
- `JSONConfig`: improved selection of custom serialization and deserialization functions
- `JSONConfig`: added shortcut custom serialization / deserialization functions using `toString()` and constructor
taking `String` parameter
- `JSONDeserializer`: changed to use new custom serialization and deserialization functions
- `JSONSerializer`: changed to use new custom serialization and deserialization functions
- Several: added more KDoc
### Added
- `JSONJava`: to access Kotlin serialization and deserialization from Java
## [1.0] - 2019-10-08
### Changed
- Updated version to 1.0
- `JSONDeserializer`: improved deserialization, including defaults if types not specified
## [0.13] - 2019-09-22
### Changed
- `JSONConfig`: added `charset`
## [0.12] - 2019-09-19
### Changed
- `JSONFun`: changed name of `targetJSON` function to `targetKType`
- `JSONFun`: added `toKType` extension function
- `JSONDeserializer`: added function to take Java `Type`
- `JSONAuto`: added function to take Java `Type`
## [0.11] - 2019-09-17
### Changed
- `JSONDeserializer`: added shared function to access type parameters
- `JSONAuto`: added `targetJSON` function
## [0.10] - 2019-09-11
### Changed
- `JSONConfig`: added more KDoc
- `JSONConfig`: added custom name and ignore annotation specification
- `JSONConfig`: added `defaultConfig` (and added use of default to other functions)
- `JSONConfig`: added combine functions
- `JSONDeserializer`: changed to use custom name and ignore annotations
- `JSONFun`: changed `asJSON` to `asJSONValue`; changed `toJSON` to `isJSON`
- `JSONFun`: added coverage of data types `Char`, `Short`, `Byte`
- `JSONFun`: added added more extensions functions
- `JSONFun`: added KDoc
- `JSONSerializer`: changed to use custom name and ignore annotations
- `JSONDeserializer`: improved enum handling
## [0.9] - 2019-07-17
### Changed
- `JSONAuto`: added optional `JSONConfig` to all methods
- `JSONAuto`: Changed `parse` to take `CharSequence` instead of `String`
- `JSONConfig`: fixed typo in method names
- `JSONDeserializer`: added deserialization of `java.util.BitSet`
- `JSONDeserializer`: switched to use `JSONInt` `typealias`
- `JSONFun`: renamed `toJSON` to `isJSON`
- `JSONFun`: added `Any?.asJSON()`
- `JSONFun`: added `CharSequence.parseJSON()`
- `JSONFun`: added `Any?.stringifyJSON()`
- `JSONSerializer`: added serialization of `java.math.BigDecimal`, `java.math.BigInteger`, `java.net.URI`,
`java.net.URL`
- `JSONSerializer`: fixed typo - `invokeSetter` should have been `invokeGetter`
- `JSONSerializer`: switched to use `JSONInt` `typealias`
- `pom.xml`: switched to use of parent POM
- `pom.xml`: added link to `jsonutil` JavaDoc
## [0.8] - 2019-07-08
### Changed
- `JSONConfig`: changed to use system default buffer size
- `JSONSerializer`: added serialization of `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`
- `JSONDeserializer`: added deserialization of `java.sql.Date`, `java.sql.Time`, `java.sql.Timestamp`
- `README.md`: documentation added (more needed)
### Added
- `JSONFun`: JSON helper functions
- `JSONFunTest`: tests for JSON helper functions
## [0.7] - 2019-07-06
### Changed
- `JSONDeserializer`: added deserialization of Kotlin `object`s (serialization already worked)
- `JSONSerializer`: improved serialization of Java objects
- `JSONDeserializer`: improved deserialization of Java objects
- `JSONSerializer`: added serialization of `java.time.Duration`, `java.time.Period`
- `JSONDeserializer`: added deserialization of `java.time.Duration`, `java.time.Period`
- `JSONConfig`: added `readBufferSize`
## [0.6] - 2019-05-23
### Changed
- `JSONAuto`: added `JSONConfig` to functions
- `JSONDeserializer`: added `JSONConfig` to functions
## [0.5] - 2019-05-21
### Changed
- `JSONSerializer`: added serialization of `Pair` and `Triple`
- `JSONSerializerTest`: corresponding tests
- `JSONDeserializer`: added deserialization of `Pair` and `Triple`
- `JSONDeserializerTest`: corresponding tests
- `JSONDeserializer`: added checking of types marked nullable
- `JSONDeserializerTest`: corresponding tests
- `JSONDeserializer`: added use of custom deserialization from `JSONConfig`
- `JSONDeserializerTest`: corresponding tests
- `JSONSerializer`: added use of custom serialization from `JSONConfig`
- `JSONSerializerTest`: corresponding tests
### Added
- `JSONConfig`: new configuration class
## [0.4] - 2019-05-14
### Changed
- `JSONDeserializerTest`: modified to use `KType` values
- `JSONSerializer`: optimisation of data classes
- `JSONAuto`: added `stringify()`
## [0.3] - 2019-04-26
### Changed
- `JSONAuto` renamed to `JSONDeserializer`
- `JSONAutoTest` renamed to `JSONDeserializerTest`
### Added
- `JSONAuto`: new version (pass-through to `JSONDeserializer`)
- `DummyClasses` (test): split out from `JSONDeserializerTest`
- `JSONSerializer`
- `JSONSerializerTest`
- `JSONIgnore` annotation class
## [0.2] - 2019-04-23
### Changed
- `JSONAutoTest`: added more tests (derived classes)
- `JSONAuto`: added code to check for `@JSONName` annotation
- `JSONAutoTest`: added tests for `@JSONName` annotation
### Added
- `JSONName`: added annotation
## [0.1] - 2019-04-22
### Added
- `JSONAuto`: `parse` and `deserialize` functions
- `JSONAutoTest`
<file_sep>/*
* @(#) JSONDeserializerFunctionsTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.test.Test
import kotlin.test.assertFailsWith
import kotlin.test.expect
import java.util.UUID
class JSONDeserializerFunctionsTest {
@Test fun `should create UUID`() {
val s = "dbfaa208-ac99-11eb-aca1-d790d50d0f28"
expect(UUID.fromString(s)) { JSONDeserializerFunctions.createUUID(s) }
}
@Test fun `should throw exception on invalid UUID`() {
val s = "dbfaa208-ac99-11eb-aca1-d790d50d0f" // 2 bytes too short
assertFailsWith<IllegalArgumentException> { JSONDeserializerFunctions.createUUID(s) }.let {
expect("Not a valid UUID - dbfaa208-ac99-11eb-aca1-d790d50d0f") { it.message }
}
}
}
<file_sep>/*
* @(#) JSONDeserializerFunctions.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.full.companionObject
import kotlin.reflect.full.functions
import kotlin.reflect.full.isSuperclassOf
import java.util.UUID
import net.pwall.json.validation.JSONValidation
object JSONDeserializerFunctions {
private val fromJsonCache = HashMap<Pair<KClass<*>, KClass<*>>, KFunction<*>>()
fun findFromJSON(resultClass: KClass<*>, parameterClass: KClass<*>): KFunction<*>? {
val cacheKey = resultClass to parameterClass
fromJsonCache[cacheKey]?.let { return it }
val newEntry = try {
resultClass.companionObject?.functions?.find { function ->
function.name == "fromJSON" &&
function.parameters.size == 2 &&
function.parameters[0].type.classifier == resultClass.companionObject &&
(function.parameters[1].type.classifier as KClass<*>).isSuperclassOf(parameterClass) &&
function.returnType.classifier == resultClass
}
}
catch (e: Exception) {
null
}
return newEntry?.apply { fromJsonCache[cacheKey] = this }
}
fun KFunction<*>.hasSingleParameter(paramClass: KClass<*>) =
parameters.size == 1 && (parameters[0].type.classifier as? KClass<*>)?.isSuperclassOf(paramClass) ?: false
fun findParameterName(parameter: KParameter, config: JSONConfig): String? =
config.findNameFromAnnotation(parameter.annotations) ?: parameter.name
fun createUUID(string: String): UUID {
if (!JSONValidation.isUUID(string))
throw IllegalArgumentException("Not a valid UUID - $string")
return UUID.fromString(string)
}
}
<file_sep>/*
* @(#) JSONFunTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KTypeProjection
import kotlin.reflect.full.createType
import kotlin.reflect.full.starProjectedType
import kotlin.test.assertNull
import kotlin.test.expect
import kotlin.test.Test
import java.lang.reflect.Type
class JSONFunTest {
@Test fun `makeJSON with asJSONValue should create the same JSONObject as explicit creation`() {
val expected = JSONObject().apply {
putValue("testString", "xyz")
putValue("testInt", 12345)
}
expect(expected) { makeJSON("testString" to "xyz".asJSONValue(), "testInt" to 12345.asJSONValue()) }
}
@Test fun `makeJSON with isJSON should create the same JSONObject as explicit creation`() {
val expected = JSONObject().apply {
putValue("testString", "xyz")
putValue("testInt", 12345)
}
expect(expected) { makeJSON("testString" isJSON "xyz", "testInt" isJSON 12345) }
}
@Test fun `asJSONValue should correctly handle String`() {
val testString = "testing..."
expect(JSONString(testString)) { testString.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Char`() {
val testChar = 'Q'
expect(JSONString("Q")) { testChar.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Int`() {
val testInt = 987654321
expect(JSONInt(testInt)) { testInt.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Long`() {
val testLong = 1234567890123456789
expect(JSONLong(testLong)) { testLong.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Short`() {
val testShort: Short = 1234
expect(JSONInt(testShort.toInt())) { testShort.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Byte`() {
val testByte: Byte = 123
expect(JSONInt(testByte.toInt())) { testByte.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Float`() {
val testFloat = 3.14159F
expect(JSONFloat(testFloat)) { testFloat.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Double`() {
val testDouble = 3.14159265358979323846
expect(JSONDouble(testDouble)) { testDouble.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle Boolean`() {
val testBoolean = true
expect(JSONBoolean(testBoolean)) { testBoolean.asJSONValue() }
}
@Test fun `isJSON should correctly handle String`() {
val testString = "what next?"
expect("testString" to JSONString(testString)) { "testString" isJSON testString }
}
@Test fun `isJSON should correctly handle Char`() {
val testChar = 'Z'
expect("testChar" to JSONString("Z")) { "testChar" isJSON testChar }
}
@Test fun `isJSON should correctly handle Int`() {
val testInt = 987654321
expect("testInt" to JSONInt(testInt)) { "testInt" isJSON testInt }
}
@Test fun `isJSON should correctly handle Long`() {
val testLong = 1234567890123456789
expect("testLong" to JSONLong(testLong)) { "testLong" isJSON testLong }
}
@Test fun `isJSON should correctly handle Short`() {
val testShort: Short = 1234
expect("testShort" to JSONInt(testShort.toInt())) { "testShort" isJSON testShort }
}
@Test fun `isJSON should correctly handle Byte`() {
val testByte: Byte = 123
expect("testByte" to JSONInt(testByte.toInt())) { "testByte" isJSON testByte }
}
@Test fun `isJSON should correctly handle Float`() {
val testFloat = 3.14159F
expect("testFloat" to JSONFloat(testFloat)) { "testFloat" isJSON testFloat }
}
@Test fun `isJSON should correctly handle Double`() {
val testDouble = 3.14159265358979323846
expect("testDouble" to JSONDouble(testDouble)) { "testDouble" isJSON testDouble }
}
@Test fun `isJSON should correctly handle Boolean`() {
val testBoolean = true
expect("testBoolean" to JSONBoolean(testBoolean)) { "testBoolean" isJSON testBoolean }
}
@Test fun `parseJSON should correctly parse string`() {
val json = """{"field1":"Hi there!","field2":888}"""
val expected: Dummy1? = Dummy1("Hi there!", 888)
expect(expected) { json.parseJSON() }
}
@Test fun `parseJSON should correctly parse string using parameterised type`() {
val json = """{"field1":"Hi there!","field2":888}"""
expect(Dummy1("Hi there!", 888)) { json.parseJSON<Dummy1>() }
}
@Test fun `parseJSON should correctly parse string using explicit KClass`() {
val json = """{"field1":"Hi there!","field2":888}"""
expect(Dummy1("Hi there!", 888)) { json.parseJSON(Dummy1::class) }
}
@Test fun `parseJSON should correctly parse string using explicit KType`() {
val json = """{"field1":"Hi there!","field2":888}"""
expect(Dummy1("Hi there!", 888)) { json.parseJSON(Dummy1::class.starProjectedType) }
}
@Test fun `stringify should work on any object`() {
val dummy1 = Dummy1("Hi there!", 888)
val expected = JSONObject().apply {
putValue("field1", "Hi there!")
putValue("field2", 888)
}
expect(expected) { JSON.parse(dummy1.stringifyJSON()) }
}
@Test fun `stringify should work on null`() {
val dummy1 = null
expect("null") { dummy1.stringifyJSON() }
}
@Test fun `asJSONValue should correctly handle arbitrary object`() {
val dummy1 = Dummy1("Hi there!", 888)
expect(makeJSON("field1" isJSON "Hi there!", "field2" isJSON 888)) { dummy1.asJSONValue() }
}
@Test fun `asJSONValue should correctly handle null`() {
val dummy1 = null
assertNull(dummy1.asJSONValue())
}
@Test fun `targetKType should create correct type`() {
val listStrings = listOf("abc", "def")
val jsonArrayString = JSONArray().apply {
addValue("abc")
addValue("def")
}
expect(listStrings) { JSONDeserializer.deserialize(targetKType(List::class, String::class), jsonArrayString) }
}
@Test fun `targetKType should create correct complex type`() {
val listStrings = listOf(listOf("abc", "def"))
val jsonArrayArrayString = JSONArray().apply {
add(JSONArray().apply {
addValue("abc")
addValue("def")
})
}
expect(listStrings) {
JSONDeserializer.deserialize(targetKType(List::class, targetKType(List::class, String::class)),
jsonArrayArrayString)
}
}
@Test fun `toKType should convert simple class`() {
val type: Type = JavaClass1::class.java
expect(JavaClass1::class.starProjectedType) { type.toKType() }
}
@Test fun `toKType should convert parameterized class`() {
val field = JavaClass2::class.java.getField("field1")
val type: Type = field.genericType
val expected = java.util.List::class.createType(
listOf(KTypeProjection.invariant(JavaClass1::class.createType(nullable = true))))
expect(expected) { type.toKType() }
}
@Test fun `toKType should convert parameterized class with extends`() {
val field = JavaClass2::class.java.getField("field2")
val type: Type = field.genericType
val expected = java.util.List::class.createType(
listOf(KTypeProjection.covariant(JavaClass1::class.createType(nullable = true))))
expect(expected) { type.toKType() }
}
@Test fun `toKType should convert parameterized class with super`() {
val field = JavaClass2::class.java.getField("field3")
val type: Type = field.genericType
val expected = java.util.List::class.createType(
listOf(KTypeProjection.contravariant(JavaClass1::class.createType(nullable = true))))
expect(expected) { type.toKType() }
}
@Test fun `toKType should convert nested parameterized class`() {
val field = JavaClass2::class.java.getField("field4")
val type: Type = field.genericType
val expected = java.util.List::class.createType(
listOf(KTypeProjection.invariant(java.util.List::class.createType(
listOf(KTypeProjection.invariant(JavaClass1::class.createType(nullable = true))),
nullable = true))))
expect(expected) { type.toKType() }
}
@Test fun `toKType should convert nested parameterized class with extends`() {
val field = JavaClass2::class.java.getField("field5")
val type: Type = field.genericType
val expected = java.util.List::class.createType(
listOf(KTypeProjection.invariant(java.util.List::class.createType(
listOf(KTypeProjection.covariant(JavaClass1::class.createType(nullable = true))),
nullable = true))))
expect(expected) { type.toKType() }
}
@Test fun `decode should convert a JSONObject to a specified type`() {
val json = JSONObject().apply {
putValue("field1", "abdef")
putValue("field2", 54321)
}
val expected: Dummy1? = Dummy1("abdef", 54321)
expect(expected) { json.deserialize(Dummy1::class.starProjectedType) }
}
@Test fun `decode should convert a JSONObject to a specified class`() {
val json = JSONObject().apply {
putValue("field1", "abdef")
putValue("field2", 54321)
}
val expected: Dummy1? = Dummy1("abdef", 54321)
expect(expected) { json.deserialize(Dummy1::class) }
}
@Test fun `decode should convert a JSONObject to an implied class`() {
val json = JSONObject().apply {
putValue("field1", "abdef")
putValue("field2", 54321)
}
val expected: Dummy1? = Dummy1("abdef", 54321)
expect(expected) { json.deserialize() }
}
@Test fun `decode should convert a JSONObject to a specified Java class`() {
val json = JSONObject().apply {
putValue("field1", "abdef")
putValue("field2", 54321)
}
val expected: Dummy1? = Dummy1("abdef", 54321)
expect(expected) { json.deserialize(Dummy1::class.java) }
}
}
<file_sep>/*
* @(#) JSONSerializer.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KProperty
import kotlin.reflect.full.staticProperties
import kotlin.reflect.jvm.isAccessible
import java.math.BigDecimal
import java.math.BigInteger
import java.util.BitSet
import java.util.Calendar
import java.util.Date
import java.util.Enumeration
import java.util.stream.BaseStream
import net.pwall.json.JSONKotlinException.Companion.fail
import net.pwall.json.JSONSerializerFunctions.findToJSON
import net.pwall.json.JSONSerializerFunctions.formatISO8601
import net.pwall.json.JSONSerializerFunctions.isSealedSubclass
import net.pwall.json.JSONSerializerFunctions.isToStringClass
/**
* JSON Auto serialize for Kotlin.
*
* @author <NAME>
*/
object JSONSerializer {
fun serialize(obj: Any?, config: JSONConfig = JSONConfig.defaultConfig): JSONValue? =
serialize(obj, config, mutableSetOf())
private fun serialize(obj: Any?, config: JSONConfig, references: MutableSet<Any>): JSONValue? {
if (obj == null)
return null
config.findToJSONMapping(obj::class)?.let { return it(obj) }
when (obj) {
is JSONValue -> return obj
is CharSequence -> return JSONString(obj)
is Char -> return JSONString(StringBuilder().append(obj))
is Number -> return serializeNumber(obj, config)
is Boolean -> return if (obj) JSONBoolean.TRUE else JSONBoolean.FALSE
is CharArray -> return JSONString(StringBuilder().append(obj))
is Array<*> -> return serializeArray(obj, config, references)
is Pair<*, *> -> return serializePair(obj, config, references)
is Triple<*, *, *> -> return serializeTriple(obj, config, references)
}
val objClass = obj::class
if (objClass.isToStringClass() || obj is Enum<*>)
return JSONString(obj.toString())
try {
objClass.findToJSON()?.let { return it.call(obj) }
}
catch (e: Exception) {
fail("Error in custom toJSON - ${objClass.simpleName}", e)
}
when (obj) {
is Iterable<*> -> return JSONArray(obj.map { serialize(it, config, references) })
is Iterator<*> -> return JSONArray().apply {
for (item in obj)
add(serialize(item, config, references))
}
is BaseStream<*, *> -> return JSONArray().apply {
for (item in obj)
add(serialize(item, config, references))
}
is Sequence<*> -> return JSONArray().apply {
for (item in obj)
add(serialize(item, config, references))
}
is Enumeration<*> -> return JSONArray().apply {
for (item in obj)
add(serialize(item, config, references))
}
is Map<*, *> -> return serializeMap(obj, config, references)
is Calendar -> return JSONString(obj.formatISO8601())
is Date -> return JSONString((Calendar.getInstance().apply { time = obj }).formatISO8601())
is BitSet -> return serializeBitSet(obj)
}
val result = JSONObject()
try {
references.add(obj)
if (objClass.isSealedSubclass())
result[config.sealedClassDiscriminator] = JSONString(objClass.simpleName ?: "null")
val includeAll = config.hasIncludeAllPropertiesAnnotation(objClass.annotations)
if (objClass.isData && objClass.constructors.isNotEmpty()) {
// data classes will be a frequent use of serialization, so optimise for them
val constructor = objClass.constructors.first()
for (parameter in constructor.parameters) {
val member = objClass.members.find { it.name == parameter.name }
if (member is KProperty<*>)
result.addUsingGetter(member, parameter.annotations, obj, config, references, includeAll)
}
// now check whether there are any more properties not in constructor
val statics: Collection<KProperty<*>> = objClass.staticProperties
for (member in objClass.members) {
if (member is KProperty<*> && !statics.contains(member) &&
!constructor.parameters.any { it.name == member.name })
result.addUsingGetter(member, member.annotations, obj, config, references, includeAll)
}
}
else {
val statics: Collection<KProperty<*>> = objClass.staticProperties
for (member in objClass.members) {
if (member is KProperty<*> && !statics.contains(member)) {
val combinedAnnotations = ArrayList(member.annotations)
objClass.constructors.firstOrNull()?.parameters?.find { it.name == member.name }?.let {
combinedAnnotations.addAll(it.annotations)
}
result.addUsingGetter(member, combinedAnnotations, obj, config, references, includeAll)
}
}
}
}
finally {
references.remove(obj)
}
return result
}
private fun JSONObject.addUsingGetter(member: KProperty<*>, annotations: List<Annotation>?, obj: Any,
config: JSONConfig, references: MutableSet<Any>, includeAll: Boolean) {
if (!config.hasIgnoreAnnotation(annotations)) {
val name = config.findNameFromAnnotation(annotations) ?: member.name
val wasAccessible = member.isAccessible
member.isAccessible = true
try {
val v = member.getter.call(obj)
if (v != null && v in references)
fail("Circular reference: field ${member.name} in ${obj::class.simpleName}")
if (v != null || config.hasIncludeIfNullAnnotation(annotations) || config.includeNulls || includeAll)
put(name, serialize(v, config, references))
}
catch (e: JSONException) {
throw e
}
catch (e: Exception) {
fail("Error getting property ${member.name} from ${obj::class.simpleName}", e)
}
finally {
member.isAccessible = wasAccessible
}
}
}
private fun serializeNumber(number: Number, config: JSONConfig): JSONValue = when (number) {
is Int -> JSONInt(number)
is Long -> JSONLong(number)
is Short -> JSONInt(number.toInt())
is Byte -> JSONInt(number.toInt())
is Float -> JSONFloat(number)
is BigInteger -> if (config.bigIntegerString) JSONString(number.toString()) else JSONLong(number.toLong())
is BigDecimal -> if (config.bigDecimalString) JSONString(number.toString()) else JSONDecimal(number)
else -> JSONDouble(number.toDouble())
}
private fun serializeArray(array: Array<*>, config: JSONConfig, references: MutableSet<Any>): JSONValue {
if (array.isArrayOf<Char>())
return JSONString(StringBuilder().apply {
for (ch in array)
append(ch)
})
return JSONArray(array.map { serialize(it, config, references) })
}
private fun serializePair(pair: Pair<*, *>, config: JSONConfig, references: MutableSet<Any>) = JSONArray().apply {
add(serialize(pair.first, config, references))
add(serialize(pair.second, config, references))
}
private fun serializeTriple(triple: Triple<*, *, *>, config: JSONConfig, references: MutableSet<Any>) =
JSONArray().apply {
add(serialize(triple.first, config, references))
add(serialize(triple.second, config, references))
add(serialize(triple.third, config, references))
}
private fun serializeMap(map: Map<*, *>, config: JSONConfig, references: MutableSet<Any>) = JSONObject().apply {
for (entry in map.entries) {
this[entry.key.toString()] = serialize(entry.value, config, references)
}
}
private fun serializeBitSet(bitSet: BitSet) = JSONArray(ArrayList<JSONValue>().apply {
for (i in 0 until bitSet.length())
if (bitSet.get(i))
add(JSONInt(i))
})
}
<file_sep>/*
* @(#) JSONStringifyTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.test.assertFailsWith
import kotlin.test.expect
import kotlin.test.Test
import java.math.BigDecimal
import java.math.BigInteger
import java.net.URI
import java.net.URL
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.MonthDay
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.Period
import java.time.Year
import java.time.YearMonth
import java.time.ZonedDateTime
import java.util.BitSet
import java.util.Calendar
import java.util.TimeZone
import java.util.UUID
import java.util.stream.IntStream
import java.util.stream.Stream
import net.pwall.json.JSONStringify.appendJSON
import net.pwall.json.test.JSONExpect.Companion.expectJSON
class JSONStringifyTest {
@Test fun `should stringify null`() {
expect("null") { JSONStringify.stringify(null) }
}
@Test fun `should use toJSON if specified in JSONConfig`() {
val config = JSONConfig().apply {
toJSON<Dummy1> { obj ->
obj?.let {
JSONObject().apply {
putValue("a", it.field1)
putValue("b", it.field2)
}
}
}
}
expectJSON(JSONStringify.stringify(Dummy1("xyz", 888), config)) {
count(2)
property("a", "xyz")
property("b", 888)
}
}
@Test fun `should stringify a JSONValue`() {
val json = JSONObject().apply {
putValue("a", "Hello")
putValue("b", 27)
}
expect("""{"a":"Hello","b":27}""") { JSONStringify.stringify(json) }
}
@Test fun `should stringify a simple string`() {
expect("\"abc\"") { JSONStringify.stringify("abc") }
}
@Test fun `should stringify a string with a newline`() {
expect("\"a\\nc\"") { JSONStringify.stringify("a\nc") }
}
@Test fun `should stringify a string with a unicode sequence`() {
expect("\"a\\u2014c\"") { JSONStringify.stringify("a\u2014c") }
}
@Test fun `should stringify a single character`() {
expect("\"X\"") { JSONStringify.stringify('X') }
}
@Test fun `should stringify a charArray`() {
expect("\"abc\"") { JSONStringify.stringify(charArrayOf('a', 'b', 'c')) }
}
@Test fun `should stringify an integer`() {
expect("123456789") { JSONStringify.stringify(123456789) }
}
@Test fun `should stringify an integer 0`() {
expect("0") { JSONStringify.stringify(0) }
}
@Test fun `should stringify a negative integer`() {
expect("-888") { JSONStringify.stringify(-888) }
}
@Test fun `should stringify a long`() {
expect("123456789012345678") { JSONStringify.stringify(123456789012345678) }
}
@Test fun `should stringify a negative long`() {
expect("-111222333444555666") { JSONStringify.stringify(-111222333444555666) }
}
@Test fun `should stringify a short`() {
val x: Short = 12345
expect("12345") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a negative short`() {
val x: Short = -4444
expect("-4444") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a byte`() {
val x: Byte = 123
expect("123") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a negative byte`() {
val x: Byte = -99
expect("-99") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a float`() {
val x = 1.2345F
expect("1.2345") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a negative float`() {
val x: Float = -567.888F
expect("-567.888") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a double`() {
val x = 1.23456789
expect("1.23456789") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a negative double`() {
val x = -9.998877665
expect("-9.998877665") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a BigInteger`() {
val x = BigInteger.valueOf(123456789000)
expect("123456789000") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a negative BigInteger`() {
val x = BigInteger.valueOf(-123456789000)
expect("-123456789000") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a BigInteger as string when specified in JSONConfig`() {
val config = JSONConfig().apply {
bigIntegerString = true
}
val x = BigInteger.valueOf(123456789000)
expect("\"123456789000\"") { JSONStringify.stringify(x, config) }
}
@Test fun `should stringify a BigDecimal`() {
val x = BigDecimal("12345.678")
expect("12345.678") { JSONStringify.stringify(x) }
}
@Test fun `should stringify a BigDecimal as string when specified in JSONConfig`() {
val config = JSONConfig().apply {
bigDecimalString = true
}
val x = BigDecimal("12345.678")
expect("\"12345.678\"") { JSONStringify.stringify(x, config) }
}
@Test fun `should stringify a Boolean`() {
var x = true
expect("true") { JSONStringify.stringify(x) }
x = false
expect("false") { JSONStringify.stringify(x) }
}
@Test fun `should stringify an array of characters`() {
expect("\"abc\"") { JSONStringify.stringify(arrayOf('a', 'b', 'c')) }
}
@Test fun `should stringify an array of integers`() {
expect("[123,456,789]") { JSONStringify.stringify(arrayOf(123, 456, 789)) }
}
@Test fun `should stringify an array of strings`() {
expect("""["Hello","World"]""") { JSONStringify.stringify(arrayOf("Hello", "World")) }
}
@Test fun `should stringify an array of arrays`() {
expect("[[11,22],[33,44]]") { JSONStringify.stringify(arrayOf(arrayOf(11, 22), arrayOf(33, 44))) }
}
@Test fun `should stringify an empty array`() {
expect("[]") { JSONStringify.stringify(emptyArray<Int>()) }
}
@Test fun `should stringify an array of nulls`() {
expect("[null,null,null]") { JSONStringify.stringify(arrayOfNulls<String>(3)) }
}
@Test fun `should stringify a Pair of integers`() {
expect("[123,789]") { JSONStringify.stringify(123 to 789) }
}
@Test fun `should stringify a Pair of strings`() {
expect("""["back","front"]""") { JSONStringify.stringify("back" to "front") }
}
@Test fun `should stringify a Triple of integers`() {
expect("[123,789,0]") { JSONStringify.stringify(Triple(123, 789, 0)) }
}
@Test fun `should stringify a class with a custom toJson`() {
expect("""{"dec":"49","hex":"31"}""") { JSONStringify.stringify(DummyFromJSON(49)) }
}
@Test fun `should stringify a list of integers`() {
expect("[1234,4567,7890]") { JSONStringify.stringify(listOf(1234, 4567, 7890)) }
}
@Test fun `should stringify a list of strings`() {
expect("""["alpha","beta","gamma"]""") { JSONStringify.stringify(listOf("alpha", "beta", "gamma")) }
}
@Test fun `should stringify a list of strings including null`() {
expect("""["alpha","beta",null,"gamma"]""") { JSONStringify.stringify(listOf("alpha", "beta", null, "gamma")) }
}
@Test fun `should stringify a set of strings`() {
// unfortunately, we don't know in what order a set iterator will return the entries, so...
val str = JSONStringify.stringify(setOf("alpha", "beta", "gamma"))
expect(true) { str.startsWith('[') && str.endsWith(']')}
val items = str.drop(1).dropLast(1).split(',').sorted()
expect(3) { items.size }
expect("\"alpha\"") { items[0] }
expect("\"beta\"") { items[1] }
expect("\"gamma\"") { items[2] }
}
@Test fun `should stringify the results of an iterator`() {
val list = listOf(1, 1, 2, 3, 5, 8, 13, 21)
expect("[1,1,2,3,5,8,13,21]") { JSONStringify.stringify(list.iterator()) }
}
@Test fun `should stringify a sequence`() {
val list = listOf(1, 1, 2, 3, 5, 8, 13, 21)
expect("[1,1,2,3,5,8,13,21]") { JSONStringify.stringify(list.asSequence()) }
}
@Test fun `should stringify the results of an enumeration`() {
val list = listOf("tahi", "rua", "toru", "wh\u0101")
expect("""["tahi","rua","toru","wh\u0101"]""") { JSONStringify.stringify(ListEnum(list)) }
}
@Test fun `should stringify a Java Stream of strings`() {
val stream = Stream.of("tahi", "rua", "toru", "wh\u0101")
expect("""["tahi","rua","toru","wh\u0101"]""") { JSONStringify.stringify(stream) }
}
@Test fun `should stringify a Java IntStream`() {
val stream = IntStream.of(1, 1, 2, 3, 5, 8, 13, 21)
expect("[1,1,2,3,5,8,13,21]") { JSONStringify.stringify(stream) }
}
@Test fun `should stringify a map of string to string`() {
val map = mapOf("tahi" to "one", "rua" to "two", "toru" to "three")
val str = JSONStringify.stringify(map)
expectJSON(str) {
count(3)
property("tahi", "one")
property("rua", "two")
property("toru", "three")
}
}
@Test fun `should stringify a map of string to integer`() {
val map = mapOf("un" to 1, "deux" to 2, "trois" to 3, "quatre" to 4)
val str = JSONStringify.stringify(map)
expectJSON(str) {
count(4)
property("un", 1)
property("deux", 2)
property("trois", 3)
property("quatre", 4)
}
}
@Test fun `should stringify an enum`() {
val value = DummyEnum.ALPHA
expect("\"ALPHA\"") { JSONStringify.stringify(value) }
}
@Test fun `should stringify an SQL date`() {
val str = "2020-04-10"
val date = java.sql.Date.valueOf(str)
expect("\"$str\"") { JSONStringify.stringify(date) }
}
@Test fun `should stringify an SQL time`() {
val str = "00:21:22"
val time = java.sql.Time.valueOf(str)
expect("\"$str\"") { JSONStringify.stringify(time) }
}
@Test fun `should stringify an SQL date-time`() {
val str = "2020-04-10 00:21:22.0"
val timeStamp = java.sql.Timestamp.valueOf(str)
expect("\"$str\"") { JSONStringify.stringify(timeStamp) }
}
@Test fun `should stringify an Instant`() {
val str = "2020-04-09T14:28:51.234Z"
val instant = Instant.parse(str)
expect("\"$str\"") { JSONStringify.stringify(instant) }
}
@Test fun `should stringify a LocalDate`() {
val str = "2020-04-10"
val localDate = LocalDate.parse(str)
expect("\"$str\"") { JSONStringify.stringify(localDate) }
}
@Test fun `should stringify a LocalDateTime`() {
val str = "2020-04-10T00:09:26.123"
val localDateTime = LocalDateTime.parse(str)
expect("\"$str\"") { JSONStringify.stringify(localDateTime) }
}
@Test fun `should stringify a LocalTime`() {
val str = "00:09:26.123"
val localTime = LocalTime.parse(str)
expect("\"$str\"") { JSONStringify.stringify(localTime) }
}
@Test fun `should stringify an OffsetTime`() {
val str = "10:15:06.543+10:00"
val offsetTime = OffsetTime.parse(str)
expect("\"$str\"") { JSONStringify.stringify(offsetTime) }
}
@Test fun `should stringify an OffsetDateTime`() {
val str = "2020-04-10T10:15:06.543+10:00"
val offsetDateTime = OffsetDateTime.parse(str)
expect("\"$str\"") { JSONStringify.stringify(offsetDateTime) }
}
@Test fun `should stringify a ZonedDateTime`() {
val str = "2020-04-10T10:15:06.543+10:00[Australia/Sydney]"
val zonedDateTime = ZonedDateTime.parse(str)
expect("\"$str\"") { JSONStringify.stringify(zonedDateTime) }
}
@Test fun `should stringify a Year`() {
val str = "2020"
val year = Year.parse(str)
expect("\"$str\"") { JSONStringify.stringify(year) }
}
@Test fun `should stringify a YearMonth`() {
val str = "2020-04"
val yearMonth = YearMonth.parse(str)
expect("\"$str\"") { JSONStringify.stringify(yearMonth) }
}
@Test fun `should stringify a MonthDay`() {
val str = "--04-23"
val monthDay = MonthDay.parse(str)
expect("\"$str\"") { JSONStringify.stringify(monthDay) }
}
@Test fun `should stringify a Duration`() {
val str = "PT2H"
val duration = Duration.parse(str)
expect("\"$str\"") { JSONStringify.stringify(duration) }
}
@Test fun `should stringify a Period`() {
val str = "P3M"
val period = Period.parse(str)
expect("\"$str\"") { JSONStringify.stringify(period) }
}
@Test fun `should stringify a URI`() {
val str = "http://pwall.net"
val uri = URI(str)
expect("\"$str\"") { JSONStringify.stringify(uri) }
}
@Test fun `should stringify a URL`() {
val str = "http://pwall.net"
val url = URL(str)
expect("\"$str\"") { JSONStringify.stringify(url) }
}
@Test fun `should stringify a UUID`() {
val str = "e24b6740-7ac3-11ea-9e47-37640adfe63a"
val uuid = UUID.fromString(str)
expect("\"$str\"") { JSONStringify.stringify(uuid) }
}
@Test fun `should stringify a Calendar`() {
val cal = Calendar.getInstance(TimeZone.getTimeZone("GMT")).apply {
set(Calendar.YEAR, 2019)
set(Calendar.MONTH, 3)
set(Calendar.DAY_OF_MONTH, 25)
set(Calendar.HOUR_OF_DAY, 18)
set(Calendar.MINUTE, 52)
set(Calendar.SECOND, 47)
set(Calendar.MILLISECOND, 123)
set(Calendar.ZONE_OFFSET, 10 * 60 * 60 * 1000)
}
expect("\"2019-04-25T18:52:47.123+10:00\"") { JSONStringify.stringify(cal) }
}
@Test fun `should stringify a Date`() {
val cal = Calendar.getInstance().apply {
set(Calendar.YEAR, 2019)
set(Calendar.MONTH, 3)
set(Calendar.DAY_OF_MONTH, 25)
set(Calendar.HOUR_OF_DAY, 18)
set(Calendar.MINUTE, 52)
set(Calendar.SECOND, 47)
set(Calendar.MILLISECOND, 123)
set(Calendar.ZONE_OFFSET, 10 * 60 * 60 * 1000)
}
val date = cal.time
// NOTE - Java implementations are inconsistent - some will normalise the time to UTC
// while others preserve the time zone as supplied. The test below allows for either.
val expected1 = "\"2019-04-25T18:52:47.123+10:00\""
val expected2 = "\"2019-04-25T08:52:47.123Z\""
val result = JSONStringify.stringify(date)
expect(true) { result == expected1 || result == expected2 }
}
@Test fun `should stringify a BitSet`() {
val bitSet = BitSet().apply {
set(1)
set(3)
}
expect("[1,3]") { JSONStringify.stringify(bitSet) }
}
@Test fun `should stringify a simple object`() {
val dummy1 = Dummy1("abcdef", 98765)
expect("""{"field1":"abcdef","field2":98765}""") { JSONStringify.stringify(dummy1) }
}
@Test fun `should stringify a simple object with extra property`() {
val dummy2 = Dummy2("abcdef", 98765)
dummy2.extra = "extra123"
expect("""{"field1":"abcdef","field2":98765,"extra":"extra123"}""") { JSONStringify.stringify(dummy2) }
}
@Test fun `should stringify a simple object with extra property omitting null field`() {
val dummy2 = Dummy2("abcdef", 98765)
dummy2.extra = null
expect("""{"field1":"abcdef","field2":98765}""") { JSONStringify.stringify(dummy2) }
}
@Test fun `should stringify a simple object with extra property including null field when config set`() {
val dummy2 = Dummy2("abcdef", 98765)
dummy2.extra = null
val config = JSONConfig().apply {
includeNulls = true
}
expect("""{"field1":"abcdef","field2":98765,"extra":null}""") { JSONStringify.stringify(dummy2, config) }
}
@Test fun `should stringify an object of a derived class`() {
val obj = Derived()
obj.field1 = "qwerty"
obj.field2 = 98765
obj.field3 = 0.012
val json = JSONStringify.stringify(obj)
expectJSON(json) {
count(3)
property("field1", "qwerty")
property("field2", 98765)
property("field3", BigDecimal("0.012"))
}
}
@Test fun `should stringify an object using name annotation`() {
val obj = DummyWithNameAnnotation()
obj.field1 = "qwerty"
obj.field2 = 98765
val json = JSONStringify.stringify(obj)
expectJSON(json) {
count(2)
property("field1", "qwerty")
property("fieldX", 98765)
}
}
@Test fun `should stringify an object using parameter name annotation`() {
val obj = DummyWithParamNameAnnotation("abc", 123)
val json = JSONStringify.stringify(obj)
expectJSON(json) {
count(2)
property("field1", "abc")
property("fieldX", 123)
}
}
@Test fun `should stringify an object using custom parameter name annotation`() {
val obj = DummyWithCustomNameAnnotation("abc", 123)
val config = JSONConfig().apply {
addNameAnnotation(CustomName::class, "symbol")
}
val json = JSONStringify.stringify(obj, config)
expectJSON(json) {
count(2)
property("field1", "abc")
property("fieldX", 123)
}
}
@Test fun `should stringify a nested object`() {
val obj1 = Dummy1("asdfg", 987)
val obj3 = Dummy3(obj1, "what?")
val json = JSONStringify.stringify(obj3)
expectJSON(json) {
count(2)
property("text", "what?")
property("dummy1") {
count(2)
property("field1", "asdfg")
property("field2", 987)
}
}
}
@Test fun `should stringify an object with @JSONIgnore`() {
val obj = DummyWithIgnore("alpha", "beta", "gamma")
val json = JSONStringify.stringify(obj)
expectJSON(json) {
count(2)
property("field1", "alpha")
property("field3", "gamma")
}
}
@Test fun `should stringify an object with custom ignore annotation`() {
val obj = DummyWithCustomIgnore("alpha", "beta", "gamma")
val config = JSONConfig().apply {
addIgnoreAnnotation(CustomIgnore::class)
}
val json = JSONStringify.stringify(obj, config)
expectJSON(json) {
count(2)
property("field1", "alpha")
property("field3", "gamma")
}
}
@Test fun `should stringify an object with @JSONIncludeIfNull`() {
val obj = DummyWithIncludeIfNull("alpha", null, "gamma")
val json = JSONStringify.stringify(obj)
expectJSON(json) {
count(3)
property("field1", "alpha")
property("field2", null)
property("field3", "gamma")
}
}
@Test fun `should stringify an object with custom include if null annotation`() {
val obj = DummyWithCustomIncludeIfNull("alpha", null, "gamma")
val config = JSONConfig().apply {
addIncludeIfNullAnnotation(CustomIncludeIfNull::class)
}
val json = JSONStringify.stringify(obj, config)
expectJSON(json) {
count(3)
property("field1", "alpha")
property("field2", null)
property("field3", "gamma")
}
}
@Test fun `should stringify an object with @JSONIncludeAllProperties`() {
val obj = DummyWithIncludeAllProperties("alpha", null, "gamma")
val json = JSONStringify.stringify(obj)
expectJSON(json) {
count(3)
property("field1", "alpha")
property("field2", null)
property("field3", "gamma")
}
}
@Test fun `should stringify an object with custom include all properties annotation`() {
val obj = DummyWithCustomIncludeAllProperties("alpha", null, "gamma")
val config = JSONConfig().apply {
addIncludeAllPropertiesAnnotation(CustomIncludeAllProperties::class)
}
val json = JSONStringify.stringify(obj, config)
expectJSON(json) {
count(3)
property("field1", "alpha")
property("field2", null)
property("field3", "gamma")
}
}
@Test fun `should fail on use of circular reference`() {
val circular1 = Circular1()
val circular2 = Circular2()
circular1.ref = circular2
circular2.ref = circular1
val exception = assertFailsWith<JSONKotlinException> {
JSONStringify.stringify(circular1)
}
expect("Circular reference: field ref in Circular2") { exception.message }
}
@Test fun `should append to existing Appendable`() {
val sb = StringBuilder()
sb.appendJSON(Dummy1("Testing..."))
val json = sb.toString()
expectJSON(json) {
count(2)
property("field1", "Testing...")
property("field2", 999)
}
}
}
<file_sep>/*
* @(#) JSONDeserializerTest.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.collections.ArrayList
import kotlin.collections.LinkedHashMap
import kotlin.reflect.KTypeProjection
import kotlin.reflect.full.createType
import kotlin.reflect.full.starProjectedType
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlin.test.assertTrue
import kotlin.test.expect
import kotlin.test.fail
import kotlin.test.Test
import java.lang.reflect.Type
import java.math.BigDecimal
import java.math.BigInteger
import java.net.URI
import java.net.URL
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.MonthDay
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.Period
import java.time.Year
import java.time.YearMonth
import java.time.ZoneId
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.util.Arrays
import java.util.BitSet
import java.util.Calendar
import java.util.Date
import java.util.LinkedList
import java.util.TimeZone
import java.util.UUID
import java.util.stream.DoubleStream
import java.util.stream.IntStream
import java.util.stream.LongStream
import java.util.stream.Stream
class JSONDeserializerTest {
@Test fun `null input should return null`() {
assertNull(JSONDeserializer.deserialize(String::class, null))
}
@Test fun `null input should cause exception for non-null function`() {
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserializeNonNull(String::class, null) }
expect("Can't deserialize null as String") { e.message }
}
@Test fun `when JSONValue expected it should pass through unchanged`() {
val json = JSONDouble(0.1)
assertSame(json, JSONDeserializer.deserialize(JSONValue::class, json))
assertSame(json, JSONDeserializer.deserialize(JSONDouble::class, json))
val json2 = JSONString("abc")
assertSame(json2, JSONDeserializer.deserialize(JSONValue::class, json2))
assertSame(json2, JSONDeserializer.deserialize(JSONString::class, json2))
}
@Test fun `companion object with fromJSON should use that function`() {
val json = JSONObject().apply {
putValue("dec", "17")
putValue("hex", "11")
}
val expected: DummyFromJSON? = DummyFromJSON(17)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `companion object with multiple fromJSON should use the correct function`() {
val json1 = JSONObject().apply {
putValue("dec", "17")
putValue("hex", "11")
}
val expected1: DummyMultipleFromJSON? = DummyMultipleFromJSON(17)
expect(expected1) { JSONDeserializer.deserialize(json1) }
val json2 = JSONInt(300)
val expected2: DummyMultipleFromJSON? = DummyMultipleFromJSON(300)
expect(expected2) { JSONDeserializer.deserialize(json2) }
val json3 = JSONString("FF")
val expected3: DummyMultipleFromJSON? = DummyMultipleFromJSON(255)
expect(expected3) { JSONDeserializer.deserialize(json3) }
}
@Test fun `JSONString should return string`() {
val json = JSONString("abc")
val expected: String? = "abc"
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `single character JSONString should return character`() {
val json = JSONString("Q")
val expected: Char? = 'Q'
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return character array`() {
val json = JSONString("abcdef")
val expected: CharArray? = arrayOf('a', 'b', 'c', 'd', 'e', 'f').toCharArray()
assertTrue(Arrays.equals(expected, JSONDeserializer.deserialize(json)))
}
@Test fun `JSONString should return array of Char`() {
val json = JSONString("abcdef")
val expected: Array<Char>? = arrayOf('a', 'b', 'c', 'd', 'e', 'f')
assertTrue(Arrays.equals(expected, JSONDeserializer.deserialize(Array<Char>::class, json)))
}
@Test fun `JSONString should return Calendar`() {
val json = JSONString("2019-04-19T15:34:02.234+10:00")
val cal = Calendar.getInstance()
cal.set(2019, 3, 19, 15, 34, 2) // month value is month - 1
cal.set(Calendar.MILLISECOND, 234)
cal.set(Calendar.ZONE_OFFSET, 10 * 60 * 60 * 1000)
assertTrue(calendarEquals(cal, JSONDeserializer.deserialize(json)!!))
}
@Test fun `JSONString should return Date`() {
val json = JSONString("2019-03-10T15:34:02.234+11:00")
val cal = Calendar.getInstance(TimeZone.getTimeZone("GMT"))
cal.set(2019, 2, 10, 15, 34, 2) // month value is month - 1
cal.set(Calendar.MILLISECOND, 234)
cal.set(Calendar.ZONE_OFFSET, 11 * 60 * 60 * 1000)
val expected: Date? = cal.time
expect(expected) { JSONDeserializer.deserialize(json) }
// val json2 = JSONString("2019-03-11")
// cal.clear()
// cal.set(2019, 2, 11, 0, 0, 0)
// cal.set(Calendar.MILLISECOND, 0)
// cal.set(Calendar.ZONE_OFFSET, 0)
// val expected2: Date? = cal.time
// expect(expected2) { JSONDeserializer.deserialize(json2) }
}
@Test fun `JSONString should return java-sql-Date`() {
val json = JSONString("2019-03-10")
val expected: java.sql.Date? = java.sql.Date.valueOf("2019-03-10")
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return java-sql-Time`() {
val json = JSONString("22:45:41")
val expected: java.sql.Time? = java.sql.Time.valueOf("22:45:41")
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return java-sql-Timestamp`() {
val json = JSONString("2019-03-10 22:45:41.5")
val expected: java.sql.Timestamp? = java.sql.Timestamp.valueOf("2019-03-10 22:45:41.5")
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return Instant`() {
val json = JSONString("2019-03-10T15:34:02.234Z")
val cal = Calendar.getInstance()
cal.timeZone = TimeZone.getTimeZone("GMT")
cal.set(2019, 2, 10, 15, 34, 2) // month value is month - 1
cal.set(Calendar.MILLISECOND, 234)
cal.set(Calendar.ZONE_OFFSET, 0)
val expected: Instant? = Instant.ofEpochMilli(cal.timeInMillis)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return LocalDate`() {
val json = JSONString("2019-03-10")
val expected: LocalDate? = LocalDate.of(2019, 3, 10)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return LocalDateTime`() {
val json = JSONString("2019-03-10T16:43:33")
val expected: LocalDateTime? = LocalDateTime.of(2019, 3, 10, 16, 43, 33)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return LocalTime`() {
val json = JSONString("16:43:33")
val expected: LocalTime? = LocalTime.of(16, 43, 33)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return OffsetTime`() {
val json = JSONString("16:46:11.234+10:00")
val expected: OffsetTime? = OffsetTime.of(16, 46, 11, 234000000, ZoneOffset.ofHours(10))
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return OffsetDateTime`() {
val json = JSONString("2019-03-10T16:46:11.234+10:00")
val expected: OffsetDateTime? = OffsetDateTime.of(2019, 3, 10, 16, 46, 11, 234000000, ZoneOffset.ofHours(10))
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return ZonedDateTime`() {
val json = JSONString("2019-01-10T16:46:11.234+11:00[Australia/Sydney]")
val expected: ZonedDateTime? = ZonedDateTime.of(2019, 1, 10, 16, 46, 11, 234000000,
ZoneId.of("Australia/Sydney"))
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return Year`() {
val json = JSONString("2019")
val expected: Year? = Year.of(2019)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return YearMonth`() {
val json = JSONString("2019-03")
val expected: YearMonth? = YearMonth.of(2019, 3)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return MonthDay`() {
val json = JSONString("--03-10")
val expected: MonthDay? = MonthDay.of(3, 10)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return Duration`() {
val json = JSONString("PT2H")
val expected: Duration? = Duration.ofHours(2)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return Period`() {
val json = JSONString("P3M")
val expected: Period? = Period.ofMonths(3)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return UUID`() {
val uuid = "b082b046-ac9b-11eb-8ea7-5fc81989f104"
val json = JSONString(uuid)
val expected: UUID? = UUID.fromString("b082b046-ac9b-11eb-8ea7-5fc81989f104")
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should fail on invalid UUID`() {
val json = JSONString("b082b046-ac9b-11eb-8ea7-5fc81989f1") // 2 bytes too short
assertFailsWith<JSONException> { JSONDeserializer.deserialize<UUID>(json) }.let {
expect("Error deserializing \"b082b046-ac9b-11eb-8ea7-5fc81989f1\" as UUID") { it.message }
}
}
@Test fun `JSONString should return URI`() {
val uriString = "http://pwall.net"
val json = JSONString(uriString)
val expected: URI? = URI(uriString)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return URL`() {
val urlString = "https://pwall.net"
val json = JSONString(urlString)
val expected: URL? = URL(urlString)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONArray should return BitSet`() {
val bitset = BitSet()
bitset.set(2)
bitset.set(7)
val json = JSONArray().apply {
addValue(2)
addValue(7)
}
val expected: BitSet? = bitset
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return enum`() {
val json = JSONString("ALPHA")
val expected: DummyEnum? = DummyEnum.ALPHA
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return BigInteger`() {
val str = "123456789"
val json = JSONString(str)
val expected: BigInteger? = BigInteger(str)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONLong should return BigInteger`() {
val value = 123456789012345678
val json = JSONLong(value)
val expected: BigInteger? = BigInteger.valueOf(value)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONInt should return BigInteger`() {
val value = 12345678
val json = JSONInt(value)
val expected: BigInteger? = BigInteger.valueOf(value.toLong())
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONString should return BigDecimal`() {
val str = "123456789.77777"
val json = JSONString(str)
val expected: BigDecimal? = BigDecimal(str)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONDecimal should return BigDecimal`() {
val str = "123456789.77777"
val json = JSONDecimal(str)
val expected: BigDecimal? = BigDecimal(str)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONDouble should return BigDecimal`() {
val value = 1234.5
val json = JSONDouble(value)
val expected: BigDecimal? = BigDecimal(value)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONInt should return Int`() {
val json = JSONInt(1234)
val expected: Int? = 1234
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONLong should return Long`() {
val json = JSONLong(123456789012345)
val expected: Long? = 123456789012345
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONDouble should return Double`() {
val json = JSONDouble(123.45)
val expected: Double? = 123.45
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONInt should return Short`() {
val json = JSONInt(1234)
val expected: Short? = 1234
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONInt should return Byte`() {
val json = JSONInt(123)
val expected: Byte? = 123
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONArray of boolean should return BooleanArray`() {
val json = JSONArray().apply {
addValue(true)
addValue(false)
addValue(false)
}
val expected = booleanArrayOf(true, false, false)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(BooleanArray::class, json) ?: fail()))
}
@Test fun `JSONArray of boolean should fail if entries not boolean`() {
val json = JSONArray().apply {
addValue(123)
addValue("ABC")
addValue(false)
}
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize(BooleanArray::class, json) }
expect("Can't deserialize 123 as Boolean at /0") { e.message }
}
@Test fun `JSONArray of number should return ByteArray`() {
val json = JSONArray().apply {
addValue(1)
addValue(2)
addValue(3)
}
val expected = byteArrayOf(1, 2, 3)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(ByteArray::class, json) ?: fail()))
}
@Test fun `JSONArray of character should return CharArray`() {
val json = JSONArray().apply {
addValue("a")
addValue("b")
addValue("c")
}
val expected = charArrayOf('a', 'b', 'c')
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(CharArray::class, json) ?: fail()))
}
@Test fun `JSONArray of number should return DoubleArray`() {
val json = JSONArray().apply {
addValue(123)
addValue(0)
addValue(0.012)
}
val expected = doubleArrayOf(123.0, 0.0, 0.012)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(DoubleArray::class, json) ?: fail()))
}
@Test fun `JSONArray of number should return FloatArray`() {
val json = JSONArray().apply {
addValue(123)
addValue(0)
addValue(0.012)
}
val expected = floatArrayOf(123.0F, 0.0F, 0.012F)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(FloatArray::class, json) ?: fail()))
}
@Test fun `JSONArray of number should return IntArray`() {
val json = JSONArray().apply {
addValue(12345)
addValue(2468)
addValue(321321)
}
val expected = intArrayOf(12345, 2468, 321321)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(IntArray::class, json) ?: fail()))
}
@Test fun `JSONArray of number should fail if entries not number`() {
val json = JSONArray().apply {
addValue("12345")
addValue(true)
addValue(321321)
}
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize(IntArray::class, json) }
expect("Can't deserialize \"12345\" as Int at /0") { e.message }
}
@Test fun `JSONArray to IntArray should fail if entries not integer`() {
val json = JSONArray().apply {
addValue(12345)
addValue(0.123)
addValue(321321)
}
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize(IntArray::class, json) }
expect("Can't deserialize 0.123 as Int at /1") { e.message }
}
@Test fun `JSONArray of number should return LongArray`() {
val json = JSONArray().apply {
addValue(123456789123456)
addValue(0)
addValue(321321L)
}
val expected = longArrayOf(123456789123456, 0, 321321)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(LongArray::class, json) ?: fail()))
}
@Test fun `JSONArray of number should return ShortArray`() {
val json = JSONArray().apply {
addValue(1234)
addValue(0)
addValue(321)
}
val expected = shortArrayOf(1234, 0, 321)
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(ShortArray::class, json) ?: fail()))
}
private val stringType = String::class.starProjectedType
private val stringTypeProjection = KTypeProjection.invariant(stringType)
private val intType = Int::class.starProjectedType
private val intTypeProjection = KTypeProjection.invariant(intType)
private val listStringType = List::class.createType(listOf(stringTypeProjection))
private val arrayListStringType = ArrayList::class.createType(listOf(stringTypeProjection))
private val linkedListStringType = LinkedList::class.createType(listOf(stringTypeProjection))
private val setStringType = Set::class.createType(listOf(stringTypeProjection))
private val hashSetStringType = HashSet::class.createType(listOf(stringTypeProjection))
private val linkedHashSetStringType = LinkedHashSet::class.createType(listOf(stringTypeProjection))
private val mapStringIntType = Map::class.createType(listOf(stringTypeProjection, intTypeProjection))
private val linkedHashMapStringIntType = LinkedHashMap::class.createType(listOf(stringTypeProjection,
intTypeProjection))
private val listStrings = listOf("abc", "def")
private val jsonArrayString = JSONArray().addValue("abc").addValue("def")
@Test fun `JSONArray of JSONString should return List of String`() {
expect(listStrings) { JSONDeserializer.deserialize(listStringType, jsonArrayString) }
}
@Test fun `JSONArray of JSONString should return ArrayList of String`() {
expect(ArrayList(listStrings)) { JSONDeserializer.deserialize(arrayListStringType, jsonArrayString) }
}
@Test fun `JSONArray of JSONString should return LinkedList of String`() {
expect(LinkedList(listStrings)) { JSONDeserializer.deserialize(linkedListStringType, jsonArrayString) }
}
@Test fun `JSONArray of JSONString should return Set of String`() {
expect(LinkedHashSet(listStrings)) { JSONDeserializer.deserialize(setStringType, jsonArrayString) }
}
@Test fun `JSONArray of JSONString should reject duplicate`() {
val jsonArrayDuplicate = JSONArray().addValue("abc").addValue("def").addValue("abc")
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize(setStringType, jsonArrayDuplicate) }
expect("Duplicate not allowed at /2") { e.message }
}
@Test fun `JSONArray of JSONString should return HashSet of String`() {
expect(HashSet(listStrings)) { JSONDeserializer.deserialize(hashSetStringType, jsonArrayString) }
}
@Test fun `JSONArray of JSONString should return LinkedHashSet of String`() {
expect(LinkedHashSet(listStrings)) { JSONDeserializer.deserialize(linkedHashSetStringType, jsonArrayString) }
}
private val mapStringInt = mapOf("abc" to 123, "def" to 456, "ghi" to 789)
private val jsonObjectInt = JSONObject().apply {
putValue("abc", 123)
putValue("def", 456)
putValue("ghi", 789)
}
@Test fun `JSONObject should return map of String to Int`() {
expect(mapStringInt) { JSONDeserializer.deserialize(mapStringIntType, jsonObjectInt)}
}
@Test fun `JSONObject should return LinkedHashMap of String to Int`() {
val linkedHashMapStringInt = LinkedHashMap(mapStringInt)
val result = JSONDeserializer.deserialize(linkedHashMapStringIntType, jsonObjectInt)
assertEquals(linkedHashMapStringInt, result)
assertTrue(result is LinkedHashMap<*, *>)
}
@Test fun `JSONObject should return simple data class`() {
val json = JSONObject().apply {
putValue("field1", "Hello")
putValue("field2", 12345)
}
val expected: Dummy1? = Dummy1("Hello", 12345)
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONObject should return simple data class with default parameter`() {
val json = JSONObject().putValue("field1", "Hello")
val expected: Dummy1? = Dummy1("Hello")
expect(expected) { JSONDeserializer.deserialize(json) }
}
@Test fun `JSONObject should return data class with extra values`() {
val json = JSONObject().apply {
putValue("field1", "Hello")
putValue("field2", 12345)
putValue("extra", "XXX")
}
val expected: Dummy2? = Dummy2("Hello", 12345)
expected?.extra = "XXX"
val result = JSONDeserializer.deserialize<Dummy2>(json)
assertEquals(expected, result)
assertEquals("XXX", result?.extra)
}
@Test fun `JSONObject should return nested data class`() {
val json1 = JSONObject().apply {
putValue("field1", "Whoa")
putValue("field2", 98765)
}
val json2 = JSONObject().apply {
put("dummy1", json1)
putValue("text", "special")
}
val expected: Dummy3? = Dummy3(Dummy1("Whoa", 98765), "special")
expect(expected) { JSONDeserializer.deserialize(json2) }
}
@Test fun `JSONObject should return nested data class with list`() {
val json1 = JSONObject().apply {
putValue("field1", "Whoa")
putValue("field2", 98765)
}
val json2 = JSONObject().apply {
putValue("field1", "Hi!")
putValue("field2", 333)
}
val json3 = JSONArray().apply {
add(json1)
add(json2)
}
val json4 = JSONObject().apply {
put("listDummy1", json3)
putValue("text", "special")
}
val expected: Dummy4? = Dummy4(listOf(Dummy1("Whoa", 98765), Dummy1("Hi!", 333)), "special")
expect(expected) { JSONDeserializer.deserialize(json4) }
}
@Test fun `JSONObject should return simple class with properties`() {
val json = JSONObject().apply {
putValue("field1", "qqq")
putValue("field2", 888)
}
val expected = Super()
expected.field1 = "qqq"
expected.field2 = 888
expect(expected) { JSONDeserializer.deserialize(Super::class, json) }
}
@Test fun `JSONObject should return derived class with properties`() {
// also test parsing from String
val str = "{\"field1\":\"qqq\",\"field2\":888,\"field3\":12345.0}"
val expected = Derived()
expected.field1 = "qqq"
expected.field2 = 888
expected.field3 = 12345.0
expect(expected) { JSONAuto.parse(Derived::class, str) }
}
@Test fun `JSONObject should return simple class with properties using name annotation`() {
val json = JSONObject().apply {
putValue("field1", "qqq")
putValue("fieldX", 888)
}
val expected = DummyWithNameAnnotation()
expected.field1 = "qqq"
expected.field2 = 888
expect(expected) { JSONDeserializer.deserialize(DummyWithNameAnnotation::class, json) }
}
@Test fun `JSONObject should return data class using name annotation`() {
val json = JSONObject().apply {
putValue("field1", "qqq")
putValue("fieldX", 888)
}
expect(DummyWithParamNameAnnotation("qqq", 888)) {
JSONDeserializer.deserialize(DummyWithParamNameAnnotation::class, json)
}
}
@Test fun `JSONObject should return data class using custom name annotation`() {
val json = JSONObject().apply {
putValue("field1", "qqq")
putValue("fieldX", 888)
}
val expected = DummyWithCustomNameAnnotation("qqq", 888)
val config = JSONConfig().apply {
addNameAnnotation(CustomName::class, "symbol")
}
expect(expected) { JSONDeserializer.deserialize(DummyWithCustomNameAnnotation::class, json, config) }
}
private val pairStringStringType = Pair::class.createType(listOf(stringTypeProjection, stringTypeProjection))
private val pairStringIntType = Pair::class.createType(listOf(stringTypeProjection, intTypeProjection))
private val tripleStringStringStringType = Triple::class.createType(listOf(stringTypeProjection,
stringTypeProjection, stringTypeProjection))
private val tripleStringIntStringType = Triple::class.createType(listOf(stringTypeProjection,
intTypeProjection, stringTypeProjection))
@Test fun `JSONArray should return Pair`() {
val json = JSONArray().apply {
addValue("abc")
addValue("def")
}
expect("abc" to "def") { JSONDeserializer.deserialize(pairStringStringType, json) }
}
@Test fun `JSONArray should return Heterogenous Pair`() {
val json = JSONArray().apply {
addValue("abc")
addValue(88)
}
expect("abc" to 88) { JSONDeserializer.deserialize(pairStringIntType, json) }
}
@Test fun `JSONArray should return Triple`() {
val json = JSONArray().apply {
addValue("abc")
addValue("def")
addValue("xyz")
}
expect(Triple("abc", "def", "xyz")) { JSONDeserializer.deserialize(tripleStringStringStringType, json) }
}
@Test fun `JSONArray should return Heterogenous Triple`() {
val json = JSONArray().apply {
addValue("abc")
addValue(66)
addValue("xyz")
}
expect(Triple("abc", 66, "xyz")) { JSONDeserializer.deserialize(tripleStringIntStringType, json) }
}
@Test fun `null should return null for nullable String`() {
val json: JSONValue? = null
assertNull(JSONDeserializer.deserialize(String::class.createType(emptyList(), true), json))
}
@Test fun `null should fail for non-nullable String`() {
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize(stringType, null) }
expect("Can't deserialize null as String") { e.message }
}
@Test fun `JSONObject should deserialize to object`() {
val json = JSONObject().putValue("field1", "abc")
expect(DummyObject) { JSONDeserializer.deserialize(DummyObject::class, json) }
}
@Test fun `class with constant val should deserialize correctly`() {
val json = JSONObject().putValue("field8", "blert")
expect(DummyWithVal()) { JSONDeserializer.deserialize(DummyWithVal::class, json) }
}
@Test fun `java class should deserialize correctly`() {
val json = JSONObject().apply {
putValue("field1", 1234)
putValue("field2", "Hello!")
}
expect(JavaClass1(1234, "Hello!")) { JSONDeserializer.deserialize(JavaClass1::class, json) }
}
@Test fun `deserialize List using Java Type should work correctly`() {
val json = JSONArray().apply {
add(JSONObject().apply {
putValue("field1", 567)
putValue("field2", "abcdef")
})
add(JSONObject().apply {
putValue("field1", 9999)
putValue("field2", "qwerty")
})
}
val type: Type = JavaClass2::class.java.getField("field1").genericType
expect(listOf(JavaClass1(567, "abcdef"), JavaClass1(9999, "qwerty"))) {
JSONDeserializer.deserialize(type, json)
}
}
@Test fun `JSONArray should deserialize into List derived type`() {
val json = JSONArray().apply {
addValue("2019-10-06")
addValue("2019-10-05")
}
expect(DummyList(listOf(LocalDate.of(2019, 10, 6), LocalDate.of(2019, 10, 5)))) {
JSONDeserializer.deserialize(DummyList::class, json)
}
}
@Test fun `JSONObject should deserialize into Map derived type`() {
val json = JSONObject().apply {
putValue("aaa", "2019-10-06")
putValue("bbb", "2019-10-05")
}
val expected = DummyMap(emptyMap()).apply {
put("aaa", LocalDate.of(2019, 10, 6))
put("bbb", LocalDate.of(2019, 10, 5))
}
expect(expected) { JSONDeserializer.deserialize(DummyMap::class, json) }
}
@Suppress("UNCHECKED_CAST")
@Test fun `JSONArray should deserialize into Sequence`() {
val json = JSONArray().apply {
addValue("abcde")
addValue("fghij")
}
val expected = sequenceOf("abcde", "fghij")
val stringSequenceType = Sequence::class.createType(listOf(stringTypeProjection))
assertTrue(sequenceEquals(expected, JSONDeserializer.deserialize(stringSequenceType, json) as Sequence<String>))
}
@Suppress("UNCHECKED_CAST")
@Test fun `JSONArray should deserialize into Array`() {
val json = JSONArray().apply {
addValue("abcde")
addValue("fghij")
}
val expected = arrayOf("abcde", "fghij")
val stringArrayType = Array<String>::class.createType(listOf(stringTypeProjection))
assertTrue(expected.contentEquals(JSONDeserializer.deserialize(stringArrayType, json) as Array<String>))
}
@Suppress("UNCHECKED_CAST")
@Test fun `JSONArray should deserialize into nested Array`() {
val list1 = JSONArray().apply {
addValue("qwerty")
addValue("asdfgh")
addValue("zxcvbn")
}
val list2 = JSONArray().apply {
addValue("abcde")
addValue("fghij")
}
val json = JSONArray().apply {
add(list1)
add(list2)
}
val array1 = arrayOf("qwerty", "asdfgh", "zxcvbn")
val array2 = arrayOf("abcde", "fghij")
val expected = arrayOf(array1, array2)
val stringArrayType = Array<String>::class.createType(listOf(stringTypeProjection))
val stringArrayArrayType = Array<String>::class.createType(listOf(KTypeProjection.invariant(stringArrayType)))
val actual = JSONDeserializer.deserialize(stringArrayArrayType, json) as Array<Array<String>>
assertTrue(expected.contentDeepEquals(actual))
}
@Test fun `JSONString should deserialize to Any`() {
val json = JSONString("Hello!")
expect("Hello!") { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONBoolean should deserialize to Any`() {
val json1 = JSONBoolean.TRUE
val result1 = JSONDeserializer.deserializeAny(json1)
assertTrue(result1 is Boolean && result1)
val json2 = JSONBoolean.FALSE
val result2 = JSONDeserializer.deserializeAny(json2)
assertTrue(result2 is Boolean && !result2)
}
@Test fun `JSONInt should deserialize to Any`() {
val json = JSONInt(123456)
expect(123456) { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONLong should deserialize to Any`() {
val json = JSONLong(1234567890123456L)
expect(1234567890123456L) { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONFloat should deserialize to Any`() {
val json = JSONFloat(0.12345F)
expect(0.12345F) { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONDouble should deserialize to Any`() {
val json = JSONDouble(0.123456789)
expect(0.123456789) { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONZero should deserialize to Any`() {
val json = JSONZero()
expect(0) { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONArray should deserialize to Any`() {
val json = JSONArray().apply {
addValue("abcde")
addValue("fghij")
}
expect(listOf("abcde", "fghij")) { JSONDeserializer.deserializeAny(json) }
}
@Test fun `JSONObject should deserialize to Any`() {
val json = JSONObject().apply {
putValue("aaa", 1234)
putValue("ccc", 9999)
putValue("bbb", 5678)
putValue("abc", 8888)
}
val result = JSONDeserializer.deserializeAny(json)
// check that the result is a map in the correct order
if (result is Map<*, *>) {
val iterator = result.keys.iterator()
expect(true) { iterator.hasNext() }
iterator.next().let {
expect("aaa") { it }
expect(1234) { result[it] }
}
expect(true) { iterator.hasNext() }
iterator.next().let {
expect("ccc") { it }
expect(9999) { result[it] }
}
expect(true) { iterator.hasNext() }
iterator.next().let {
expect("bbb") { it }
expect(5678) { result[it] }
}
expect(true) { iterator.hasNext() }
iterator.next().let {
expect("abc") { it }
expect(8888) { result[it] }
}
expect(false) { iterator.hasNext() }
}
else
fail("Not a Map - $result")
}
@Test fun `sealed class should deserialize to correct subclass`() {
val json = JSONObject().apply {
putValue("class", "Const")
putValue("number", 2.0)
}
expect(Const(2.0)) { JSONDeserializer.deserialize<Expr>(json) }
}
@Test fun `sealed class should deserialize to correct object subclass`() {
val json = JSONObject().apply {
putValue("class", "NotANumber")
}
expect(NotANumber) { JSONDeserializer.deserialize<Expr>(json) }
}
@Test fun `sealed class should deserialize with custom discriminator`() {
val config = JSONConfig().apply {
sealedClassDiscriminator = "?"
}
val json = JSONObject().apply {
putValue("?", "Const")
putValue("number", 2.0)
}
expect(Const(2.0)) { JSONDeserializer.deserialize<Expr>(json, config) }
}
@Test fun `class should ignore additional fields when allowExtra set in config`() {
val config = JSONConfig().apply {
allowExtra = true
}
val json = JSONObject().apply {
putValue("field1", "Hello")
putValue("field2", 123)
putValue("extra", "allow")
}
expect(Dummy1("Hello", 123)) { JSONDeserializer.deserialize<Dummy1>(json, config) }
}
@Test fun `class annotated with @JSONAllowExtra should ignore additional fields`() {
val json = JSONObject().apply {
putValue("field1", "Hello")
putValue("field2", 123)
putValue("extra", "allow")
}
expect(DummyWithAllowExtra("Hello", 123)) { JSONDeserializer.deserialize<DummyWithAllowExtra>(json) }
}
@Test fun `class annotated with custom allow extra should ignore additional fields`() {
val config = JSONConfig().apply {
addAllowExtraPropertiesAnnotation(CustomAllowExtraProperties::class)
}
val json = JSONObject().apply {
putValue("field1", "Hi")
putValue("field2", 123)
putValue("extra", "allow")
}
expect(DummyWithCustomAllowExtra("Hi", 123)) {
JSONDeserializer.deserialize<DummyWithCustomAllowExtra>(json, config)
}
}
@Test fun `field annotated with @JSONIgnore should be ignored on deserialization`() {
val json = JSONObject().apply {
putValue("field1", "one")
putValue("field2", "two")
putValue("field3", "three")
}
expect(DummyWithIgnore(field1 = "one", field3 = "three")) {
JSONDeserializer.deserialize<DummyWithIgnore>(json)
}
}
@Test fun `field annotated with custom ignore annotation should be ignored on deserialization`() {
val config = JSONConfig().apply {
addIgnoreAnnotation(CustomIgnore::class)
}
val json = JSONObject().apply {
putValue("field1", "one")
putValue("field2", "two")
putValue("field3", "three")
}
expect(DummyWithCustomIgnore(field1 = "one", field3 = "three")) {
JSONDeserializer.deserialize<DummyWithCustomIgnore>(json, config)
}
}
@Test fun `should deserialize missing members as null where allowed`() {
val json = JSONObject().apply {
putValue("field2", 123)
}
expect(Dummy5(null, 123)) { JSONDeserializer.deserialize<Dummy5>(json) }
}
@Test fun `should deserialize custom parameterised type`() {
val json = JSONObject().apply {
put("lines", JSONArray(JSONString("abc"), JSONString("def")))
}
val expected = TestPage<String>(lines = listOf("abc", "def"))
expect(expected) { JSONDeserializer.deserialize<TestPage<String>>(json) }
}
@Test fun `should deserialize nested custom parameterised type`() {
val json1 = JSONObject().apply {
put("lines", JSONArray(JSONString("abc"), JSONString("def")))
}
val json2 = JSONArray(json1, JSONString("xyz"))
val expected = TestPage<String>(lines = listOf("abc", "def")) to "xyz"
expect(expected) { JSONDeserializer.deserialize<Pair<TestPage<String>, String>>(json2) }
}
@Test fun `should deserialize differently nested custom parameterised type`() {
val json = JSONObject().apply {
put("lines", JSONArray(JSONArray(JSONString("abc"), JSONString("ABC")),
JSONArray(JSONString("def"), JSONString("DEF"))))
}
val expected = TestPage<Pair<String, String>>(lines = listOf("abc" to "ABC", "def" to "DEF"))
expect(expected) { JSONDeserializer.deserialize<TestPage<Pair<String, String>>>(json) }
}
@Test fun `should deserialize complex custom parameterised type`() {
val obj1 = JSONObject().apply {
putValue("field1", "abc")
putValue("field2", 123)
}
val obj2 = JSONObject().apply {
putValue("field1", "def")
putValue("field2", 456)
}
val json = JSONObject().apply {
put("lines", JSONArray(obj1, obj2))
}
val expected = TestPage<Dummy1>(lines = listOf(Dummy1("abc", 123), Dummy1("def", 456)))
expect(expected) { JSONDeserializer.deserialize<TestPage<Dummy1>>(json) }
}
@Test fun `should deserialize another form of custom parameterised type`() {
val obj1 = JSONObject().apply {
putValue("field1", "abc")
putValue("field2", 123)
}
val json = JSONObject().apply {
putValue("description", "testing")
put("data", obj1)
}
val dummy1 = Dummy1("abc", 123)
val expected = TestDataHolder("testing", dummy1)
expect(expected) { JSONDeserializer.deserialize<TestDataHolder<Dummy1>>(json) }
}
@Test fun `should deserialize yet another form of custom parameterised type`() {
val json = JSONObject().apply {
put("lineLists", JSONArray(JSONArray(JSONString("lineA1"), JSONString("lineA2")),
JSONArray(JSONString("lineB1"), JSONString("lineB2"))))
}
val expected = TestPage2<String>(lineLists = listOf(listOf("lineA1", "lineA2"), listOf("lineB1", "lineB2")))
expect(expected) { JSONDeserializer.deserialize<TestPage2<String>>(json)}
}
@Test fun `should deserialize Java Stream`() {
val json = JSONArray(JSONString("abc"), JSONString("def"))
val result: Stream<String> = JSONDeserializer.deserialize(json) ?: fail("result was null")
val iterator = result.iterator()
expect(true) { iterator.hasNext() }
expect("abc") { iterator.next() }
expect(true) { iterator.hasNext() }
expect("def") { iterator.next() }
expect(false) { iterator.hasNext() }
}
@Test fun `should deserialize Java IntStream`() {
val json = JSONArray(JSONInt(2345), JSONInt(6789))
val result: IntStream = JSONDeserializer.deserialize(json) ?: fail("result was null")
val iterator = result.iterator()
expect(true) { iterator.hasNext() }
expect(2345) { iterator.next() }
expect(true) { iterator.hasNext() }
expect(6789) { iterator.next() }
expect(false) { iterator.hasNext() }
}
@Test fun `should deserialize Java LongStream`() {
val json = JSONArray(JSONLong(1234567812345678), JSONLong(9876543298765432))
val result: LongStream = JSONDeserializer.deserialize(json) ?: fail("result was null")
val iterator = result.iterator()
expect(true) { iterator.hasNext() }
expect(1234567812345678) { iterator.next() }
expect(true) { iterator.hasNext() }
expect(9876543298765432) { iterator.next() }
expect(false) { iterator.hasNext() }
}
@Test fun `should deserialize Java DoubleStream`() {
val json = JSONArray(JSONDouble(1234.5), JSONDouble(1e40))
val result: DoubleStream = JSONDeserializer.deserialize(json) ?: fail("result was null")
val iterator = result.iterator()
expect(true) { iterator.hasNext() }
expect(1234.5) { iterator.next() }
expect(true) { iterator.hasNext() }
expect(1e40) { iterator.next() }
expect(false) { iterator.hasNext() }
}
@Test fun `should give error message with pointer`() {
val json = JSON.parse("""{"field1":"abc","field2":"def"}""")
val e1 = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize<Dummy1>(json) }
expect("Can't deserialize \"def\" as Int at /field2") { e1.message }
val e2 = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize<List<Dummy1>>(JSONArray(json)) }
expect("Can't deserialize \"def\" as Int at /0/field2") { e2.message }
}
@Test fun `should give expanded error message with pointer`() {
val json = JSON.parse("""{"field2":1}""")
val e1 = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize<Dummy1>(json) }
expect("Can't create Dummy1; missing: field1") { e1.message }
val e2 = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize<List<Dummy1>>(JSONArray(json)) }
expect("Can't create Dummy1; missing: field1 at /0") { e2.message }
}
@Test fun `should give expanded error message for multiple constructors`() {
val json = JSON.parse("""[{"aaa":"X"},{"bbb":1},{"ccc":true,"ddd":0}]""")
val e = assertFailsWith<JSONKotlinException> { JSONDeserializer.deserialize<List<MultiConstructor>>(json) }
expect("Can't locate constructor for MultiConstructor; properties: ccc, ddd at /2") { e.message }
}
@Test fun `should use type projection upperBounds`() {
val json = JSON.parse("""{"expr":{"class":"Const","number":20.0}}""")
val expr = JSONDeserializer.deserialize<SealedClassContainer<*>>(json)?.expr
assertTrue(expr is Const)
expect(20.0) { expr.number }
}
private fun <T> sequenceEquals(seq1: Sequence<T>, seq2: Sequence<T>) = seq1.toList() == seq2.toList()
private val calendarFields = arrayOf(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY,
Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND, Calendar.ZONE_OFFSET)
private fun calendarEquals(a: Calendar, b: Calendar): Boolean {
for (field in calendarFields)
if (a.get(field) != b.get(field))
return false
return true
}
data class TestPage<T>(val header: String? = null, val lines: List<T>)
data class TestDataHolder<T>(val description: String, val data: T)
data class TestPage2<T>(val header: String? = null, val lineLists: List<List<T>>)
data class SealedClassContainer<T: Expr>(val expr: T)
}
<file_sep>/*
* @(#) JSONDeserializer.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KCallable
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KMutableProperty
import kotlin.reflect.KParameter
import kotlin.reflect.KProperty
import kotlin.reflect.KType
import kotlin.reflect.KTypeParameter
import kotlin.reflect.KTypeProjection
import kotlin.reflect.KVariance
import kotlin.reflect.full.companionObjectInstance
import kotlin.reflect.full.createType
import kotlin.reflect.full.isSubclassOf
import kotlin.reflect.full.isSuperclassOf
import kotlin.reflect.full.starProjectedType
import kotlin.reflect.full.staticFunctions
import kotlin.reflect.jvm.isAccessible
import kotlin.reflect.typeOf
import java.lang.reflect.Type
import java.math.BigDecimal
import java.math.BigInteger
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.MonthDay
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.Period
import java.time.Year
import java.time.YearMonth
import java.time.ZonedDateTime
import java.util.BitSet
import java.util.Calendar
import java.util.Date
import java.util.LinkedList
import java.util.UUID
import java.util.stream.DoubleStream
import java.util.stream.IntStream
import java.util.stream.LongStream
import java.util.stream.Stream
import net.pwall.json.JSONDeserializerFunctions.createUUID
import net.pwall.json.JSONDeserializerFunctions.findFromJSON
import net.pwall.json.JSONDeserializerFunctions.findParameterName
import net.pwall.json.JSONDeserializerFunctions.hasSingleParameter
import net.pwall.json.JSONKotlinException.Companion.fail
import net.pwall.json.pointer.JSONPointer
import net.pwall.util.ISO8601Date
/**
* JSON Auto deserialize for Kotlin.
*
* @author <NAME>
*/
@OptIn(ExperimentalStdlibApi::class)
object JSONDeserializer {
private val anyQType = Any::class.createType(emptyList(), true)
/**
* Deserialize a parsed [JSONValue] to a specified [KType].
*
* @param resultType the target type
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param config an optional [JSONConfig]
* @return the converted object
*/
fun deserialize(resultType: KType, json: JSONValue?, config: JSONConfig = JSONConfig.defaultConfig): Any? =
deserialize(resultType, json, JSONPointer.root, config)
/**
* Deserialize a parsed [JSONValue] to a specified [KType] (specifying [JSONPointer]).
*
* @param resultType the target type
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param pointer the [JSONPointer]
* @param config an optional [JSONConfig]
* @return the converted object
*/
fun deserialize(resultType: KType, json: JSONValue?, pointer: JSONPointer,
config: JSONConfig = JSONConfig.defaultConfig): Any? {
config.findFromJSONMapping(resultType)?.let {
try {
return it(json)
}
catch (e: Exception) {
fail("Error in custom fromJSON", pointer, e)
}
}
if (json == null) {
if (!resultType.isMarkedNullable)
fail("Can't deserialize null as ${resultType.simpleName}", pointer)
return null
}
val classifier = resultType.classifier as? KClass<*> ?:
fail("Can't deserialize ${resultType.simpleName}", pointer)
return deserialize(resultType, classifier, resultType.arguments, json, pointer, config)
}
/**
* Deserialize a parsed [JSONValue] to a specified [KClass].
*
* @param resultClass the target class
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param config an optional [JSONConfig]
* @param T the target class
* @return the converted object
*/
@Suppress("UNCHECKED_CAST")
fun <T: Any> deserialize(resultClass: KClass<T>, json: JSONValue?,
config: JSONConfig = JSONConfig.defaultConfig): T? {
config.findFromJSONMapping(resultClass)?.let { return it(json) as T }
if (json == null)
return null
return deserialize(resultClass.starProjectedType, resultClass, emptyList(), json, JSONPointer.root, config)
}
/**
* Deserialize a parsed [JSONValue] to a specified [KClass], where the result may not be `null`.
*
* @param resultClass the target class
* @param json the parsed JSON, as a [JSONValue]
* @param config an optional [JSONConfig]
* @param T the target class
* @return the converted object
*/
fun <T: Any> deserializeNonNull(resultClass: KClass<T>, json: JSONValue?,
config: JSONConfig = JSONConfig.defaultConfig): T =
deserializeNonNull(resultClass, json, JSONPointer.root, config)
/**
* Deserialize a parsed [JSONValue] to a specified [KClass], where the result may not be `null` (specifying
* [JSONPointer]).
*
* @param resultClass the target class
* @param json the parsed JSON, as a [JSONValue]
* @param pointer the [JSONPointer]
* @param config an optional [JSONConfig]
* @param T the target class
* @return the converted object
*/
@Suppress("UNCHECKED_CAST")
fun <T: Any> deserializeNonNull(resultClass: KClass<T>, json: JSONValue?, pointer: JSONPointer,
config: JSONConfig = JSONConfig.defaultConfig): T {
config.findFromJSONMapping(resultClass)?.let { return it(json) as T }
if (json == null)
fail("Can't deserialize null as ${resultClass.simpleName}")
return deserialize(resultClass.starProjectedType, resultClass, emptyList(), json, pointer, config)
}
/**
* Deserialize a parsed [JSONValue] to a specified Java [Type].
*
* @param javaType the target type
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param config an optional [JSONConfig]
* @return the converted object
*/
fun deserialize(javaType: Type, json: JSONValue?, config: JSONConfig = JSONConfig.defaultConfig): Any? =
deserialize(javaType.toKType(nullable = true), json, config)
/**
* Deserialize a parsed [JSONValue] to an unspecified([Any]) type. Strings will be converted to `String`, numbers
* to `Int`, `Long` or `BigDecimal`, booleans to `Boolean`, arrays to `ArrayList<Any?>` and objects to
* `ListMap<String, Any?>` (a simple implementation of `Map` that preserves order).
*
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param config an optional [JSONConfig] (not used, accepted for compatibility with other functions)
* @return the converted object
*/
fun deserializeAny(json: JSONValue?, @Suppress("UNUSED_PARAMETER") config: JSONConfig? = null): Any? =
json?.toSimpleValue()
/**
* Deserialize a parsed [JSONValue] to the inferred [KType].
*
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param config an optional [JSONConfig]
* @param T the target class
* @return the converted object
*/
inline fun <reified T: Any> deserialize(json: JSONValue?, config: JSONConfig = JSONConfig.defaultConfig): T? =
deserialize(typeOf<T>(), json, config) as T?
/**
* Deserialize a parsed [JSONValue] to a parameterized [KClass], with the specified [KTypeProjection]s.
*
* @param resultType the target [KType]
* @param resultClass the target class
* @param types the [KTypeProjection]s
* @param json the parsed JSON, as a [JSONValue] (or `null`)
* @param pointer a [JSONPointer] to the current location
* @param config a [JSONConfig]
* @param T the target class
* @return the converted object
*/
@Suppress("UNCHECKED_CAST")
private fun <T: Any> deserialize(resultType: KType, resultClass: KClass<T>, types: List<KTypeProjection>,
json: JSONValue, pointer: JSONPointer, config: JSONConfig): T {
// check for JSONValue
if (resultClass.isSubclassOf(JSONValue::class) && resultClass.isSuperclassOf(json::class))
return json as T
// does the target class companion object have a "fromJSON()" method?
try {
findFromJSON(resultClass, json::class)?.let {
return it.call(resultClass.companionObjectInstance, json) as T
}
}
catch (e: Exception) {
fail("Error in custom in-class fromJSON - ${resultClass.simpleName}", pointer, e)
}
when (json) {
is JSONBoolean -> {
if (resultClass.isSuperclassOf(Boolean::class))
return json.booleanValue() as T
}
is JSONString -> return deserializeString(resultClass, json.toString(), pointer)
is JSONNumberValue -> {
when (resultClass) {
Int::class -> if (json is JSONInt || json is JSONZero)
return json.toInt() as T
Long::class -> if (json is JSONLong || json is JSONInt || json is JSONZero)
return json.toLong() as T
Double::class -> return json.toDouble() as T
Float::class -> return json.toFloat() as T
Short::class -> if (json is JSONInt || json is JSONZero)
return json.toShort() as T
Byte::class -> if (json is JSONInt || json is JSONZero)
return json.toByte() as T
BigInteger::class -> if (json is JSONLong || json is JSONInt || json is JSONZero)
return json.toBigInteger() as T
BigDecimal::class -> return json.toBigDecimal() as T
}
if (resultClass.isSuperclassOf(Number::class)) {
when (json) {
is JSONInt,
is JSONZero -> return json.toInt() as T
is JSONLong -> return json.toLong() as T
is JSONFloat -> return json.toFloat() as T
is JSONDouble -> return json.toDouble() as T
is JSONDecimal -> return json.toBigDecimal() as T
}
}
fail("Can't deserialize $json as ${resultClass.simpleName}", pointer)
}
is JSONSequence<*> -> return deserializeArray(resultType, resultClass, types, json, pointer, config)
is JSONMapping<*> -> return deserializeObject(resultType, resultClass, types, json, pointer, config)
}
fail("Can't deserialize ${resultClass.simpleName}", pointer)
}
@Suppress("UNCHECKED_CAST")
private fun <T: Any> deserializeString(resultClass: KClass<T>, str: String, pointer: JSONPointer): T {
try {
if (resultClass.isSuperclassOf(String::class))
return str as T
when (resultClass) {
Char::class -> {
if (str.length != 1)
fail("Character must be string of length 1", pointer)
return str[0] as T
}
CharArray::class -> return str.toCharArray() as T
Array<Char>::class -> return Array(str.length) { i -> str[i] } as T
java.sql.Date::class -> return java.sql.Date.valueOf(str) as T
java.sql.Time::class -> return java.sql.Time.valueOf(str) as T
java.sql.Timestamp::class -> return java.sql.Timestamp.valueOf(str) as T
Calendar::class -> return ISO8601Date.decode(str) as T
Date::class -> return ISO8601Date.decode(str).time as T
Instant::class -> return Instant.parse(str) as T
LocalDate::class -> return LocalDate.parse(str) as T
LocalDateTime::class -> return LocalDateTime.parse(str) as T
LocalTime::class -> return LocalTime.parse(str) as T
OffsetTime::class -> return OffsetTime.parse(str) as T
OffsetDateTime::class -> return OffsetDateTime.parse(str) as T
ZonedDateTime::class -> return ZonedDateTime.parse(str) as T
Year::class -> return Year.parse(str) as T
YearMonth::class -> return YearMonth.parse(str) as T
MonthDay::class -> return MonthDay.parse(str) as T
Duration::class -> return Duration.parse(str) as T
Period::class -> return Period.parse(str) as T
UUID::class -> return createUUID(str) as T
}
// is the target class an enum?
if (resultClass.isSubclassOf(Enum::class))
resultClass.staticFunctions.find { it.name == "valueOf" }?.let { return it.call(str) as T }
// does the target class have a public constructor that takes String? (e.g. StringBuilder, URL, ... )
resultClass.constructors.find { it.hasSingleParameter(String::class) }?.apply { return call(str) }
}
catch (e: JSONException) {
throw e
}
catch (e: Exception) {
fail("Error deserializing \"$str\" as ${resultClass.simpleName}", pointer, e)
}
fail("Can't deserialize \"$str\" as ${resultClass.simpleName}", pointer)
}
@Suppress("UNCHECKED_CAST", "IMPLICIT_CAST_TO_ANY")
private fun <T: Any> deserializeArray(resultType: KType, resultClass: KClass<T>, types: List<KTypeProjection>,
json: JSONSequence<*>, pointer: JSONPointer, config: JSONConfig): T {
return when (resultClass) {
BooleanArray::class -> BooleanArray(json.size) {
i -> deserializeNonNull(Boolean::class, json[i], pointer.child(i))
}
ByteArray::class -> ByteArray(json.size) {
i -> deserializeNonNull(Byte::class, json[i], pointer.child(i))
}
CharArray::class -> CharArray(json.size) {
i -> deserializeNonNull(Char::class, json[i], pointer.child(i))
}
DoubleArray::class -> DoubleArray(json.size) {
i -> deserializeNonNull(Double::class, json[i], pointer.child(i))
}
FloatArray::class -> FloatArray(json.size) {
i -> deserializeNonNull(Float::class, json[i], pointer.child(i))
}
IntArray::class -> IntArray(json.size) {
i -> deserializeNonNull(Int::class, json[i], pointer.child(i))
}
LongArray::class -> LongArray(json.size) {
i -> deserializeNonNull(Long::class, json[i], pointer.child(i))
}
ShortArray::class -> ShortArray(json.size) {
i -> deserializeNonNull(Short::class, json[i], pointer.child(i))
}
Collection::class,
MutableCollection::class,
List::class,
MutableList::class,
Iterable::class,
Any::class,
ArrayList::class-> ArrayList<Any?>(json.size).fillFromJSON(resultType, json, getTypeParam(types), pointer,
config)
LinkedList::class -> LinkedList<Any?>().fillFromJSON(resultType, json, getTypeParam(types), pointer, config)
Stream::class -> {
val list = ArrayList<Any?>(json.size).fillFromJSON(resultType, json, getTypeParam(types), pointer,
config)
list.stream()
}
IntStream::class -> {
val intArray = IntArray(json.size) {
i -> deserializeNonNull(Int::class, json[i], pointer.child(i), config)
}
IntStream.of(*intArray)
}
LongStream::class -> {
val longArray = LongArray(json.size) {
i -> deserializeNonNull(Long::class, json[i], pointer.child(i), config)
}
LongStream.of(*longArray)
}
DoubleStream::class -> {
val doubleArray = DoubleArray(json.size) {
i -> deserializeNonNull(Double::class, json[i], pointer.child(i), config)
}
DoubleStream.of(*doubleArray)
}
Set::class,
MutableSet::class,
LinkedHashSet::class -> LinkedHashSet<Any?>(json.size).fillFromJSON(resultType, json, getTypeParam(types),
pointer, config)
HashSet::class -> HashSet<Any?>(json.size).fillFromJSON(resultType, json, getTypeParam(types), pointer,
config)
Sequence::class -> json.mapIndexed { i, value ->
deserializeNested(resultType, getTypeParam(types), value, pointer.child(i), config)
}.asSequence()
Pair::class -> {
val result0 = deserializeNested(resultType, getTypeParam(types, 0), json[0], pointer.child(0), config)
val result1 = deserializeNested(resultType, getTypeParam(types, 1), json[1], pointer.child(1), config)
result0 to result1
}
Triple::class -> {
val result0 = deserializeNested(resultType, getTypeParam(types, 0), json[0], pointer.child(0), config)
val result1 = deserializeNested(resultType, getTypeParam(types, 1), json[1], pointer.child(1), config)
val result2 = deserializeNested(resultType, getTypeParam(types, 2), json[2], pointer.child(2), config)
Triple(result0, result1, result2)
}
BitSet::class -> {
BitSet().apply {
json.mapIndexed { i, value ->
if (value !is JSONInt)
fail("Can't deserialize BitSet; array member not int", pointer.child(i))
set(value.value)
}
}
}
else -> {
if (resultClass.java.isArray) {
val type = getTypeParam(types)
val itemClass = type.classifier as? KClass<Any> ?: fail("Can't determine array type", pointer)
newArray(itemClass, json.size).apply {
for (i in json.indices)
this[i] = deserializeNested(resultType, type, json[i], pointer.child(i), config)
}
}
else {
// If the target class has a constructor that takes a single List parameter, create a List and
// invoke that constructor. This should catch the less frequently used List classes.
resultClass.constructors.find { it.hasSingleParameter(List::class) }?.run {
val type = getTypeParam(parameters[0].type.arguments)
call(ArrayList<Any?>(json.size).fillFromJSON(resultType, json, type, pointer, config))
} ?: fail("Can't deserialize array as ${resultClass.simpleName}", pointer)
}
}
} as T
}
@Suppress("UNCHECKED_CAST")
private fun <T: Any> newArray(itemClass: KClass<T>, size: Int): Array<T?> =
// there appears to be no way of creating an array of dynamic type in Kotlin
// other than to use Java reflection
java.lang.reflect.Array.newInstance(itemClass.java, size) as Array<T?>
private fun getTypeParam(types: List<KTypeProjection>, n: Int = 0): KType = types.getOrNull(n)?.type ?: anyQType
private fun MutableCollection<Any?>.fillFromJSON(resultType: KType, json: JSONSequence<*>, type: KType,
pointer: JSONPointer, config: JSONConfig): MutableCollection<Any?> {
// using for rather than map to avoid creation of intermediate List
for (i in json.indices) {
if (!add(deserializeNested(resultType, type, json[i], pointer.child(i), config)))
fail("Duplicate not allowed", pointer.child(i))
}
return this
}
@Suppress("UNCHECKED_CAST")
private fun <T: Any> deserializeObject(resultType: KType, resultClass: KClass<T>, types: List<KTypeProjection>,
json: JSONMapping<*>, pointer: JSONPointer, config: JSONConfig): T {
if (resultClass.isSubclassOf(Map::class)) {
when (resultClass) {
HashMap::class -> return deserializeMap(resultType, HashMap(json.size), types, json, pointer,
config) as T
Map::class,
MutableMap::class,
LinkedHashMap::class -> return deserializeMap(resultType, LinkedHashMap(json.size), types, json,
pointer, config) as T
}
}
// If the target class has a constructor that takes a single Map parameter, create a Map and invoke that
// constructor. This should catch the less frequently used Map classes.
resultClass.constructors.find { it.hasSingleParameter(Map::class) }?.apply {
return call(deserializeMap(resultType, LinkedHashMap(json.size), parameters[0].type.arguments, json,
pointer, config))
}
val jsonCopy = JSONMapping<JSONValue>(json)
if (resultClass.isSealed) {
val subClassName = (jsonCopy.remove(config.sealedClassDiscriminator) as? JSONString)?.toString() ?:
fail("No class name for sealed class", pointer)
val subClass = resultClass.sealedSubclasses.find { it.simpleName == subClassName } ?:
fail("Can't find named subclass for sealed class", pointer)
return deserializeObject(subClass.createType(types, nullable = resultType.isMarkedNullable), subClass,
types, jsonCopy, pointer, config)
}
resultClass.objectInstance?.let {
return setRemainingFields(resultType, resultClass, it, json, pointer, config)
}
if (resultClass.isSuperclassOf(Map::class))
return deserializeMap(resultType, LinkedHashMap(json.size), types, json, pointer, config) as T
findBestConstructor(resultClass.constructors, json, config)?.let { constructor ->
val argMap = HashMap<KParameter, Any?>()
for (parameter in constructor.parameters) {
val paramName = findParameterName(parameter, config)
if (!config.hasIgnoreAnnotation(parameter.annotations)) {
if (jsonCopy.containsKey(paramName)) {
argMap[parameter] = deserializeNested(resultType, parameter.type, jsonCopy[paramName],
pointer.child(paramName), config)
}
else {
if (!parameter.isOptional) {
if (parameter.type.isMarkedNullable)
argMap[parameter] = null
else
fail("Can't create $resultClass - missing property $paramName", pointer)
}
}
}
jsonCopy.remove(paramName)
}
return setRemainingFields(resultType, resultClass, constructor.callBy(argMap), jsonCopy, pointer, config)
}
// there is no matching constructor
if (resultClass.constructors.size == 1) {
val missing = resultClass.constructors.first().parameters.filter {
!config.hasIgnoreAnnotation(it.annotations) && !it.isOptional && !it.type.isMarkedNullable
}.map {
findParameterName(it, config)
}.filter {
!jsonCopy.containsKey(it)
}
fail("Can't create ${resultClass.simpleName}; missing: ${missing.displayList()}", pointer)
}
val propMessage = when {
jsonCopy.isNotEmpty() -> jsonCopy.keys.displayList()
else -> "none"
}
fail("Can't locate constructor for ${resultClass.simpleName}; properties: $propMessage", pointer)
}
private fun Collection<Any?>.displayList(): String = joinToString(", ")
private fun deserializeMap(resultType: KType, map: MutableMap<Any, Any?>, types: List<KTypeProjection>,
json: JSONMapping<*>, pointer: JSONPointer, config: JSONConfig): MutableMap<Any, Any?> {
val keyClass = getTypeParam(types, 0).classifier as? KClass<*> ?:
fail("Key type can not be determined for Map", pointer)
val valueType = getTypeParam(types, 1)
for (entry in json.entries) {
map[deserializeString(keyClass, entry.key, pointer)] = deserializeNested(resultType, valueType, entry.value,
pointer.child(entry.key), config)
}
return map
}
private fun <T: Any> setRemainingFields(resultType: KType, resultClass: KClass<T>, instance: T,
json: Map<String, JSONValue?>, pointer: JSONPointer, config: JSONConfig): T {
for (entry in json) { // JSONObject fields not used in constructor
val member = findField(resultClass.members, entry.key, config)
if (member != null) {
if (!config.hasIgnoreAnnotation(member.annotations)) {
val value = deserializeNested(resultType, member.returnType, entry.value, pointer.child(entry.key),
config)
if (member is KMutableProperty<*>) {
val wasAccessible = member.isAccessible
member.isAccessible = true
try {
member.setter.call(instance, value)
}
catch (e: Exception) {
fail("Error setting property ${entry.key} in ${resultClass.simpleName}", pointer, e)
}
finally {
member.isAccessible = wasAccessible
}
}
else {
if (member.getter.call(instance) != value)
fail("Can't set property ${entry.key} in ${resultClass.simpleName}", pointer)
}
}
}
else {
if (!(config.allowExtra || config.hasAllowExtraPropertiesAnnotation(resultClass.annotations)))
fail("Can't find property ${entry.key} in ${resultClass.simpleName}", pointer)
}
}
return instance
}
private fun findField(members: Collection<KCallable<*>>, name: String, config: JSONConfig): KProperty<*>? {
for (member in members)
if (member is KProperty<*> && (config.findNameFromAnnotation(member.annotations) ?: member.name) == name)
return member
return null
}
private fun <T: Any> findBestConstructor(constructors: Collection<KFunction<T>>, json: JSONMapping<*>,
config: JSONConfig): KFunction<T>? {
var result: KFunction<T>? = null
var best = -1
for (constructor in constructors) {
val parameters = constructor.parameters
if (parameters.any { findParameterName(it, config) == null || it.kind != KParameter.Kind.VALUE })
continue
val n = findMatchingParameters(parameters, json, config)
if (n > best) {
result = constructor
best = n
}
}
return result
}
private fun findMatchingParameters(parameters: List<KParameter>, json: JSONMapping<*>, config: JSONConfig): Int {
var n = 0
for (parameter in parameters) {
if (json.containsKey(findParameterName(parameter, config)))
n++
else {
if (!(parameter.isOptional || parameter.type.isMarkedNullable))
return -1
}
}
return n
}
private fun deserializeNested(enclosingType: KType, resultType: KType, json: JSONValue?, pointer: JSONPointer,
config: JSONConfig): Any? =
deserialize(resultType.applyTypeParameters(enclosingType, pointer), json, pointer, config)
private fun KType.applyTypeParameters(enclosingType: KType, pointer: JSONPointer): KType {
(classifier as? KTypeParameter)?.let { typeParameter ->
val enclosingClass = enclosingType.classifierAsClass(this, pointer)
val index = enclosingClass.typeParameters.indexOfFirst { it.name == typeParameter.name }
return enclosingType.arguments.getOrNull(index)?.type ?:
enclosingClass.typeParameters.getOrNull(index)?.upperBounds?.singleOrNull() ?:
fail("Can't create $simpleName - no type information for ${typeParameter.name}", pointer)
}
if (arguments.isEmpty())
return this
return classifierAsClass(this, pointer).createType(arguments.map { (variance, type) ->
if (variance == null || type == null)
KTypeProjection.STAR
else
type.applyTypeParameters(enclosingType, pointer).let {
when (variance) {
KVariance.INVARIANT -> KTypeProjection.invariant(it)
KVariance.IN -> KTypeProjection.contravariant(it)
KVariance.OUT -> KTypeProjection.covariant(it)
}
}
}, isMarkedNullable, annotations)
}
private fun KType.classifierAsClass(target: KType, pointer: JSONPointer): KClass<*> =
classifier as? KClass<*> ?: fail("Can't create $target - insufficient type information", pointer)
private val KType.simpleName
get() = (classifier as? KClass<*>)?.simpleName ?: toString()
}
<file_sep>/*
* @(#) JSONSerializerFunctions.kt
*
* json-kotlin Kotlin JSON Auto Serialize/deserialize
* Copyright (c) 2019, 2020, 2022 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package net.pwall.json
import kotlin.reflect.KClass
import kotlin.reflect.KFunction
import kotlin.reflect.KParameter
import kotlin.reflect.KType
import kotlin.reflect.full.isSubclassOf
import java.math.BigDecimal
import java.math.BigInteger
import java.net.URI
import java.net.URL
import java.time.Duration
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.time.MonthDay
import java.time.OffsetDateTime
import java.time.OffsetTime
import java.time.Period
import java.time.Year
import java.time.YearMonth
import java.time.ZonedDateTime
import java.util.Calendar
import java.util.LinkedList
import java.util.UUID
import net.pwall.util.ISO8601Date
/**
* Utility functions for JSON Serialization. These functions are not expected to be of use outside the `json-kotlin`
* family of projects.
*
* @author <NAME>
*/
object JSONSerializerFunctions {
private val toJsonCache = HashMap<KClass<*>, KFunction<JSONValue>?>()
private val toStringClasses = setOf(java.sql.Date::class, java.sql.Time::class, java.sql.Timestamp::class,
Instant::class, LocalDate::class, LocalDateTime::class, LocalTime::class, OffsetTime::class,
OffsetDateTime::class, ZonedDateTime::class, Year::class, YearMonth::class, MonthDay::class,
Duration::class, Period::class, URI::class, URL::class, UUID::class)
private val uncachedClasses = setOf(Any::class, String::class, Boolean::class, Int::class, Long::class, Byte::class,
Short::class, Double::class, Float::class, BigDecimal::class, BigInteger::class, ArrayList::class,
LinkedList::class, HashMap::class, LinkedHashMap::class, HashSet::class)
/**
* Is the class best represented by a string of the `toString()` result?
*
* @receiver the class of the object
* @return `true` if the object should be output as a string
*/
fun KClass<*>.isToStringClass() = this in toStringClasses
fun KClass<*>.findToJSON(): KFunction<JSONValue>? {
if (this in uncachedClasses || this in toStringClasses)
return null
if (toJsonCache.containsKey(this))
return toJsonCache[this]
try {
for (function in members) {
if (function is KFunction<*> &&
function.name == "toJSON" &&
function.parameters.size == 1 &&
function.parameters[0].kind == KParameter.Kind.INSTANCE &&
function.returnType.isJSONValue())
@Suppress("UNCHECKED_CAST")
return (function as KFunction<JSONValue>).apply { toJsonCache[this@findToJSON] = this }
}
}
catch (_: Throwable) {
}
toJsonCache[this] = null
return null
}
private fun KType.isJSONValue(): Boolean {
classifier?.let { if (it is KClass<*>) return it.isSubclassOf(JSONValue::class) }
return false
}
fun KClass<*>.isSealedSubclass(): Boolean {
for (supertype in supertypes) {
(supertype.classifier as? KClass<*>)?.let {
if (it.isSealed)
return true
if (it != Any::class)
if (it.isSealedSubclass())
return true
}
}
return false
}
fun Calendar.formatISO8601() : String = ISO8601Date.toString(this, true,
ISO8601Date.YEAR_MASK or ISO8601Date.MONTH_MASK or ISO8601Date.DAY_OF_MONTH_MASK or
ISO8601Date.HOUR_OF_DAY_MASK or ISO8601Date.MINUTE_MASK or ISO8601Date.SECOND_MASK or
ISO8601Date.MILLISECOND_MASK or ISO8601Date.ZONE_OFFSET_MASK)
}
<file_sep><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.pwall.json</groupId>
<artifactId>json-kotlin</artifactId>
<version>4.8</version>
<name>JSON serialization and deserialization for Kotlin</name>
<description>Kotlin classes to perform auto-serialization and deserialization.</description>
<packaging>jar</packaging>
<url>https://github.com/pwall567/json-kotlin</url>
<parent>
<groupId>net.pwall.maven</groupId>
<artifactId>maven-kotlin</artifactId>
<version>5.1</version>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<licenses>
<license>
<name>The MIT License (MIT)</name>
<url>http://opensource.org/licenses/MIT</url>
<distribution>repo</distribution>
</license>
</licenses>
<scm>
<connection>scm:git:git://github.com/pwall567/json-kotlin.git</connection>
<url>https://github.com/pwall567/json-kotlin</url>
</scm>
<developers>
<developer>
<id><EMAIL></id>
<name><NAME></name>
<email><EMAIL></email>
<url>https://pwall.net</url>
<roles>
<role>architect</role>
<role>developer</role>
</roles>
<timezone>Australia/Sydney</timezone>
</developer>
</developers>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<name>Maven Central</name>
<url>https://repo1.maven.org/maven2/</url>
</pluginRepository>
</pluginRepositories>
<dependencies>
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>json-kotlin-annotations</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>json-pointer</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>json-validation</artifactId>
<version>1.5</version>
</dependency>
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>jsonutil</artifactId>
<version>5.1</version>
</dependency>
<dependency>
<groupId>net.pwall.util</groupId>
<artifactId>javautil</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-stdlib-jdk8</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-reflect</artifactId>
</dependency>
<dependency>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-test-junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>json-kotlin-test-classes</artifactId>
<version>1.8</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>net.pwall.json</groupId>
<artifactId>json-kotlin-test</artifactId>
<version>1.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<sourceDirectory>src/main/kotlin</sourceDirectory>
<testSourceDirectory>src/test/kotlin</testSourceDirectory>
<plugins>
<plugin>
<groupId>org.jetbrains.kotlin</groupId>
<artifactId>kotlin-maven-plugin</artifactId>
<executions>
<execution>
<id>compile-kotlin</id>
<phase>process-sources</phase>
<goals>
<goal>compile</goal>
</goals>
</execution>
<execution>
<id>test-compile-kotlin</id>
<phase>test-compile</phase>
<goals>
<goal>test-compile</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<executions>
<execution>
<id>compile-java</id>
<phase>compile</phase>
</execution>
<execution>
<id>test-compile-java</id>
<phase>test-compile</phase>
</execution>
</executions>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
</configuration>
</plugin>
<plugin>
<groupId>org.jetbrains.dokka</groupId>
<artifactId>dokka-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
| 272df647a323e4154878773d0ee0d77e890aa35d | [
"Markdown",
"Java",
"Maven POM",
"Kotlin"
] | 27 | Markdown | pwall567/json-kotlin | 96b43936c9c02577026d3028c83c82c68387388a | e5c9abdc1eec7d6b6f7a923b02caf699992629d7 | |
refs/heads/master | <repo_name>ih4t3youall/scripts<file_sep>/mavenCreate
#!/bin/bash
if [ $# -eq 0 ]
then
mvn archetype:generate -DgroupId=test -DartifactId=test -Dpackage=test \
-Dname="parent top level" \
-Dversion="1.0" \
-DarchetypeGroupId=org.apache.maven.archetypes \
-DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 \
-DinteractiveMode=false
fi
if [ $# -eq 1 ]
then
echo "se creara un proyecto con el paquete ar.com.${1}"
mvn archetype:generate -DgroupId="${1}" -DartifactId="${1}" -Dpackage=ar.com."${1}" -Dname="parent top level" -Dversion="1.0" -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
fi
if [ $# -eq 2 ]
then
echo "se creara un proyecto con el paquete ${1}.${2}"
mvn archetype:generate -DgroupId="${1}" -DartifactId="${2}" -Dpackage=${1} -Dname="parent top level" -Dversion="1.0" -DarchetypeGroupId=org.apache.maven.archetypes -DarchetypeArtifactId=maven-archetype-quickstart -DarchetypeVersion=1.4 -DinteractiveMode=false
fi
| 7f88dc6c98ff701793ccf2a424a27e26e6e515a2 | [
"Shell"
] | 1 | Shell | ih4t3youall/scripts | 6b520a9b32f0c6475f6555f5396871f99f36e087 | b319b79e57ee7f2fa35c9b9dd4343a6b51b49538 | |
refs/heads/main | <repo_name>masaywar/MP_ARCT<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Logic Gates/Scripts/UIC_LG_GateEnd.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_LG_GateEnd : UIC_LG_Gate
{
protected override void Awake()
{
base.Awake();
_image = GetComponent<Image>();
_text = transform.GetChild(0).GetComponentInChildren<Text>();
}
void Update()
{
if (outValue == 1)
{
Color outColor = Color.green;
ColorUtility.TryParseHtmlString("#6AFF6A", out outColor);
_image.color = outColor;
_text.text = "on";
}
else if (outValue == 0)
{
Color outColor = Color.green;
ColorUtility.TryParseHtmlString("#636363", out outColor);
_image.color = outColor;
_text.text = "off";
}
else
{
_image.color = new Color(1, 1, 1);
_text.text = "--";
}
}
Image _image;
Text _text;
public override void Solve()
{
GetInputs();
if (inputs.Count > 0)
{
outValue = inputs[0];
}
else
{
outValue = -1;
return;
}
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_Pointer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;
//[ExecuteInEditMode]
public class UIC_Pointer : MonoBehaviour
{
UIC_Manager _uicManager;
public KeyCode clickKey;
public KeyCode secondaryKey;
Image _image;
Canvas _pointerCanvas;
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
EventSystem m_EventSystem;
public Sprite iconDefault;
public Sprite iconHold;
Vector3 _initialMousePos;
List<I_UIC_Object> _orderedObjectsList = new List<I_UIC_Object>();
// v1.3 - corrected pointer position for canvas render mode overlay and camera
public Vector3 PointerPosition
{
get
{
return Input.mousePosition;
}
}
public UnityEvent e_OnPointerDownFirst;
public UnityEvent e_OnPointerDownLast;
public UnityEvent e_OnDragFirst;
public UnityEvent e_OnDragLast;
public UnityEvent e_OnPointerUpFirst;
public UnityEvent e_OnPointerUpLast;
// OBS.: event First and Last means that it is called prior or after all the actions on the event
void OnDrawGizmos()
{
#if UNITY_EDITOR
if (!Application.isPlaying)
{
UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
UnityEditor.SceneView.RepaintAll();
}
#endif
}
void OnValidate()
{
Init();
Awake();
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
}
void Start()
{
e_OnPointerDownFirst = e_OnPointerDownFirst ?? new UnityEvent();
e_OnPointerDownLast = e_OnPointerDownLast ?? new UnityEvent();
e_OnDragFirst = e_OnDragFirst ?? new UnityEvent();
e_OnDragLast = e_OnDragLast ?? new UnityEvent();
e_OnPointerUpFirst = e_OnPointerUpFirst ?? new UnityEvent();
e_OnPointerUpLast = e_OnPointerUpLast ?? new UnityEvent();
Cursor.visible = false;
FollowMouse();
Init();
m_Raycaster = FindObjectOfType<GraphicRaycaster>();
m_EventSystem = FindObjectOfType<EventSystem>();
}
public void Init()
{
_image = _image ? _image : GetComponent<Image>() ? GetComponent<Image>() : gameObject.AddComponent<Image>();
_image.raycastTarget = false;
_pointerCanvas = _pointerCanvas ? _pointerCanvas : GetComponent<Canvas>() ? GetComponent<Canvas>() : gameObject.AddComponent<Canvas>();
_pointerCanvas.overrideSorting = true;
_pointerCanvas.sortingOrder = 999; // pointer on top of everything makes dragged entity being also on top of everithing
}
void Update()
{
FollowMouse();
if (Input.GetKeyDown(clickKey))
{
OnPointerDown();
}
if (Input.GetKey(clickKey))
{
if (_initialMousePos != transform.position)
OnDrag();
}
if (Input.GetKeyUp(clickKey))
{
OnPointerUp();
}
}
private void OnDisable()
{
e_OnPointerDownFirst.RemoveAllListeners();
e_OnPointerDownLast.RemoveAllListeners();
e_OnDragFirst.RemoveAllListeners();
e_OnDragLast.RemoveAllListeners();
e_OnPointerUpFirst.RemoveAllListeners();
e_OnPointerUpLast.RemoveAllListeners();
}
void FollowMouse()
{
Camera mainCamera = _uicManager.mainCamera;
if (_uicManager.CanvasRenderMode == RenderMode.ScreenSpaceOverlay)
{
transform.position = PointerPosition;
}
else if (_uicManager.CanvasRenderMode == RenderMode.ScreenSpaceCamera)
{
var screenPoint = PointerPosition;
screenPoint.z = _uicManager.transform.position.z - mainCamera.transform.position.z; //distance of the plane from the camera
transform.position = mainCamera.ScreenToWorldPoint(screenPoint);
}
// v1.5 - set pointer on the world space canvas
else if (_uicManager.CanvasRenderMode == RenderMode.WorldSpace)
{
var screenPoint = PointerPosition;
screenPoint.z = _uicManager.transform.position.z - mainCamera.transform.position.z; //distance of the plane from the camera
transform.position = mainCamera.ScreenToWorldPoint(screenPoint);
}
}
public void OnPointerDown()
{
e_OnPointerDownFirst.Invoke();
_image.sprite = iconHold;
SelectCloserUIObject();
UIC_ContextMenu.UpdateContextMenu();
_initialMousePos = transform.position;
e_OnPointerDownLast.Invoke();
}
public void OnDrag()
{
e_OnDragFirst.Invoke();
if (_uicManager.clickedUIObject is I_UIC_Draggable)
(_uicManager.clickedUIObject as I_UIC_Draggable).OnDrag();
if (_uicManager.clickedUIObject is UIC_Entity)
{
foreach (I_UIC_Selectable obj in _uicManager.selectedUIObjectsList)
{
if (obj is UIC_Entity)
{
(obj as I_UIC_Draggable).OnDrag();
}
}
}
e_OnDragLast.Invoke();
}
public void OnPointerUp()
{
e_OnPointerUpFirst.Invoke();
_image.sprite = iconDefault;
if (_uicManager.clickedUIObject is I_UIC_Clickable)
(_uicManager.clickedUIObject as I_UIC_Clickable).OnPointerUp();
foreach (I_UIC_Object uiObject in _uicManager.selectedUIObjectsList)
{
if (uiObject is I_UIC_Clickable)
(uiObject as I_UIC_Clickable).OnPointerUp();
}
e_OnPointerUpLast.Invoke();
}
public void UnselectAllUIObjects()
{
if (!Input.GetKey(secondaryKey))
{
for (int i = _uicManager.selectedUIObjectsList.Count - 1; i >= 0; i--)
{
_uicManager.selectedUIObjectsList[i].Unselect();
}
}
}
[System.Obsolete]
public List<RaycastResult> RaycastUI()
{
// v2.0 - by using more than one canvases, raycast system needs to know search the objects in every graphicRaycaster
List<RaycastResult> results = new List<RaycastResult>();
m_PointerEventData = new PointerEventData(m_EventSystem);
m_PointerEventData.position = PointerPosition;
List<RaycastResult> resultsLocal = new List<RaycastResult>();
// you can cache this array for performance
GraphicRaycaster[] m_RaycasterArray = FindObjectsOfType<GraphicRaycaster>();
foreach (GraphicRaycaster gr in m_RaycasterArray)
{
gr.Raycast(m_PointerEventData, resultsLocal);
results.AddRange(resultsLocal);
}
return results;
}
// v2.0 - fix: wrong raycaster found when using more than one canvas
public List<RaycastResult> RaycastUIAll()
{
List<RaycastResult> results = new List<RaycastResult>();
m_PointerEventData = new PointerEventData(m_EventSystem);
m_PointerEventData.position = PointerPosition;
List<RaycastResult> resultsLocal = new List<RaycastResult>();
// if the GraphicRaycasters are fixed, its possible to cache this array for performance
GraphicRaycaster[] m_RaycasterArray = FindObjectsOfType<GraphicRaycaster>();
foreach (GraphicRaycaster gr in m_RaycasterArray)
{
gr.Raycast(m_PointerEventData, resultsLocal);
results.AddRange(resultsLocal);
}
return results;
}
private static int SortByPriority(I_UIC_Object o1, I_UIC_Object o2)
{
return o2.Priority.CompareTo(o1.Priority);
}
public List<I_UIC_Object> ReorderFoundObjectsToPriority(List<I_UIC_Object> objectsList)
{
objectsList.Sort(SortByPriority);
return objectsList;
}
public List<I_UIC_Object> OrderedObjectsUnderPointer()
{
List<I_UIC_Object> orderedObjects = new List<I_UIC_Object>();
List<RaycastResult> results = RaycastUIAll();
I_UIC_Object uiObject = null;
foreach (RaycastResult result in results)
{
uiObject = result.gameObject.GetComponent<I_UIC_Object>();
if (uiObject != null)
{
if (!(uiObject is I_UIC_Clickable) || !(uiObject as I_UIC_Clickable).DisableClick)
orderedObjects.Add(uiObject);
}
}
// v1.5 - find closest connection based on the world space
if (_uicManager.CanvasRenderMode != RenderMode.WorldSpace)
{
uiObject = _uicManager.FindClosestConnectionToPosition(PointerPosition, 15);
}
else
{
uiObject = _uicManager.FindClosestConnectionToPosition(UIC_Utility.WorldToScreenPointInCanvas(transform.position, _uicManager), 15);
}
if (uiObject != null)
if (!(uiObject as I_UIC_Clickable).DisableClick)
orderedObjects.Add(uiObject);
orderedObjects.Sort(SortByPriority);
return orderedObjects;
}
public I_UIC_Object FindObjectCloserToPointer()
{
_orderedObjectsList = OrderedObjectsUnderPointer();
if (_orderedObjectsList.Count > 0)
{
if (!(_orderedObjectsList[0] is I_UIC_ContextItem))
UnselectAllUIObjects();
return _orderedObjectsList[0];
}
else
{
UnselectAllUIObjects();
return null;
}
}
public void SelectCloserUIObject()
{
_uicManager.clickedUIObject = FindObjectCloserToPointer();
if (_uicManager.clickedUIObject is I_UIC_Clickable)
{
(_uicManager.clickedUIObject as I_UIC_Clickable).OnPointerDown();
}
}
// v2.0 - method to find closest node by distance made obsolete
[System.Obsolete("Obsolete, use RaycastClosestNodeOfOppositPolarity instead.")]
public static UIC_Node FindClosestNodeOfOppositPolarity(Vector2 position, float maxDistance, UIC_Node draggedNode, UIC_Manager uicManager)
{
float minDist = Mathf.Infinity;
UIC_Node closestNode = null;
foreach (UIC_Entity entity in uicManager.EntityList)
{
if ((entity == draggedNode.entity && entity.enableSelfConnection) || entity != draggedNode.entity)
{
foreach (UIC_Node node in entity.nodeList)
{
if (draggedNode != node && node.haveSpots && draggedNode.haveSpots)
{
if (node.polarityType != draggedNode.polarityType || node.polarityType == UIC_Node.PolarityTypeEnum._all)
{
float distance = Vector2.Distance(position, node.transform.position);
if (distance < minDist && distance <= maxDistance / uicManager.uiLineRenderer.rectTransform.localScale.x)
{
closestNode = node;
minDist = distance;
}
}
}
}
}
}
return closestNode;
}
// v2.0 - new method to find node using raycast from pointer
public UIC_Node RaycastClosestNodeOfOppositPolarity(UIC_Node draggedNode)
{
UIC_Node closestNode = null;
List<RaycastResult> results = _uicManager.pointer.RaycastUIAll();
I_UIC_Object uiObject = null;
foreach (RaycastResult result in results)
{
uiObject = result.gameObject.GetComponent<I_UIC_Object>();
if (uiObject != null)
{
if (!(uiObject is I_UIC_Clickable) || !(uiObject as I_UIC_Clickable).DisableClick)
if (uiObject is UIC_Node)
{
UIC_Node node = (uiObject as UIC_Node);
if (draggedNode != node && node.haveSpots && draggedNode.haveSpots)
if ((node.entity == draggedNode.entity && node.entity.enableSelfConnection) || node.entity != draggedNode.entity)
if (node.polarityType != draggedNode.polarityType || node.polarityType == UIC_Node.PolarityTypeEnum._all)
{
return node;
}
}
}
}
return closestNode;
}
}
<file_sep>/MP_ARCT/Assets/Scripts/BlockCompiler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockCompiler : MonoBehaviour
{
public void CompileBlocks(Block[] blocks)
{
foreach(var block in blocks)
{
#if UNITY_EDITOR
block.TestAction();
#endif
}
}
public void CompileBlock(Block block)
{
#if UNITY_EDITOR
block.TestAction();
#endif
block.BlockAction();
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Logic Gates/Scripts/UIC_LG_GatesManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// v1.4 - Logic Gates scene added
// this scene uses a really simple solve method just as inspiration on using the asset. It is possible to use a more complex solver and expand the project.
// gates manager class responsible for calling the solve method of each gate and manage connections
public class UIC_LG_GatesManager : MonoBehaviour
{
public UIC_Manager uicManager;
void Start()
{
// add listener for pointer event
uicManager.pointer.e_OnPointerUpFirst.AddListener(
delegate
{
CheckAndUpdateNodeConnections();
});
}
void Update()
{
foreach (UIC_Entity entity in uicManager.EntityList)
{
UIC_LG_Gate gate = entity.GetComponent<UIC_LG_Gate>();
gate.Solve();
gate.UpdateConnections();
}
}
void CheckAndUpdateNodeConnections()
{
UIC_Node clickedNode = uicManager.GetClickedObjectOfType<UIC_Node>();
if (clickedNode)
{
UIC_Node foundNode = clickedNode.lastFoundNode;
if (foundNode)
{
UIC_Connection outConn = clickedNode.connectionsList.Count > 0 ? clickedNode.connectionsList[0] : null;
UIC_Connection inConn = foundNode.connectionsList.Count > 0 ? foundNode.connectionsList[0] : null;
if (outConn != null)
{
outConn.Remove();
}
if (inConn != null)
{
inConn.Remove();
}
}
}
}
}
<file_sep>/MP_ARCT/Assets/Scripts/Base/ExtensionMethods.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;
public static class ExtensionMethods
{
public static void ForEach<T>(this IEnumerable<T> source, System.Action<T> action)
{
foreach (var e in source)
action(e);
}
public static List<T> ToList<T>(this IEnumerable<T> source)
{
return source.ToList();
}
public static IEnumerable<T> ToArray<T>(this IEnumerable<T> source)
{
return source.ToArray();
}
public static IEnumerable<T> SubArray<T>(this IEnumerable<T> source, int start, int count)
{
return source.Skip(start).Take(count);
}
public static T GetTop<T>(this T[] array)
{
return array[array.Length - 1];
}
public static T Top<T>(this List<T> list)
{
return list[list.Count - 1];
}
public static IEnumerator DoWaitForSeconds(float time, System.Action action)
{
yield return new WaitForSeconds(time);
action();
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_Utility.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public static class UIC_Utility
{
// adapted from http://csharphelper.com/blog/2016/09/find-the-shortest-distance-between-a-point-and-a-line-segment-in-c/
public static float FindDistanceToSegment(Vector2 pt, Vector2 p1, Vector2 p2)
{
Vector2 closest;
float dx = p2.x - p1.x;
float dy = p2.y - p1.y;
if ((dx == 0) && (dy == 0))
{
// It's a point not a line segment.
closest = p1;
dx = pt.x - p1.x;
dy = pt.y - p1.y;
return Mathf.Sqrt(dx * dx + dy * dy);
}
// Calculate the t that minimizes the distance.
float t = ((pt.x - p1.x) * dx + (pt.y - p1.y) * dy) /
(dx * dx + dy * dy);
// See if this represents one of the segment's
// end points or a point in the middle.
if (t < 0)
{
closest = new Vector2(p1.x, p1.y);
dx = pt.x - p1.x;
dy = pt.y - p1.y;
}
else if (t > 1)
{
closest = new Vector2(p2.x, p2.y);
dx = pt.x - p2.x;
dy = pt.y - p2.y;
}
else
{
closest = new Vector2(p1.x + t * dx, p1.y + t * dy);
dx = pt.x - closest.x;
dy = pt.y - closest.y;
}
return Mathf.Sqrt(dx * dx + dy * dy);
}
// v1.2 - method DistanceToSpline made obsolete due to missing detection in some cases, changed to DistanceToConnection
[Obsolete("Method obsolete, use DistanceToConnection instead")]
public static float DistanceToSpline(UISpline spline, Vector3 point, int steps)
{
float minDist = Mathf.Infinity;
for (int i = 0; i <= steps; i++)
{
Vector3 curvePoint = spline.GetPoint(spline.controlPoints[0], spline.controlPoints[1], spline.controlPoints[2],
spline.controlPoints[3], (float)i / (float)steps);
float distance = Vector3.Distance(point, curvePoint);
if (distance < minDist)
minDist = distance;
}
return minDist;
}
// v1.2 - new precise method used to find distance from pointer to connection
public static float DistanceToConnectino(UIC_Connection conn, Vector3 point, float maxDistance)
{
List<Vector2> connPoints = conn.line.points;
int connectionPointsCount = connPoints.Count;
float minDist = Mathf.Infinity;
for (int i = 1; i < connectionPointsCount; i++)
{
float distance = UIC_Utility.FindDistanceToSegment(point, connPoints[i - 1], connPoints[i]);
if (distance < minDist && distance <= maxDistance)
{
minDist = distance;
}
}
return minDist;
}
// adapted from https://www.geeksforgeeks.org/check-if-two-given-line-segments-intersect/
//---
// Given three colinear points p, q, r, the function checks if
// point q lies on line segment 'pr'
static bool PointIsOnSegment(Vector2 p, Vector2 q, Vector2 r)
{
if (q.x <= Mathf.Max(p.x, r.x) && q.x >= Mathf.Min(p.x, r.x) &&
q.y <= Mathf.Max(p.y, r.y) && q.y >= Mathf.Min(p.y, r.y))
return true;
return false;
}
// To find orientation of ordered triplet (p, q, r).
// The function returns following values
// 0 --> p, q and r are colinear
// 1 --> Clockwise
// 2 --> Counterclockwise
static int LineOrientation(Vector2 p, Vector2 q, Vector2 r)
{
// See https://www.geeksforgeeks.org/orientation-3-ordered-points/
// for details of below formula.
float val = (q.y - p.y) * (r.x - q.x) -
(q.x - p.x) * (r.y - q.y);
if (val == 0) return 0; // colinear
return (val > 0) ? 1 : 2; // clock or counterclock wise
}
// The main function that returns true if line segment 'p1q1'
// and 'p2q2' intersect.
public static bool LinesDoIntersect(Vector2 p1, Vector2 q1, Vector2 p2, Vector2 q2)
{
// Find the four orientations needed for general and
// special cases
int o1 = LineOrientation(p1, q1, p2);
int o2 = LineOrientation(p1, q1, q2);
int o3 = LineOrientation(p2, q2, p1);
int o4 = LineOrientation(p2, q2, q1);
// General case
if (o1 != o2 && o3 != o4)
return true;
// Special Cases
// p1, q1 and p2 are colinear and p2 lies on segment p1q1
if (o1 == 0 && PointIsOnSegment(p1, p2, q1)) return true;
// p1, q1 and q2 are colinear and q2 lies on segment p1q1
if (o2 == 0 && PointIsOnSegment(p1, q2, q1)) return true;
// p2, q2 and p1 are colinear and p1 lies on segment p2q2
if (o3 == 0 && PointIsOnSegment(p2, p1, q2)) return true;
// p2, q2 and q1 are colinear and q1 lies on segment p2q2
if (o4 == 0 && PointIsOnSegment(p2, q1, q2)) return true;
return false; // Doesn't fall in any of the above cases
}
//---
public static bool ConnectionsIntersect(UIC_Connection conn1, UIC_Connection conn2)
{
bool intersect = false;
if (conn1 != conn2)
{
List<Vector2> conn1Points = conn1.line.points;
List<Vector2> conn2Points = conn2.line.points;
int conn1PointsCount = conn1Points.Count;
int conn2PointsCount = conn2Points.Count;
for (int i = 1; i < conn1PointsCount; i++)
{
for (int j = 1; j < conn2PointsCount; j++)
{
Vector2 p1 = conn1Points[i - 1];
Vector2 q1 = conn1Points[i];
Vector2 p2 = conn2Points[j - 1];
Vector2 q2 = conn2Points[j];
intersect = UIC_Utility.LinesDoIntersect(p1, q1, p2, q2);
if (intersect)
break;
}
if (intersect)
break;
}
}
return intersect;
}
public static bool ConnectionIntersectRect(UIC_Connection conn1, RectTransform rt)
{
int intersectCount = 0;
List<Vector2> conn1Points = conn1.line.points;
int conn1PointsCount = conn1Points.Count;
for (int i = 1; i < conn1PointsCount; i++)
{
Vector2 p1 = conn1Points[i - 1];
Vector2 q1 = conn1Points[i];
Vector3[] v = new Vector3[4];
rt.GetWorldCorners(v);
intersectCount = 0;
for (int j = 1; j <= 4; j++)
{
bool intersect = false;
int k = j;
Vector2 p2 = v[k - 1];
if (j == 4)
{
k = 0;
}
Vector2 q2 = v[k];
intersect = UIC_Utility.LinesDoIntersect(p1, q1, p2, q2);
if (intersect)
intersectCount++;
if (intersectCount >= 2)
break;
}
if (intersectCount >= 2)
break;
}
return intersectCount >= 2 ? true : false;
}
// v2.0 - added local manager to parameters
// v1.5 - transformation to world space
public static Vector3 WorldToScreenPointInCanvas(Vector3 point, UIC_Manager uicManager)
{
Camera mainCamera = uicManager.mainCamera;
RectTransform canvasRect = uicManager.canvasRectTransform;
// v2.1 - Corrected lines position when LineRenderer is offset for Canvas World Space
Vector3 uicManagerOffset = mainCamera.WorldToScreenPoint(uicManager.transform.position);
Vector3 uicLineRendererOffset = mainCamera.WorldToScreenPoint(uicManager.uiLineRenderer.transform.position);
Vector3 screenPos = mainCamera.WorldToScreenPoint(point) - uicLineRendererOffset + uicManagerOffset;
Vector2 screenPos2D = new Vector2(screenPos.x, screenPos.y);
Vector2 anchoredPos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(canvasRect, screenPos2D, mainCamera, out anchoredPos);
return anchoredPos;// + new Vector2(canvasRect.sizeDelta.x / 2, canvasRect.sizeDelta.y / 2);
}
// v2.1 - Method added to corrected lines position when LineRenderer is offset for Canvas Screen Space Camera
public static Vector3 WorldToScreenPoint(Vector3 point, UIC_Manager uicManager)
{
Camera mainCamera = uicManager.mainCamera;
// v2.1 - Corrected lines position when LineRenderer is offset for Canvas Screen Space Camera
Vector3 uicLineRendererOffset = mainCamera.WorldToScreenPoint(uicManager.uiLineRenderer.transform.position);
return mainCamera.WorldToScreenPoint(point) - uicLineRendererOffset;
}
}
<file_sep>/MP_ARCT/Assets/Scripts/Loader/ResourceLoader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class ResourceLoader : ScriptableObject
{
public abstract void Initialize();
public abstract void LoadResources();
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/ScrollView Graphs/Scripts/UIC_SV_Zoom.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
// this is only a simple example code to show the zoomming is possible with the correct hierarchy, please, use a more reliable code in your project
public class UIC_SV_Zoom : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
bool _mouseIsOver;
public RectTransform contentRectTransform;
void Update()
{
if (_mouseIsOver)
{
if (Input.mouseScrollDelta.y != 0)
{
contentRectTransform.localScale += Vector3.one * Input.mouseScrollDelta.y * 0.2f;
}
}
}
public void OnPointerEnter(PointerEventData eventData)
{
_mouseIsOver = true;
}
public void OnPointerExit(PointerEventData eventData)
{
_mouseIsOver = false;
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Connection Puzzle/Scripts/ConnectionPuzzle_GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ConnectionPuzzle_GameManager : MonoBehaviour
{
public UIC_Manager uicManager;
void Start()
{
// set the global line type
uicManager.globalLineType = UIC_Connection.LineTypeEnum.Line;
// disable click on connections
uicManager.disableConnectionClick = true;
// add listeners for pointer events
uicManager.pointer.e_OnDragLast.AddListener(
delegate
{
PerformVirtualClickOnFoundNode();
});
uicManager.pointer.e_OnPointerDownLast.AddListener(
delegate
{
CheckAndUpdateCrossedConnections();
});
}
List<UIC_Connection> alreadyCheckedConnection = new List<UIC_Connection>();
private void CheckAndUpdateCrossedConnections()
{
UIC_Node clickedNode = uicManager.GetClickedObjectOfType<UIC_Node>();
if (clickedNode)
{
alreadyCheckedConnection.Clear();
// check every connection for a crossing, excluding the ones that were checked previously
foreach (UIC_Connection conn in clickedNode.connectionsList)
{
if (!alreadyCheckedConnection.Contains(conn))
{
alreadyCheckedConnection.Add(conn);
bool red = false;
// get connections that are crossed by conn and set their color red if exist
List<UIC_Connection> cross = conn.GetCrossedConnections();
if (cross.Count > 0)
{
alreadyCheckedConnection.AddRange(cross);
foreach (UIC_Connection c in cross)
{
c.line.color = Color.red;
}
red = true;
}
// alse check if the conn crosses any entity
foreach (UIC_Entity entity in uicManager.EntityList)
{
if ((entity != conn.node0.entity && entity != conn.node1.entity) && UIC_Utility.ConnectionIntersectRect(conn, entity.GetComponent<RectTransform>()))
{
red = true;
break;
}
}
if (red)
{
conn.line.color = Color.red;
}
else
{
conn.line.color = conn.line.defaultColor;
}
}
}
}
}
void PerformVirtualClickOnFoundNode()
{
UIC_Node clickedNode = uicManager.GetClickedObjectOfType<UIC_Node>();
// check if clicked object is a node to perform virtual click
if (clickedNode)
{
// get last node detected under the pointer
UIC_Node foundNode = clickedNode.lastFoundNode;
if (foundNode != null)
{
// if first clicked node is != than detected one, perform new simulated click
if (foundNode != clickedNode)
{
uicManager.pointer.OnPointerUp();
uicManager.pointer.OnPointerDown();
}
}
}
else
{
// call pointer down to mantain the click action
uicManager.pointer.OnPointerDown();
}
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Logic Gates/Scripts/UIC_LG_Gate.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// defines a logic gate, it is inherited by each specific gate and has the methods for get the input values and calculate output
// each gate overrides the solve method with its own logic
public class UIC_LG_Gate : MonoBehaviour
{
public UIC_Entity entity;
[HideInInspector]
public int outValue; // 0(low), 1(high), -1(undefined)
protected virtual void Awake()
{
entity = GetComponent<UIC_Entity>();
}
// update connection with the correspondent animation
public virtual void UpdateConnections()
{
if (entity.nodeList.Count - 1 == entity.GetEntitiesConnectedToPolarity(UIC_Node.PolarityTypeEnum._in).Count && !inputs.Contains(-1))
{
if (outValue == 1)
{
foreach (UIC_Node node in entity.nodeList)
{
if (node.polarityType == UIC_Node.PolarityTypeEnum._out)
{
foreach (UIC_Connection conn in node.connectionsList)
{
conn.line.animation.color = Color.red;
conn.line.animation.DrawType = UIC_Line.CapTypeEnum.Triangle;
conn.line.animation.isActive = true;
}
}
}
}
else
{
foreach (UIC_Node node in entity.nodeList)
{
if (node.polarityType == UIC_Node.PolarityTypeEnum._out)
{
foreach (UIC_Connection conn in node.connectionsList)
{
conn.line.animation.color = Color.white;
conn.line.animation.DrawType = UIC_Line.CapTypeEnum.Circle;
conn.line.animation.isActive = true;
}
}
}
}
}
else
{
foreach (UIC_Node node in entity.nodeList)
{
if (node.polarityType == UIC_Node.PolarityTypeEnum._out)
{
foreach (UIC_Connection conn in node.connectionsList)
{
conn.line.animation.isActive = false;
}
}
}
}
}
public List<int> inputs;
public virtual void GetInputs()
{
inputs = new List<int>();
foreach (UIC_Entity inEntity in entity.GetEntitiesConnectedToPolarity(UIC_Node.PolarityTypeEnum._in))
{
UIC_LG_Gate inGate = inEntity.GetComponent<UIC_LG_Gate>();
inputs.Add(inGate.outValue);
}
}
// ex AND
public virtual void Solve()
{
GetInputs();
int result;
if (inputs.Count > 0)
result = inputs[0];
else
{
outValue = -1;
return;
}
for (int i = 1; i < inputs.Count; i++)
{
if (inputs[i] == -1)
{
outValue = -1;
return;
}
else
{
bool boolInput = inputs[i] == 1;
bool boolResult = result == 1;
boolResult = boolResult & boolInput;
outValue = boolResult == true ? 1 : 0;
}
}
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Logic Gates/Scripts/UIC_LG_GateValue.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIC_LG_GateValue : UIC_LG_Gate
{
protected override void Awake()
{
base.Awake();
}
public bool value;
public override void Solve()
{
outValue = value == true ? 1 : 0;
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_LocalLineAnimationPointCount.cs
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
// v1.4 - context menu line animation point count slider added
public class UIC_LocalLineAnimationPointCount : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
public string ID => "input";
public Color objectColor { get; set; }
public int Priority => -10;
Slider _slider;
public void Action()
{
}
List<UIC_Connection> _connList = new List<UIC_Connection>();
public void OnChangeSelection()
{
_connList.Clear();
bool _show = false;
foreach (I_UIC_Selectable item in _uicManager.selectedUIObjectsList)
{
if (item is UIC_Connection)
{
_connList.Add(item as UIC_Connection);
_show = true;
}
}
gameObject.SetActive(_show);
if (_connList.Count == 1)
_slider.value = _connList[0].line.animation.pointCount;
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_slider = GetComponentInChildren<Slider>();
}
private void SetPointCount(float arg0)
{
foreach (UIC_Connection conn in _connList)
{
conn.line.animation.pointCount = (int)_slider.value;
}
}
void OnEnable()
{
_slider.onValueChanged.AddListener(SetPointCount);
}
void OnDisable()
{
_slider.onValueChanged.RemoveAllListeners();
}
public void Remove()
{
Destroy(gameObject);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_SimpleColorPicker.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_SimpleColorPicker : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
Transform _colorsPanel;
Button[] _colorButtons;
public string ID => "color picker";
public Color objectColor { get; set; }
public int Priority => -10;
public void Action()
{
}
public void OnChangeSelection()
{
gameObject.SetActive(_uicManager.selectedUIObjectsList.Count > 0);
}
void SetColor(Button _button)
{
foreach (I_UIC_Object obj in _uicManager.selectedUIObjectsList)
{
obj.objectColor = _button.image.color;
}
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_colorsPanel = transform.GetChild(1);
_colorButtons = new Button[_colorsPanel.childCount];
for (int i = 0; i < _colorButtons.Length; i++)
{
_colorButtons[i] = _colorsPanel.GetChild(i).GetComponent<Button>();
}
}
void OnEnable()
{
foreach (Button button in _colorButtons)
{
button.onClick.AddListener(delegate { SetColor(button); });
}
}
void OnDisable()
{
foreach (Button button in _colorButtons)
{
button.onClick.RemoveAllListeners();
}
}
public void Remove()
{
Destroy(gameObject);
}
}
<file_sep>/MP_ARCT/Assets/Scripts/Editor/ResouceLoaderInspector.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(ResourceLoader), true)]
public class DatabaseLoaderInspector : Editor
{
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
ResourceLoader dbLoader = (ResourceLoader)target;
if (GUILayout.Button("Load Resources"))
dbLoader.LoadResources();
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_Entity.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class UIC_Entity : MonoBehaviour, I_UIC_Object, I_UIC_Selectable, I_UIC_Draggable, I_UIC_Clickable
{
// v2.0 - local UIC manager
public UIC_Manager uicManager;
[Header("Logic")]
[SerializeField]
bool _enableDrag;
public bool EnableDrag { get => _enableDrag; set => _enableDrag = value; }
public bool enableSelfConnection;
RectTransform _rectTransform;
[Header("Elements")]
public List<UIC_Node> nodeList;
Outline _outline;
public string ID => name;
public Vector3[] Handles { get; set; }
public Color objectColor { get => _image.color; set => _image.color = value; }
public int Priority => 0;
public bool DisableClick { get; set; }
Image _image;
void Awake()
{
uicManager = GetComponentInParent<UIC_Manager>();
DisableClick = false;
_image = GetComponent<Image>();
// v2.0 - maintain the last parent
parent = transform.parent;
}
void OnValidate()
{
Init();
Awake();
}
void Start()
{
Init();
}
public void Init()
{
_outline = _outline ? _outline : gameObject.GetComponent<Outline>() ? gameObject.GetComponent<Outline>() : gameObject.AddComponent<Outline>();
if (_outline)
{
_outline.effectColor = new Color32(0x7f, 0x5a, 0xf0, 0xFF);
_outline.effectDistance = new Vector2(3, -3);
_outline.enabled = false;
}
_rectTransform = _rectTransform ? _rectTransform : GetComponent<RectTransform>();
nodeList = new List<UIC_Node>();
nodeList.AddRange(transform.GetComponentsInChildren<UIC_Node>());
}
public void UpdateConnections()
{
foreach (UIC_Node node in nodeList)
{
foreach (UIC_Connection conn in node.connectionsList)
{
conn.UpdateLine();
}
}
}
public void Select()
{
_outline.enabled = true;
if (!uicManager.selectedUIObjectsList.Contains(this))
{
uicManager.selectedUIObjectsList.Add(this);
}
}
public void Unselect()
{
_outline.enabled = false;
if (uicManager.selectedUIObjectsList.Contains(this))
{
uicManager.selectedUIObjectsList.Remove(this);
}
}
// v2.0 - using not static UIC Manager method
public void Remove()
{
Unselect();
foreach (UIC_Node node in nodeList)
{
node.RemoveAllConnections();
}
if (uicManager.EntityList.Contains(this))
{
uicManager.EntityList.Remove(this);
}
Destroy(gameObject);
}
public Transform parent;
public void OnPointerDown()
{
if (!uicManager.selectedUIObjectsList.Contains(this))
{
Select();
// v2.0 - maintain the last parent
parent = transform.parent;
}
else
{
Unselect();
}
}
public void OnPointerUp()
{
// v1.2 - using static Manager instance to set parent of dropped entity
transform.SetParent(uicManager.transform);
// v2.0 - maintain the last parent
transform.SetParent(parent);
UpdateConnections();
}
public void OnDrag()
{
if (EnableDrag)
{
Select();
transform.SetParent(uicManager.pointer.transform.GetChild(0));
UpdateConnections();
}
}
public List<UIC_Entity> GetConnectedEntities()
{
List<UIC_Entity> connectedEntities = new List<UIC_Entity>();
foreach (UIC_Node node in nodeList)
{
foreach (UIC_Connection conn in node.connectionsList)
{
UIC_Entity connEntitiy = conn.node0 != node ? conn.node0.entity : conn.node1.entity;
connectedEntities.Add(connEntitiy);
}
}
return connectedEntities;
}
// v1.4 - method to get entities connected to an specific node polarity
public List<UIC_Entity> GetEntitiesConnectedToPolarity(UIC_Node.PolarityTypeEnum polarity)
{
List<UIC_Entity> connectedEntities = new List<UIC_Entity>();
foreach (UIC_Node node in nodeList)
{
if (node.polarityType == polarity)
{
foreach (UIC_Connection conn in node.connectionsList)
{
UIC_Entity connEntitiy = conn.node0 != node ? conn.node0.entity : conn.node1.entity;
connectedEntities.Add(connEntitiy);
}
}
}
return connectedEntities;
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_ObjectName.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_ObjectName : MonoBehaviour, I_UIC_ContextItem
{
UIC_Manager _uicManager;
Text _text;
public void Action()
{
}
public void OnChangeSelection()
{
if (_uicManager.selectedUIObjectsList.Count <= 0)
{
_text.text = "--";
}
else if (_uicManager.selectedUIObjectsList.Count == 1)
{
_text.text = (_uicManager.selectedUIObjectsList[0] as I_UIC_Object).ID;
}
else
{
_text.text = string.Format("Multiple Objects ({0})", _uicManager.selectedUIObjectsList.Count);
}
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_text = transform.GetComponentInChildren<Text>();
}
}
<file_sep>/MP_ARCT/Assets/Scripts/BlockFactory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Reflection;
public class BlockFactory : MonoBehaviour
{
[SerializeField] private List<Block> blockList = new List<Block>();
public T InstantiateBlock<T>(int input, int output) where T : Block
{
T block = Instantiate<T>((T)blockList[input*3 + (output-1)]);
return block;
}
public void SetBlockAttribute<T>() where T : Block
{
}
}
<file_sep>/MP_ARCT/Assets/Scripts/LogicManager.cs
using System.Net.WebSockets;
using System.Net;
using System;
using System.Net.NetworkInformation;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;
using UnityEngine.XR.ARSubsystems;
public class LogicManager : MonoBehaviour
{
[SerializeField] private bool isLive;
[SerializeField] private ARSession _arSession;
[SerializeField] private GameObject _prefab;
[SerializeField] private GameObject _spawnedPrefab;
[SerializeField] private ARRaycastManager _arRaycastManager;
[SerializeField] private ARPlaneManager _arPlaneManager;
private List<ARRaycastHit> hits = new List<ARRaycastHit>();
private void Awake()
{
if (TryInitialize())
{
print("Error in initialize LogicManager");
}
}
private void Update()
{
if (isLive)
{
if (Input.touchCount > 0)
{
OnScreenTouch();
}
}
}
private bool TryInitialize()
{
_arSession = GetComponent<ARSession>();
return _arSession.Equals(null) || _arPlaneManager.Equals(null) || _arPlaneManager.Equals(null);
}
public void SetPlaneDetection(bool set)
{
_arPlaneManager.enabled = set;
}
private void OnScreenTouch()
{
Touch touch = Input.GetTouch(0);
Vector3 touchPos = Camera.main.ScreenToWorldPoint(touch.position);
Ray ray = Camera.main.ScreenPointToRay(touchPos);
if (touch.phase == TouchPhase.Began)
{
if (_spawnedPrefab.Equals(null))
{
if (_arRaycastManager.Raycast(ray, hits, TrackableType.PlaneWithinPolygon))
{
Pose hitPose = hits[0].pose;
Spawn(hitPose.position);
}
}
else
{
// if (Physics.Raycast(ray, out var hit))
// {
// if (hit.collider.gameObject.CompareTag("Selectable"))
// OnTouchObject(hit.collider.gameObject);
// }
}
}
}
private void Spawn(Vector3 pos)
{
_spawnedPrefab = Instantiate(_prefab);
_spawnedPrefab.SetActive(true);
_spawnedPrefab.transform.SetPositionAndRotation(pos, Quaternion.identity);
}
private void OnTouchObject(GameObject selected)
{
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_ButtonDuplicateBlock.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_ButtonDuplicateBlock : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
Button _button;
public string ID => "button";
public Color objectColor { get; set; }
public int Priority => -10;
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_button = GetComponent<Button>();
}
public void Action()
{
for (int i = _uicManager.selectedUIObjectsList.Count - 1; i >= 0; i--)
{
UIC_Entity entityToDuplicate = _uicManager.selectedUIObjectsList[i] as UIC_Entity;
if (entityToDuplicate)
{
_uicManager.InstantiateEntityAtPosition(entityToDuplicate, entityToDuplicate.transform.position + new Vector3(15, -15));
}
}
UIC_ContextMenu.UpdateContextMenu();
}
// v1.5 - fix: incorrect enabling of button "duplicate"
public void OnChangeSelection()
{
int entityCount = 0;
for (int i = _uicManager.selectedUIObjectsList.Count - 1; i >= 0; i--)
{
UIC_Entity entity = _uicManager.selectedUIObjectsList[i] as UIC_Entity;
if (entity)
{
entityCount++;
}
}
gameObject.SetActive(entityCount > 0);
}
void OnEnable()
{
_button.onClick.AddListener(Action);
}
void OnDisable()
{
_button.onClick.RemoveAllListeners();
}
public void Remove()
{
Destroy(gameObject);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_LocalLineAnimationActive.cs
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
// v1.4 - context menu line animation active toggle added
public class UIC_LocalLineAnimationActive : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
public string ID => "input";
public Color objectColor { get; set; }
public int Priority => -10;
Toggle _toggle;
public void Action()
{
}
List<UIC_Connection> _connList = new List<UIC_Connection>();
public void OnChangeSelection()
{
_connList.Clear();
bool _show = false;
foreach (I_UIC_Selectable item in _uicManager.selectedUIObjectsList)
{
if (item is UIC_Connection)
{
_connList.Add(item as UIC_Connection);
_show = true;
}
}
gameObject.SetActive(_show);
if (_connList.Count == 1)
_toggle.isOn = _connList[0].line.animation.isActive;
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_toggle = GetComponentInChildren<Toggle>();
}
private void SetIsOn(bool arg0)
{
foreach (UIC_Connection conn in _connList)
{
conn.line.animation.isActive = _toggle.isOn;
}
}
void OnEnable()
{
_toggle.onValueChanged.AddListener(SetIsOn);
}
void OnDisable()
{
_toggle.onValueChanged.RemoveAllListeners();
}
public void Remove()
{
Destroy(gameObject);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Line Renderer/UIC_Line.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class UIC_Line
{
public CapTypeEnum capStartType;
public float capStartSize;
public Color capStartColor;
public float capStartAngleOffset;
public CapTypeEnum capEndType;
public float capEndSize;
public Color capEndColor;
public float capEndAngleOffset;
public string ID;
public float width;
public Color color;
public List<Vector2> points;
public Color selectedColor = new Color32(0x7f, 0x5a, 0xf0, 0xff);
public Color hoverColor = new Color32(0x2c, 0xb6, 0x7d, 0xff);
public Color defaultColor = new Color32(0xff, 0xff, 0xfe, 0xff);
public UIC_Line()
{
color = defaultColor;
width = 2;
points = new List<Vector2>();
}
/// <summary>
/// Clear all points and add new points to the line
/// </summary>
/// <param name="newPoints"></param>
public void SetPoints(Vector2[] newPoints)
{
if (newPoints != null)
{
points.Clear();
points.AddRange(newPoints);
}
length = GetLength();
}
public enum CapTypeEnum { none, Square, Circle, Triangle };
public enum CapIDEnum { Start, End };
public void SetCap(CapIDEnum capID, CapTypeEnum capType, float capSize = 5, Color? capColor = null, float angleOffset = 0)
{
if (capID == CapIDEnum.Start)
{
this.capStartSize = capSize;
this.capStartType = capType;
this.capStartColor = capColor ?? Color.white;
this.capStartAngleOffset = angleOffset;
}
else
{
this.capEndSize = capSize;
this.capEndType = capType;
this.capEndColor = capColor ?? Color.white;
this.capEndAngleOffset = angleOffset;
}
}
// v1.4 - new methods and variables for enabling lerp line
[Range(0, 1)]
public float linePosition01;
public float length;
public UIC_LineAnimation animation = new UIC_LineAnimation();
float _deg2Rad90 = Mathf.Deg2Rad * 90f;
public float GetLength()
{
float l = 0;
for (int i = 1; i < points.Count; i++)
{
l += Vector2.Distance(points[i - 1], points[i]);
}
return l;
}
System.Tuple<int, float> GetPreviousPointELength(float pos01)
{
System.Tuple<int, float> t = new System.Tuple<int, float>(0, 0);
float l = 0;
float prevL = 0;
for (int i = 1; i < points.Count; i++)
{
l += Vector2.Distance(points[i - 1], points[i]);
if (l >= pos01 * length)
{
t = new System.Tuple<int, float>(i - 1, prevL);
break;
}
prevL = l;
}
return t;
}
// v1.4 - LerpLine method that returns point in the line, used to draw animations points
public System.Tuple<Vector2, float> LerpLine(float pos01)
{
System.Tuple<int, float> t = GetPreviousPointELength(pos01);
Vector2 p0 = points[t.Item1];
Vector2 p1 = points[t.Item1 + 1];
float ppDistance = Vector2.Distance(p0, p1);
Vector2 position = Vector2.Lerp(p0, p1, ((pos01 * length) - t.Item2) / ppDistance);
float angle = Mathf.Atan2(p0.y - p1.y, p0.x - p1.x) + _deg2Rad90;
return new System.Tuple<Vector2, float>(position, angle);
}
}
// v1.4 - added line animation class for uic_lines
[System.Serializable]
public class UIC_LineAnimation
{
public enum AnimationTypeEnum {lerp, constantSpeed}
public AnimationTypeEnum Type = AnimationTypeEnum.lerp;
public bool isActive = false;
[Range(1, 10)]
public int pointCount = 1;
public float size = 10;
public Color color = Color.white;
public UIC_Line.CapTypeEnum DrawType = UIC_Line.CapTypeEnum.Triangle;
public float speed = 0.5f;
[HideInInspector]
public float time = 0;
}
<file_sep>/MP_ARCT/Assets/Scripts/BlockOutput.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockOutput : UIC_Node
{
}
<file_sep>/MP_ARCT/Assets/Scripts/Base/BaseObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public abstract class BaseObject : MonoBehaviour
{
private ObjectManager m_ObjectManager;
[SerializeField] private string mId;
public string ID
{
get => mId;
set => mId = value;
}
protected virtual void Awake()
{
TryInitialize();
}
protected virtual bool TryInitialize()
{
m_ObjectManager = ObjectManager.Instance;
return true;
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_Node.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[ExecuteInEditMode]
public class UIC_Node : MonoBehaviour, I_UIC_Object, I_UIC_Draggable, I_UIC_Clickable
{
public Type type;
public enum PolarityTypeEnum { _in, _out, _all };
[Header("Logic")]
public PolarityTypeEnum polarityType;
[HideInInspector]
public UIC_Entity entity;
public int maxConnections = 0; // 0 - no limit
[Header("Visuals")]
public Sprite iconUnconnected;
public Sprite iconConnected;
public Color iconColorDefault;
public Color iconColorHover;
public Color iconColorSelected;
public Color iconColorConnected;
Text text;
Image imageCurrentIcon;
[Header("Elements")]
public Transform spLineControlPointTranform;
public bool haveSpots
{
get
{
return maxConnections == 0 || connectionsList.Count < maxConnections;
}
}
public string ID => string.Format("{0}'s Node ({1})", entity.name, name);
public Color objectColor { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int Priority => 2;
public bool EnableDrag { get; set; }
public bool DisableClick => false;
UIC_Line connectionUILine;
UISpline connectionUISpline;
public UIC_LineRenderer uILineRenderer;
[HideInInspector]
public UIC_Node lastFoundNode;
UIC_Node closestFoundNode;
public List<UIC_Connection> connectionsList;
void OnValidate()
{
Init();
Awake();
}
void Awake()
{
}
void Start()
{
Init();
imageCurrentIcon.color = iconColorDefault;
connectionsList = new List<UIC_Connection>();
connectionUILine = new UIC_Line();
connectionUILine.animation.isActive = false;
}
public void Init()
{
text = transform.GetChild(0).GetComponent<Text>();
imageCurrentIcon = transform.GetChild(1).GetComponent<Image>();
spLineControlPointTranform = transform.GetChild(2);
spLineControlPointTranform.name = "SPLineControlPoint";
if (polarityType == PolarityTypeEnum._in)
{
name = "In Node";
}
else if (polarityType == PolarityTypeEnum._out)
{
name = "Out Node";
}
else if (polarityType == PolarityTypeEnum._all)
{
name = "In-Out Node";
}
imageCurrentIcon.sprite = iconUnconnected;
entity = GetParentEntity(transform);
if (entity != null && !entity.nodeList.Contains(this))
entity.nodeList.Add(this);
connectionUISpline = new UISpline();
uILineRenderer = FindObjectOfType<UIC_LineRenderer>();
}
UIC_Entity GetParentEntity(Transform child)
{
if (child && child.gameObject.activeSelf)
{
UIC_Entity parentEntity = GetComponentInParent<UIC_Entity>();
if (parentEntity != null)
return parentEntity;
else
return GetParentEntity(child.parent);
}
else return null;
}
public void SetIcon()
{
if (connectionsList.Count > 0)
{
imageCurrentIcon.sprite = iconConnected;
imageCurrentIcon.color = iconColorConnected;
}
else
{
imageCurrentIcon.sprite = iconUnconnected;
imageCurrentIcon.color = iconColorDefault;
}
}
// v1.2.1 - UIC_Node.ConnectTo return UIC_Connection
public UIC_Connection ConnectTo(UIC_Node otherNode)
{
UIC_Connection _connection = null;
if (otherNode.haveSpots && this.haveSpots)
{
_connection = entity.uicManager.AddConnection(this, otherNode, entity.uicManager.globalLineType);
otherNode.SetIcon();
}
SetIcon();
return _connection;
}
public void Remove()
{
RemoveAllConnections();
entity.nodeList.Remove(this);
Destroy(gameObject);
}
public void RemoveAllConnections()
{
for (int i = connectionsList.Count - 1; i >= 0; i--)
{
connectionsList[i].Remove();
}
SetIcon();
}
public void OnPointerDown()
{
UIC_Manager uicManager = entity.uicManager;
imageCurrentIcon.color = iconColorSelected;
entity.uicManager.AddLine(connectionUILine);
connectionUILine.width = uicManager.globalLineWidth;
connectionUILine.defaultColor = uicManager.globalLineDefaultColor;
connectionUILine.color = uicManager.globalLineDefaultColor;
connectionUILine.SetCap(UIC_Line.CapIDEnum.Start, uicManager.globalCapStartType, uicManager.globalCapStartSize,
uicManager.globalCapStartColor, uicManager.globalCapStartAngleOffset);
connectionUILine.SetCap(UIC_Line.CapIDEnum.End, uicManager.globalCapEndType, uicManager.globalCapEndSize,
uicManager.globalCapEndColor, uicManager.globalCapEndAngleOffset);
}
public void OnPointerUp()
{
imageCurrentIcon.color = iconColorDefault;
connectionUILine.points.Clear();
entity.uicManager.RemoveLine(connectionUILine);
UIC_Manager uicManager = entity.uicManager;
closestFoundNode = uicManager.pointer.RaycastClosestNodeOfOppositPolarity(this);
if (closestFoundNode)
{
closestFoundNode.imageCurrentIcon.color = closestFoundNode.iconColorDefault;
if (polarityType == PolarityTypeEnum._in || closestFoundNode.polarityType == PolarityTypeEnum._out)
closestFoundNode.ConnectTo(this);
else
ConnectTo(closestFoundNode);
}
SetIcon();
lastFoundNode = null;
}
// v1.3 - line poinst adjusted to canvas render mode overlay and camera
Vector3[] LinePoints
{
get
{
UIC_Manager uicManager = entity.uicManager;
Vector3 pointerPosition = uicManager.pointer.PointerPosition;
if (uicManager.CanvasRenderMode == RenderMode.ScreenSpaceOverlay)
{
return new Vector3[] {
transform.position,
spLineControlPointTranform.position,
closestFoundNode ? closestFoundNode.spLineControlPointTranform.position : pointerPosition,
closestFoundNode ? closestFoundNode.transform.position : pointerPosition };
}
else if (uicManager.CanvasRenderMode == RenderMode.ScreenSpaceCamera)
{
return new Vector3[] {
UIC_Utility.WorldToScreenPoint(transform.position, uicManager),
UIC_Utility.WorldToScreenPoint(spLineControlPointTranform.position, uicManager),
closestFoundNode ? UIC_Utility.WorldToScreenPoint(closestFoundNode.spLineControlPointTranform.position, uicManager) : pointerPosition,
closestFoundNode ? UIC_Utility.WorldToScreenPoint(closestFoundNode.transform.position, uicManager) : pointerPosition };
}
// v1.5 - set the line points on the world space canvas
else if (uicManager.CanvasRenderMode == RenderMode.WorldSpace)
{
return new Vector3[] {
UIC_Utility.WorldToScreenPointInCanvas(transform.position, uicManager),
UIC_Utility.WorldToScreenPointInCanvas(spLineControlPointTranform.position, uicManager),
closestFoundNode ? UIC_Utility.WorldToScreenPointInCanvas(closestFoundNode.spLineControlPointTranform.position, uicManager) : UIC_Utility.WorldToScreenPointInCanvas(uicManager.pointer.transform.position, uicManager),
closestFoundNode ? UIC_Utility.WorldToScreenPointInCanvas(closestFoundNode.transform.position, uicManager) : UIC_Utility.WorldToScreenPointInCanvas(uicManager.pointer.transform.position, uicManager) };
}
return new Vector3[] {
transform.position,
spLineControlPointTranform.position,
closestFoundNode ? closestFoundNode.spLineControlPointTranform.position : pointerPosition,
closestFoundNode ? closestFoundNode.transform.position : pointerPosition };
}
}
public void OnDrag()
{
UIC_Manager uicManager = entity.uicManager;
if (lastFoundNode)
lastFoundNode.SetIcon();
closestFoundNode = uicManager.pointer.RaycastClosestNodeOfOppositPolarity(this);
if (closestFoundNode)
{
closestFoundNode.imageCurrentIcon.color = closestFoundNode.iconColorSelected;
lastFoundNode = closestFoundNode;
}
if (uicManager.globalLineType == UIC_Connection.LineTypeEnum.Spline)
{
connectionUISpline.SetControlPoints(
LinePoints[0],
LinePoints[1],
LinePoints[2],
LinePoints[3]);
connectionUILine.SetPoints(connectionUISpline.points);
}
else if (uicManager.globalLineType == UIC_Connection.LineTypeEnum.Z_Shape)
{
connectionUILine.SetPoints(new Vector2[] {
LinePoints[0],
(LinePoints[1] + LinePoints[0])/2,
(LinePoints[2] + LinePoints[3])/2,
LinePoints[3] });
}
else if (uicManager.globalLineType == UIC_Connection.LineTypeEnum.Line)
{
connectionUILine.SetPoints(new Vector2[] {
LinePoints[0],
LinePoints[3] });
}
}
public List<UIC_Entity> GetConnectedEntities()
{
List<UIC_Entity> connectedEntities = new List<UIC_Entity>();
foreach (UIC_Connection conn in connectionsList)
{
UIC_Entity connEntitiy = conn.node0 != this ? conn.node0.entity : conn.node1.entity;
connectedEntities.Add(connEntitiy);
}
return connectedEntities;
}
public List<UIC_Connection> GetOutConnections()
{
List<UIC_Connection> outConnections = new List<UIC_Connection>();
foreach (UIC_Connection conn in connectionsList)
{
if (conn.node0 == this)
outConnections.Add(conn);
}
return outConnections;
}
public List<UIC_Connection> GetInConnections()
{
List<UIC_Connection> outConnections = new List<UIC_Connection>();
foreach (UIC_Connection conn in connectionsList)
{
if (conn.node0 != this)
outConnections.Add(conn);
}
return outConnections;
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Logic Gates/Scripts/UIC_LG_GateNOT.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIC_LG_GateNOT : UIC_LG_Gate
{
protected override void Awake()
{
base.Awake();
}
public override void Solve()
{
GetInputs();
if (inputs.Count > 0)
{
outValue = inputs[0] == 0 ? 1 : 0;
}
else
{
outValue = -1;
return;
}
}
}
<file_sep>/MP_ARCT/Assets/Scripts/Loader/PrefabLoader.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
[CreateAssetMenu(menuName = "LoadResouces/LoadPrefabs")]
public class PrefabLoader : ResourceLoader
{
[SerializeField] private string[] paths;
public List<List<BaseObject>> mLoadedPrefabs;
private WaitForSeconds waits = new WaitForSeconds(0.01f);
public override void Initialize()
{
mLoadedPrefabs = new List<List<BaseObject>>();
}
public override void LoadResources()
{
foreach (var path in paths)
{
Resources.LoadAll<BaseObject>(path);
}
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/SetupInitialConnections/Editor/SetupInitialConnectionsEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(SetupInitialConnections))]
public class SetupInitialConnectionsEditor : Editor
{
SetupInitialConnections _setup;
SerializedProperty _fromNodes;
SerializedProperty _toNodes;
void OnEnable()
{
_setup = (SetupInitialConnections)target;
_fromNodes = serializedObject.FindProperty("fromNodes");
_toNodes = serializedObject.FindProperty("toNodes");
}
public override void OnInspectorGUI()
{
serializedObject.Update();
string _message =
"Define the number of connections that will be created on start.\n" +
"Set the start nodes to the left column and the end nodes to the right column.";
EditorGUILayout.HelpBox(_message, MessageType.Info);
int size = _setup.size;
_setup.size = EditorGUILayout.IntSlider("# of Connections", size, 0, 20);
int fromCount = _setup.fromNodes.Count;
int toCount = _setup.toNodes.Count;
EditorGUILayout.LabelField("Connections to be created On Start:");
EditorGUILayout.BeginHorizontal();
EditorGUILayout.BeginVertical();
if (_setup.fromNodes != null)
{
for (int i = 0; i < fromCount; i++)
{
EditorGUILayout.PropertyField(_fromNodes.GetArrayElementAtIndex(i), GUIContent.none);
}
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
if (_setup.fromNodes != null)
{
for (int i = 0; i < fromCount; i++)
{
EditorGUILayout.LabelField("——(" + i + ")——>", GUILayout.MaxWidth(80));
}
}
EditorGUILayout.EndVertical();
EditorGUILayout.BeginVertical();
if (_setup.toNodes != null)
{
for (int i = 0; i < toCount; i++)
{
EditorGUILayout.PropertyField(_toNodes.GetArrayElementAtIndex(i), GUIContent.none);
}
}
EditorGUILayout.EndVertical();
EditorGUILayout.EndHorizontal();
if (fromCount < size)
{
for (int i = fromCount - 1; i < size; i++)
{
_setup.fromNodes.Add(null);
}
}
else if (fromCount > size)
{
for (int i = fromCount - 1; i >= size; i--)
{
_setup.fromNodes.RemoveAt(i);
}
}
if (toCount < size)
{
for (int i = toCount - 1; i < size; i++)
{
_setup.toNodes.Add(null);
}
}
else if (toCount > size)
{
for (int i = toCount - 1; i >= size; i--)
{
_setup.toNodes.RemoveAt(i);
}
}
serializedObject.ApplyModifiedProperties();
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Multiple Charts/Scripts/UIC_MultipleChartsManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_MultipleChartsManager : MonoBehaviour
{
public List<GameObject> chartsList;
public void OpenChart(GameObject chart)
{
foreach (GameObject c in chartsList)
{
c.SetActive(false);
}
chart.SetActive(true);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_Manager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.UI;
[ExecuteInEditMode]
public class UIC_Manager : MonoBehaviour
{
// v2.0 - entity list not static to localize UIC to children
// list of entities in the scene, used to improve performance of detections
List<UIC_Entity> _entityList;
public List<UIC_Entity> EntityList { get => _entityList; }
// v2.0 - made not static to localize UIC to children
// list of connections in the scene, used to improve performance of detections
List<UIC_Connection> _connectionsList;
public List<UIC_Connection> ConnectionsList { get => _connectionsList; }
// v2.0 - made not static to localize UIC to children
public UIC_LineRenderer uiLineRenderer;
public List<UIC_Line> UILinesList { get => uiLineRenderer.UILines; }
// v2.0 - made not static to localize UIC to children
public Canvas canvas;
public RectTransform canvasRectTransform;
// v2.0 - made not static to localize UIC to children
// v1.3 - reference to rendermode
public RenderMode CanvasRenderMode
{
get
{
if (!canvas)
canvas = GetComponent<Canvas>();
return canvas.renderMode;
}
}
public Camera mainCamera;
// list of selected uic objects, used for single or multi selection
public List<I_UIC_Selectable> selectedUIObjectsList = new List<I_UIC_Selectable>();
public I_UIC_Object clickedUIObject;
public T GetClickedObjectOfType<T>()
{
if (clickedUIObject is T)
return (T)clickedUIObject;
else
return default(T);
}
// v2.0 - made public and not static
public UIC_Pointer pointer;
[Header("Logic")]
public bool replaceConnectionByReverse;
// v2.0 - using detect nodes from raycast instead of distance to pointer
//float _maxPointerDetectionDistance = 30;
//public float MaxPointerDetectionDistance
//{
// get
// {
// return _maxPointerDetectionDistance * canvasRectTransform.localScale.x;
// }
// set
// {
// _maxPointerDetectionDistance = value;
// }
//}
[Header("Connection Settings (for new liens)")]
public bool disableConnectionClick = false;
public int globalLineWidth = 2;
public Color globalLineDefaultColor = Color.white;
public UIC_Connection.LineTypeEnum globalLineType;
[Header("- line caps")]
public UIC_Line.CapTypeEnum globalCapStartType;
public float globalCapStartSize;
public Color globalCapStartColor;
public float globalCapStartAngleOffset;
public UIC_Line.CapTypeEnum globalCapEndType;
public float globalCapEndSize;
public Color globalCapEndColor;
public float globalCapEndAngleOffset;
[Header("- line animation")]
public UIC_LineAnimation globalLineAnimation = new UIC_LineAnimation();
private void OnEnable()
{
InitUILineRenderer();
}
void OnValidate()
{
Awake();
}
void Awake()
{
canvas = GetComponent<Canvas>();
canvasRectTransform = canvas.GetComponent<RectTransform>();
pointer = GetComponentInChildren<UIC_Pointer>();
}
void Start()
{
_entityList = new List<UIC_Entity>();
UpdateEntityList();
_connectionsList = new List<UIC_Connection>();
InitUILineRenderer();
}
void InitUILineRenderer()
{
uiLineRenderer = GetComponentInChildren<UIC_LineRenderer>();
if (!uiLineRenderer)
{
uiLineRenderer = GetComponentInChildren<UIC_LineRenderer>();
if (!uiLineRenderer)
{
uiLineRenderer = Instantiate(Resources.Load("UIC_LineRenderer") as UIC_LineRenderer, transform.position, Quaternion.identity, transform);
uiLineRenderer.name = "UIC_LineRenderer";
}
}
}
public void AddLine(UIC_Line line)
{
if (!uiLineRenderer.UILines.Contains(line))
uiLineRenderer.UILines.Add(line);
}
public void RemoveLine(UIC_Line line)
{
if (uiLineRenderer.UILines.Contains(line))
uiLineRenderer.UILines.Remove(line);
}
// v2.0 - made not static
// v1.3 - new method instantiate Entity at position
public void InstantiateEntityAtPosition(UIC_Entity entityToInstantiate, Vector3 position)
{
GameObject go = Instantiate(entityToInstantiate.gameObject, new Vector3(200, 100), Quaternion.identity, canvas.transform);
AddEntity(go.GetComponent<UIC_Entity>());
// v1.5 - instantiate entity at a convenient world space position
if (CanvasRenderMode == RenderMode.ScreenSpaceOverlay)
{
go.transform.position = position + new Vector3(15, 15, 0);
}
else if (CanvasRenderMode == RenderMode.ScreenSpaceCamera)
{
position.z = 0;
go.transform.localPosition = position + new Vector3(1, 1, 0);
}
else if (CanvasRenderMode == RenderMode.WorldSpace)
{
position.z = 0;
go.transform.localPosition = position + new Vector3(1, 1, 0);
go.transform.localRotation = Quaternion.identity;
}
}
// v2.0 - made not static
public void AddEntity(UIC_Entity entityToAdd)
{
if (!EntityList.Contains(entityToAdd))
{
EntityList.Add(entityToAdd);
}
}
// v2.0 - made not static and get entities in children
public void UpdateEntityList()
{
_entityList = new List<UIC_Entity>();
_entityList.AddRange(GetComponentsInChildren<UIC_Entity>());
}
// v1.3 - UIC_Manager.AddConnection return UIC_Connection
public UIC_Connection AddConnection(UIC_Node node0, UIC_Node node1, UIC_Connection.LineTypeEnum lineType = UIC_Connection.LineTypeEnum.Spline)
{
UIC_Connection previousConnectionWithSameNode = NodesAreConnected(node0, node1);
if (previousConnectionWithSameNode != null)
{
if (replaceConnectionByReverse)
{
previousConnectionWithSameNode.Remove();
return previousConnectionWithSameNode;
}
else
{
return previousConnectionWithSameNode;
}
}
UIC_Connection _connection = CreateConnection(node0, node1, lineType);
ConnectionsList.Add(_connection);
node0.connectionsList.Add(_connection);
node1.connectionsList.Add(_connection);
AddLine(_connection.line);
_connection.line.width = globalLineWidth;
_connection.line.defaultColor = globalLineDefaultColor;
_connection.line.color = globalLineDefaultColor;
_connection.line.SetCap(UIC_Line.CapIDEnum.Start, globalCapStartType, globalCapStartSize, globalCapStartColor, globalCapStartAngleOffset);
_connection.line.SetCap(UIC_Line.CapIDEnum.End, globalCapEndType, globalCapEndSize, globalCapEndColor, globalCapEndAngleOffset);
CopyAnimation(globalLineAnimation, _connection.line.animation);
_connection.UpdateLine();
return _connection;
}
public static void CopyAnimation(UIC_LineAnimation from, UIC_LineAnimation to)
{
to.Type = from.Type;
to.isActive = from.isActive;
to.pointCount = from.pointCount;
to.size = from.size;
to.color = from.color;
to.DrawType = from.DrawType;
to.speed = from.speed;
to.time = from.time;
}
// v1.4 - NodesAreConnected verification method made public
public UIC_Connection NodesAreConnected(UIC_Node node0, UIC_Node node1)
{
foreach (UIC_Connection connection in ConnectionsList)
{
if ((node0 == connection.node0 && node1 == connection.node1) ||
(node0 == connection.node1 && node1 == connection.node0))
return connection;
}
return null;
}
UIC_Connection CreateConnection(UIC_Node node0, UIC_Node node1, UIC_Connection.LineTypeEnum lineType)
{
UIC_Connection _connection = new UIC_Connection(node0, node1, lineType);
_connection.line = new UIC_Line();
_connection.line.width = 2;
return _connection;
}
public void RemoveUIObject()
{
for (int i = selectedUIObjectsList.Count - 1; i >= 0; i--)
{
selectedUIObjectsList[i].Remove();
}
}
public UIC_Connection FindClosestConnectionToPosition(Vector3 position, float maxDistance)
{
float minDist = Mathf.Infinity;
UIC_Connection closestConnection = null;
foreach (UIC_Connection connection in ConnectionsList)
{
int connectionPointsCount = connection.line.points.Count;
if (connectionPointsCount > 0)
{
// v1.2 - changed from DistanceToSpline(obsolete) to DistanceToConnection, a general and more precise way to find distance to connections independent of the lineType
for (int i = 1; i < connectionPointsCount; i++)
{
float distance = UIC_Utility.DistanceToConnectino(connection, position, maxDistance);
if (distance < minDist)
{
closestConnection = connection;
minDist = distance;
}
}
}
}
return closestConnection;
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/SetupInitialConnections/SetupInitialConnections.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
// v1.3 - connect defined nodes on start of the project
public class SetupInitialConnections : MonoBehaviour
{
public UIC_Manager uicManager;
[SerializeField] public List<UIC_Node> fromNodes = new List<UIC_Node>();
[SerializeField] public List<UIC_Node> toNodes = new List<UIC_Node>();
public int size = 1;
void Awake()
{
uicManager = GetComponentInParent<UIC_Manager>();
}
bool lateStart = true;
void LateStart()
{
for (int i = 0; i < fromNodes.Count; i++)
{
if (fromNodes[i] && toNodes[i])
{
fromNodes[i].ConnectTo(toNodes[i]);
}
}
lateStart = false;
//Destroy(gameObject);
}
void Update()
{
if (lateStart)
{
LateStart();
}
foreach (UIC_Connection conn in uicManager.ConnectionsList)
{
conn.UpdateLine();
}
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Logic Gates/Scripts/UIC_LG_GateOR.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIC_LG_GateOR : UIC_LG_Gate
{
protected override void Awake()
{
base.Awake();
}
public override void Solve()
{
GetInputs();
int result;
if (inputs.Count > 0)
result = inputs[0];
else
{
outValue = -1;
return;
}
for (int i = 1; i < inputs.Count; i++)
{
if (inputs[i] == -1)
{
outValue = -1;
return;
}
else
{
bool boolInput = inputs[i] == 1;
bool boolResult = result == 1;
boolResult = boolResult | boolInput;
outValue = boolResult == true ? 1 : 0;
}
}
}
}
<file_sep>/MP_ARCT/Assets/Scripts/ObjectManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ObjectManager : Singleton<ObjectManager>
{
[SerializeField]private PrefabLoader mPrefabLoader;
private Dictionary<string, Dictionary<int, BaseObject>> mActiveObjectDict;
private Dictionary<string, Dictionary<int, BaseObject>> mDeactiveObjectDict;
public Dictionary<string, Dictionary<int, BaseObject>> ActiveObjectDict { get => mActiveObjectDict;}
public Dictionary<string, Dictionary<int, BaseObject>> DeactiveObjectDict { get => mDeactiveObjectDict;}
private bool TryInitialize()
{
mActiveObjectDict = new Dictionary<string, Dictionary<int, BaseObject>>();
mDeactiveObjectDict = new Dictionary<string, Dictionary<int, BaseObject>>();
return true;
}
/// <summary>
///
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="instance"></param>
/// <param name="position"></param>
/// <param name="rotation"></param>
/// <param name="parent"></param>
public void Spawn<T>(T instance, Vector3 position, Quaternion rotation, Transform parent) where T : BaseObject
{
}
public void Spawn<T>(T instance, Vector3 position, Quaternion rotation) where T : BaseObject
{
Spawn<T>(instance, position, rotation, null);
}
public void Spawn<T>(T instance, Vector3 position, Transform parent) where T : BaseObject
{
Spawn<T>(instance, position, Quaternion.identity, parent);
}
public void Spawn<T>(T instance, Quaternion rotation, Transform parent) where T : BaseObject
{
Spawn<T>(instance, Vector3.zero, rotation, parent);
}
public void Spawn<T>(T instance, Vector3 position) where T : BaseObject
{
Spawn<T>(instance, position, Quaternion.identity, null);
}
public void Spawn<T>(T instance, Quaternion rotation) where T : BaseObject
{
Spawn<T>(instance, Vector3.zero, rotation, null);
}
public void Spawn<T>(T instance, Transform parent) where T : BaseObject
{
Spawn<T>(instance, Vector3.zero, Quaternion.identity, parent);
}
public void Spawn<T>(T instance) where T : BaseObject
{
Spawn<T>(instance, Vector3.zero, Quaternion.identity, null);
}
public void Despawn<T>(T instance) where T : BaseObject
{
}
}
<file_sep>/MP_ARCT/Assets/Scripts/BlockManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockManager : Singleton<BlockManager>
{
[SerializeField] private BlockCompiler m_blockCompiler;
public Tree<Block> blocks = new Tree<Block>();
public void Compile()
{
var levelTree = blocks.LevelTraversal();
levelTree.ForEach(leaf => m_blockCompiler.CompileBlock(leaf.info));
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Line Renderer/UIC_LineRenderer.cs
/// <NAME>
/// Procedural UI Rounded Corners - https://danielcmcg.github.io/
///
/// Based on CiaccoDavide's Unity-UI-Polygon
/// Sourced from - https://github.com/CiaccoDavide/Unity-UI-Polygon
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
// v2.1 - changed from Graphic to MaskableGraphic
// v1.2 - UIC_LineRenderer code optimization and refactoring
[ExecuteInEditMode]
public class UIC_LineRenderer : MaskableGraphic
{
UIC_Manager _uicManager;
public Sprite s1;
[SerializeField] Texture m_Texture;
RectTransform _rectTransform;
float _rectScaleX;
float _deg2Rad90 = Mathf.Deg2Rad * 90f;
Canvas _canvas;
//[HideInInspector]
public List<UIC_Line> uIlines;
// v1.0.1 - added property for UIC_LineRenderer.UILines with null check
public List<UIC_Line> UILines
{
get
{
// v2.0 - fix: uILines list reset on enable
//if (uIlines == null)
// uIlines = new List<UIC_Line>();
return uIlines;
}
}
[HideInInspector]
public override Texture mainTexture
{
get => m_Texture == null ? s_WhiteTexture : m_Texture;
}
[HideInInspector]
public Texture texture
{
get => m_Texture;
set
{
if (m_Texture == value) return;
m_Texture = value;
SetVerticesDirty();
SetMaterialDirty();
}
}
protected override void OnEnable()
{
// v2.0 - fix: uILines list reset on enable
//uIlines = uIlines == null ? uIlines : new List<UIC_Line>();
_rectTransform = GetComponent<RectTransform>();
_rectScaleX = _rectTransform.localScale.x;
_canvas = GetComponentInParent<Canvas>();
Awake();
}
void Awake()
{
// v2.0 - fix: uILines list reset on enable
//uIlines = uIlines == null ? uIlines : new List<UIC_Line>();
_uicManager = GetComponentInParent<UIC_Manager>();
}
void Update()
{
// v1.5 - scale the line renderer for world space
if (_uicManager.CanvasRenderMode != RenderMode.WorldSpace)
{
_rectTransform.localScale = Vector3.one / _canvas.scaleFactor;
}
else
{
_rectTransform.localScale = Vector3.one;
// v2.1 - fix: changes on the UIC_Manager pivot, cause offset on the LineRenderer, compensated by setting the LineRenderer pivot
_rectTransform.pivot = new Vector2(_uicManager.canvasRectTransform.pivot.x - 0.5f, _uicManager.canvasRectTransform.pivot.y - 0.5f);
}
SetVerticesDirty();
SetMaterialDirty();
}
// v1.2.1 - added uiline count limit
[HideInInspector]
public int vertCount = 0;
public bool IsVertLimitReached { get => (vertCount >= 64000); }
protected UIVertex[] SetVbo(Vector2[] vertices, Vector2[] uvs, Color _color)
{
UIVertex[] vbo = new UIVertex[4];
for (int i = 0; i < vertices.Length; i++)
{
var vert = UIVertex.simpleVert;
vert.color = _color;
vert.position = vertices[i];
vert.uv0 = uvs[i];
vbo[i] = vert;
}
return vbo;
}
Vector2 lastPos2;
Vector2 lastPos3;
protected override void OnPopulateMesh(VertexHelper vh)
{
vh.Clear();
_vh = _vh ?? vh;
if (uIlines != null)
{
foreach (UIC_Line line in uIlines)
{
if (line.points != null && line.points.Count > 0)
{
if (!IsVertLimitReached)
{
// v1.2 - fix: excessive frame drop on spline drawing
DrawLine(line);
}
else
{
Debug.Log("<!> Vert limit reached. Some lines may not be drawn");
}
vertCount = _vh.currentVertCount;
}
}
}
}
float animT = 0;
Vector2 animPositionStart;
Vector2 animPositionEnd;
VertexHelper _vh;
Vector2 uv0 = new Vector2(0, 0);
Vector2 uv1 = new Vector2(0, 1);
Vector2 uv2 = new Vector2(1, 1);
Vector2 uv3 = new Vector2(1, 0);
Vector2 pos0;
Vector2 pos1;
Vector2 pos2;
Vector2 pos3;
void DrawLine(UIC_Line line)
{
// v2.1 - Corrected lines position when LineRenderer is offset for Canvas Overlay
Vector2 uicLineRendererOffset = Vector2.zero;
if (_uicManager.CanvasRenderMode == RenderMode.ScreenSpaceOverlay)
{
uicLineRendererOffset = transform.position;
}
int linePointsCount = line.points.Count;
for (int i = 1; i < linePointsCount; i++)
{
Vector2 p0 = line.points[i - 1];
Vector2 p1 = line.points[i];
float angle = Mathf.Atan2(p0.y - p1.y, p0.x - p1.x) + (_deg2Rad90);
float cos = Mathf.Cos(angle); // calc cos
float sin = Mathf.Sin(angle); // calc sin
float _halfLineWidth = ((line.width / _rectScaleX) / 2);
float _wCos = (_halfLineWidth * cos);
float _wSin = (_halfLineWidth * sin);
// v2.1 - Corrected lines position when LineRenderer is offset
pos0 = new Vector2((p0.x) + _wCos, (p0.y) + _wSin) - uicLineRendererOffset;
pos1 = new Vector2((p0.x) - _wCos, (p0.y) - _wSin) - uicLineRendererOffset;
pos2 = new Vector2((p1.x) - _wCos, (p1.y) - _wSin) - uicLineRendererOffset;
pos3 = new Vector2((p1.x) + _wCos, (p1.y) + _wSin) - uicLineRendererOffset;
_vh.AddUIVertexQuad(SetVbo(new[] { pos0, pos1, pos2, pos3 }, new[] { uv0, uv1, uv2, uv3 }, line.color));
if (i > 1)
{
_vh.AddUIVertexQuad(SetVbo(new[] { lastPos3, lastPos2, pos1, pos0 }, new[] { uv0, uv1, uv2, uv3 }, line.color));
}
if (i == 1)
DrawCap(line.points[i - 1] - uicLineRendererOffset, angle + (line.capStartAngleOffset * Mathf.Deg2Rad), line.capStartSize, line.capStartType, line.capStartColor);
if (i == linePointsCount - 1)
DrawCap(line.points[i] - uicLineRendererOffset, angle + (line.capEndAngleOffset * Mathf.Deg2Rad), line.capEndSize, line.capEndType, line.capEndColor);
lastPos2 = pos2;
lastPos3 = pos3;
}
DrawLineAnimation(line, -uicLineRendererOffset);
}
public void DrawCap(Vector2 position, float angle, float size, UIC_Line.CapTypeEnum type, Color color)
{
if (type != UIC_Line.CapTypeEnum.none)
{
float cos = Mathf.Cos(angle); // calc cos
float sin = Mathf.Sin(angle); // calc sin
size /= _rectScaleX;
float _sSin = (size * sin);
float _sCos = (size * cos);
if (type == UIC_Line.CapTypeEnum.Square)
{
Vector2 po0 = new Vector2((position.x - _sSin) + _sCos, (position.y + _sCos) + _sSin);
Vector2 po1 = new Vector2((position.x - _sSin) - _sCos, (position.y + _sCos) - _sSin);
Vector2 po2 = new Vector2((position.x + _sSin) - _sCos, (position.y - _sCos) - _sSin);
Vector2 po3 = new Vector2((position.x + _sSin) + _sCos, (position.y - _sCos) + _sSin);
_vh.AddUIVertexQuad(SetVbo(new[] { po0, po1, po2, po3 }, new[] { uv0, uv1, uv2, uv3 }, color));
}
else if (type == UIC_Line.CapTypeEnum.Triangle)
{
Vector2 po0 = new Vector2((position.x - _sSin), (position.y + _sCos));
Vector2 po1 = new Vector2((position.x - _sSin), (position.y + _sCos));
Vector2 po2 = new Vector2((position.x + _sSin) - _sCos, (position.y - _sCos) - _sSin);
Vector2 po3 = new Vector2((position.x + _sSin) + _sCos, (position.y - _sCos) + _sSin);
_vh.AddUIVertexQuad(SetVbo(new[] { po0, po1, po2, po3 }, new[] { uv0, uv1, uv2, uv3 }, color));
}
else if (type == UIC_Line.CapTypeEnum.Circle)
{
DrawCircle(position, size, color);
}
}
}
void DrawCircle(Vector2 position, float radius, Color color)
{
Vector2 p0 = position;
Vector2 prevX = p0;
float _circleSlice = (360 / 10);
for (int j = 0; j <= 10; j++)
{
float angle = _circleSlice * j;
angle = Mathf.Deg2Rad * angle;
float cos = Mathf.Cos(angle); // calc cos
float sin = Mathf.Sin(angle); // calc sin
pos2 = p0;
pos3 = p0;
pos0 = prevX;
pos1 = new Vector2((p0.x) + (radius * cos), (p0.y) + (radius * sin));
prevX = pos1;
// v1.4 - fix: circle cap with uv wrongly positioned
_vh.AddUIVertexQuad(SetVbo(new[] { pos0, pos1, pos2, pos3 }, new[] { uv3, uv0, uv1, uv2 }, color));
}
}
// v1.4 - method to draw line animations
public void DrawLineAnimation(UIC_Line line, Vector2 offset)
{
UIC_LineAnimation animation = line.animation;
if (animation.isActive)
{
for (int i = 0; i < animation.pointCount; i++)
{
System.Tuple<Vector2, float> pointInLine;
if (animation.Type == UIC_LineAnimation.AnimationTypeEnum.lerp)
{
// triangle wave
animation.time = Mathf.Abs(((Time.time * animation.speed + ((float)i / (float)animation.pointCount)) % 1));
if (animation.speed < 0)
animation.time = 1 - animation.time;
pointInLine = line.LerpLine(animation.time);
}
else
{
float timePerPoint = 0;
animation.time += Mathf.Abs(((Time.deltaTime * animation.speed * 100)) / line.length);
if (animation.time > 1)
animation.time = 0;
timePerPoint = animation.time + ((float)i / (float)animation.pointCount);
if (timePerPoint > 1)
timePerPoint = timePerPoint - 1;
if (animation.speed < 0)
timePerPoint = 1 - timePerPoint;
pointInLine = line.LerpLine(timePerPoint);
}
DrawCap(pointInLine.Item1 + offset, pointInLine.Item2, animation.size, animation.DrawType, animation.color);
}
}
}
}
[System.Serializable]
public class UISpline
{
public Vector2[] controlPoints = new Vector2[4];
public Vector2[] points = new Vector2[1];
public int steps;
public static int minPoints = 5;
public static int maxPoints = 15;
public void SetControlPoints(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
{
// v1.2 - sets the number of points in the line based on its curvature
steps = CalculateNumberOfPointsInLine(p0, p1, p2, p3);
controlPoints = new Vector2[] { p0, p1, p2, p3 };
points = GetCurve(steps);
}
// v1.2 - added method that sets the number of points in the line based on its curvature
// - adjust the values minPoints and maxPoints to achieve the desired efficiency or smoothness of the lines
public int CalculateNumberOfPointsInLine(Vector2 p0, Vector2 p1, Vector2 p2, Vector2 p3)
{
float a0 = Mathf.Abs(Mathf.Sin(Vector2.Angle(p0 - p1, p3 - p1) * Mathf.Deg2Rad));
float a1 = Mathf.Abs(Mathf.Sin(Vector2.Angle(p3 - p2, p0 - p2) * Mathf.Deg2Rad));
float r0 = a0 > a1 ? a0 : a1;
return (int)((r0 * (maxPoints - minPoints)) + minPoints);
}
Vector2[] GetCurve(int steps)
{
points = new Vector2[steps + 1];
for (int i = 0; i < steps; i++)
{
points[i] = GetPoint(controlPoints[0], controlPoints[1], controlPoints[2], controlPoints[3], (float)i / (float)steps);
}
points[steps] = controlPoints[3];
return points;
}
public Vector3 GetPoint(Vector3 p0, Vector3 p1, Vector3 p2, Vector3 p3, float t)
{
t = Mathf.Clamp01(t);
float oneMinusT = 1f - t;
return
oneMinusT * oneMinusT * oneMinusT * p0 +
3f * oneMinusT * oneMinusT * t * p1 +
3f * oneMinusT * t * t * p2 +
t * t * t * p3;
}
}<file_sep>/MP_ARCT/Assets/Scripts/BlockInput.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BlockInput : UIC_Node
{
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Editor/UIC_NodeEditor.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
[CustomEditor(typeof(UIC_Node))]
public class UIC_NodeEditor : Editor
{
UIC_Node uicNode;
public override void OnInspectorGUI()
{
if (uicNode == null)
uicNode = (UIC_Node)target;
nodePosition = uicNode.transform.position;
spLineControlPosition = uicNode.spLineControlPointTranform.position;
DrawDefaultInspector();
}
Vector3 nodePosition;
Vector3 spLineControlPosition;
void OnSceneGUI()
{
Handles.DrawLine(nodePosition, spLineControlPosition);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/Connect The Life Cycles/Scripts/LifeCycles_GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class LifeCycles_GameManager : MonoBehaviour
{
public UIC_Manager uicManager;
int lastConnCount;
void Start()
{
foreach (UIC_Entity entity in uicManager.EntityList)
{
entity.DisableClick = true;
}
lastConnCount = uicManager.ConnectionsList != null ? uicManager.ConnectionsList.Count : 0;
// set pointer detection range for nodes
//uicManager.MaxPointerDetectionDistance = 130;
// set the line type
uicManager.globalLineType = UIC_Connection.LineTypeEnum.Line;
// add listener for pointer event
uicManager.pointer.e_OnPointerUpFirst.AddListener(
delegate
{
CheckAndUpdateNodeConnections();
});
}
private void CheckAndUpdateNodeConnections()
{
UIC_Node clickedNode = uicManager.GetClickedObjectOfType<UIC_Node>();
if (clickedNode)
{
UIC_Node foundNode = clickedNode.lastFoundNode;
if (foundNode)
{
UIC_Connection outConn = clickedNode.GetOutConnections().Count > 0 ? clickedNode.GetOutConnections()[0] : null;
UIC_Connection inConn = foundNode.GetInConnections().Count > 0 ? foundNode.GetInConnections()[0] : null;
if (outConn != null)
{
outConn.Remove();
}
if (inConn != null)
{
inConn.Remove();
}
}
}
}
void Update()
{
if (lastConnCount != uicManager.ConnectionsList.Count)
{
lastConnCount = uicManager.ConnectionsList.Count;
}
}
}
<file_sep>/MP_ARCT/Assets/Scripts/DataStructure/Node.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Node<T>
{
public int level;
public Node<T> parent;
public List<Node<T>> branches = new List<Node<T>>();
public Tree<T> rootTree;
public T info;
public int branchCount
{
get=>branches.Count;
}
public bool isRoot
{
get => parent == null;
}
public bool isExternal
{
get => branchCount == 0;
}
public bool isInternal
{
get => !isExternal;
}
public Node(Tree<T> tree, T info, Node<T> parent=null)
{
this.rootTree = tree;
this.info = info;
if (parent != null)
{
level = parent.level + 1;
}
tree.height = Math.Max(tree.height, level);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_EmptyContextItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIC_EmptyContextItem : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
public string ID => "empty";
public Color objectColor { get; set; }
public int priority;
public int Priority => priority;
public void Action()
{
}
public void OnChangeSelection()
{
}
public void Remove()
{
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_Connection.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[System.Serializable]
public class UIC_Connection : I_UIC_Object, I_UIC_Selectable, I_UIC_Clickable
{
// connection nodes, node0 start & node1 end
public UIC_Node node0;
public UIC_Node node1;
public enum LineTypeEnum { Spline, Z_Shape, Line }
public LineTypeEnum lineType;
public UIC_Line line;
public Vector3[] handles = new Vector3[2];
public UIC_Connection(UIC_Node node0, UIC_Node node1, LineTypeEnum lineType)
{
this.node0 = node0;
this.node1 = node1;
this.lineType = lineType;
}
public string ID => string.Format("Connection ({0} - {1})", node0.entity ? node0.entity.name : "null", node1.entity ? node1.entity.name : "null");
public Vector3[] Handles
{
get
{
handles[0] = node0.spLineControlPointTranform.position;
handles[1] = node1.spLineControlPointTranform.position;
return handles;
}
set => handles = value;
}
public Color objectColor
{
get => line.defaultColor;
set
{
line.color = value;
line.defaultColor = value;
}
}
public int Priority => 1;
public bool DisableClick => node0.entity.uicManager.disableConnectionClick;
public void OnPointerDown()
{
if (!node0.entity.uicManager.selectedUIObjectsList.Contains(this))
{
Select();
}
else
{
Unselect();
}
}
public void OnPointerUp()
{
}
public void Remove()
{
Unselect();
node0.connectionsList.Remove(this);
node1.connectionsList.Remove(this);
node0.SetIcon();
node1.SetIcon();
node0.entity.uicManager.RemoveLine(this.line);
node0.entity.uicManager.ConnectionsList.Remove(this);
}
public void Select()
{
line.color = line.selectedColor;
if (!node0.entity.uicManager.selectedUIObjectsList.Contains(this))
{
node0.entity.uicManager.selectedUIObjectsList.Add(this);
}
}
public void Unselect()
{
line.color = line.defaultColor;
if (node0.entity.uicManager.selectedUIObjectsList.Contains(this))
{
node0.entity.uicManager.selectedUIObjectsList.Remove(this);
}
}
public UISpline connectionUISpline;
// v1.3 - line poinst adjusted to canvas render mode overlay and camera
Vector3[] LinePoints
{
get
{
UIC_Manager uicManager = node0.entity.uicManager;
Camera mainCamera = uicManager.mainCamera;
if (uicManager.CanvasRenderMode == RenderMode.ScreenSpaceOverlay)
{
return new Vector3[] {
node0.transform.position,
Handles[0],
Handles[1],
node1.transform.position };
}
else if (uicManager.CanvasRenderMode == RenderMode.ScreenSpaceCamera)
{
return new Vector3[] {
UIC_Utility.WorldToScreenPoint(node0.transform.position, uicManager),
UIC_Utility.WorldToScreenPoint(Handles[0], uicManager),
UIC_Utility.WorldToScreenPoint(Handles[1], uicManager),
UIC_Utility.WorldToScreenPoint(node1.transform.position, uicManager) };
}
// v1.5 - set the line points on the world space canvas
else if (uicManager.CanvasRenderMode == RenderMode.WorldSpace)
{
return new Vector3[] {
UIC_Utility.WorldToScreenPointInCanvas(node0.transform.position, uicManager),
UIC_Utility.WorldToScreenPointInCanvas(Handles[0], uicManager),
UIC_Utility.WorldToScreenPointInCanvas(Handles[1], uicManager),
UIC_Utility.WorldToScreenPointInCanvas(node1.transform.position, uicManager) };
}
return new Vector3[] {
node0.transform.position,
Handles[0],
Handles[1],
node1.transform.position };
}
}
public void UpdateLine()
{
if (lineType == LineTypeEnum.Spline)
{
connectionUISpline = new UISpline();
connectionUISpline.SetControlPoints(
LinePoints[0],
LinePoints[1],
LinePoints[2],
LinePoints[3]);
line.SetPoints(connectionUISpline.points);
}
if (lineType == LineTypeEnum.Z_Shape)
{
line.SetPoints(new Vector2[] {
LinePoints[0],
(LinePoints[1] + LinePoints[0])/2,
(LinePoints[2] + LinePoints[3])/2,
LinePoints[3] });
}
if (lineType == LineTypeEnum.Line)
{
line.SetPoints(new Vector2[] {
LinePoints[0],
LinePoints[3] });
}
}
public List<UIC_Connection> GetCrossedConnections()
{
List<UIC_Connection> crossedConnections = new List<UIC_Connection>();
foreach (UIC_Connection conn in node0.entity.uicManager.ConnectionsList)
{
if (UIC_Utility.ConnectionsIntersect(conn, this))
if (!(conn.node0 == node0 || conn.node1 == node1 || conn.node0 == node1 || conn.node1 == node0))
crossedConnections.Add(conn);
}
return crossedConnections;
}
public UIC_Node GetOppositeNode(UIC_Node node)
{
return node0 == node ? node1 : node0;
}
}
<file_sep>/MP_ARCT/Assets/Scripts/Block.cs
using System.Runtime.InteropServices;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Block : UIC_Entity
{
[SerializeField] int _numOfInput;
[SerializeField] int _numOfOutput;
private BlockManager m_BlockManager;
public int InputCount
{
get => _numOfInput;
set => _numOfInput = value;
}
public int OutputCount
{
get => _numOfOutput;
set => _numOfOutput = value;
}
private void Awake()
{
m_BlockManager = BlockManager.Instance;
}
public virtual BlockOutput[] BlockAction()
{
return null;
}
public void OnAttached(Block block)
{
}
public void OnDetached()
{
}
public void TestAction()
{
string inputs = "";
string outputs = "";
foreach(var node in nodeList)
{
if (node.polarityType == UIC_Node.PolarityTypeEnum._in)
{
inputs += " " + node.name;
}
else if (node.polarityType == UIC_Node.PolarityTypeEnum._out)
{
outputs += " " + node.name;
}
}
print(string.Format("In Node : {0}, Out Node : {1}", inputs, outputs));
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Interfaces/I_UIC_ContextItem.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface I_UIC_ContextItem
{
void Action();
void OnChangeSelection();
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Interfaces/I_UIC_Selectable.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface I_UIC_Selectable
{
Vector3[] Handles { get; set; }
void Select();
void Unselect();
void Remove();
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_LocalInputLineWidth.cs
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
using UnityEngine.UI;
public class UIC_LocalInputLineWidth : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
public string ID => "input";
public Color objectColor { get; set; }
public int Priority => -10;
InputField _inputField;
public void Action()
{
}
List<UIC_Connection> _connList = new List<UIC_Connection>();
public void OnChangeSelection()
{
_connList.Clear();
bool _show = false;
foreach (I_UIC_Selectable item in _uicManager.selectedUIObjectsList)
{
if (item is UIC_Connection)
{
_connList.Add(item as UIC_Connection);
_show = true;
}
}
gameObject.SetActive(_show);
if (_connList.Count != 1)
_inputField.text = "-";
else
_inputField.text = _connList[0].line.width.ToString();
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_inputField = GetComponentInChildren<InputField>();
}
private void SetWidth(string arg0)
{
if (_inputField.text != "-")
{
foreach (UIC_Connection conn in _connList)
{
float w = conn.line.width;
if (float.TryParse(_inputField.text, NumberStyles.Float, CultureInfo.InvariantCulture, out w))
conn.line.width = w;
}
}
}
void OnEnable()
{
_inputField.onValueChanged.AddListener(SetWidth);
}
void OnDisable()
{
_inputField.onValueChanged.RemoveAllListeners();
}
public void Remove()
{
Destroy(gameObject);
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Interfaces/I_UIC_Object.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface I_UIC_Object
{
string ID { get; }
Color objectColor { get; set; }
int Priority { get; }
void Remove();
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Interfaces/I_UIC_Clickable.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface I_UIC_Clickable
{
bool DisableClick { get; }
void OnPointerDown();
void OnPointerUp();
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/Interfaces/I_UIC_Draggable.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public interface I_UIC_Draggable
{
bool EnableDrag { get; set; }
void OnDrag();
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_DropdownGlobalLineType.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_DropdownGlobalLineType : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
Dropdown _dropdown;
public string ID => "dropdown";
public Color objectColor { get; set; }
public int Priority => -9;
public void Action()
{
}
public void OnChangeSelection()
{
}
private void SetLineType(int arg0)
{
UIC_Connection.LineTypeEnum parsed_enum = (UIC_Connection.LineTypeEnum)System.Enum.Parse(typeof(UIC_Connection.LineTypeEnum), _dropdown.options[_dropdown.value].text);
_uicManager.globalLineType = parsed_enum;
}
void SetDropdown()
{
_dropdown.value = _dropdown.options.FindIndex(option => option.text == _uicManager.globalLineType.ToString());
}
void OnEnable()
{
SetDropdown();
_dropdown.onValueChanged.AddListener(SetLineType);
}
void OnDisable()
{
_dropdown.onValueChanged.RemoveAllListeners();
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_dropdown = GetComponent<Dropdown>();
}
void Start()
{
string[] _names = System.Enum.GetNames(typeof(UIC_Connection.LineTypeEnum));
List<string> _options = new List<string>();
_options.AddRange(_names);
_dropdown.options.Clear();
_dropdown.AddOptions(_options);
}
public void Remove()
{
Destroy(gameObject);
}
}
<file_sep>/MP_ARCT/Assets/Scripts/DataStructure/Tree.cs
using System.Collections;
using System.Collections.Generic;
public class Tree<T>
{
public Node<T> root;
public int height = 0;
public Tree(Node<T> root)
{
this.root = root;
}
public Tree()
{
}
public Node<T> GetNode()
{
return null;
}
public void AddBranch(Node<T> target, Node<T> added)
{
target.branches.Add(added);
}
public void RemoveBranch(Node<T> target, Node<T> deleted)
{
if (target.branchCount > 0)
{
target.branches.Remove(deleted);
}
}
public Node<T>[] LevelTraversal()
{
Queue<Node<T>> queue = new Queue<Node<T>>();
List<Node<T>> returnList = new List<Node<T>>();
queue.Enqueue(root);
while(queue.Count > 0)
{
var temp = queue.Dequeue();
foreach(var branch in temp.branches)
{
queue.Enqueue(branch);
}
returnList.Add(temp);
}
return returnList.ToArray();
}
}
<file_sep>/MP_ARCT/Assets/Scripts/Base/Singleton.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> : MonoBehaviour where T : MonoBehaviour
{
private static bool _ShuttingDown = false;
private static object _Lock = new object();
private static T _Instance;
public static T Instance
{
get
{
if (_ShuttingDown)
{
Debug.Log("[Singleton] Instance '" + typeof(T) + "' already destroyed. Returning null.");
return null;
}
lock (_Lock) //Thread Safe
{
if (_Instance == null)
{
_Instance = (T)FindObjectOfType(typeof(T));
if (_Instance == null)
{
var singletonObject = new GameObject();
_Instance = singletonObject.AddComponent<T>();
singletonObject.name = typeof(T).ToString();
}
}
return _Instance;
}
}
}
private void OnApplicationQuit()
{
_ShuttingDown = true;
}
private void OnDestroy()
{
_ShuttingDown = true;
}
}
//출처: https://skuld2000.tistory.com/26 [아마군의 Dev로그]<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scenes/ScrollView Graphs/Scripts/CustomScrollRect.cs
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine;
public class CustomScrollRect : ScrollRect
{
int maximumTouchCount = 2;
public Vector2 MultiTouchPosition
{
get
{
Vector2 position = Vector2.zero;
for (int i = 0; i < Input.touchCount && i < maximumTouchCount; i++)
{
position += Input.touches[i].position;
}
position /= ((Input.touchCount <= maximumTouchCount) ? Input.touchCount : maximumTouchCount);
return position;
}
}
public override void OnBeginDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Middle)
{
eventData.button = PointerEventData.InputButton.Left;
base.OnBeginDrag(eventData);
}
if (Input.touchCount >= maximumTouchCount)
{
eventData.position = MultiTouchPosition;
base.OnBeginDrag(eventData);
}
}
public override void OnEndDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Middle)
{
eventData.button = PointerEventData.InputButton.Left;
base.OnEndDrag(eventData);
}
if (Input.touchCount >= maximumTouchCount)
{
eventData.position = MultiTouchPosition;
base.OnEndDrag(eventData);
}
}
public override void OnDrag(PointerEventData eventData)
{
if (eventData.button == PointerEventData.InputButton.Middle)
{
eventData.button = PointerEventData.InputButton.Left;
base.OnDrag(eventData);
}
if (Input.touchCount >= maximumTouchCount)
{
eventData.position = MultiTouchPosition;
base.OnDrag(eventData);
}
}
}<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/ContextItems/UIC_GlobalInputLineWidth.cs
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIC_GlobalInputLineWidth : MonoBehaviour, I_UIC_ContextItem, I_UIC_Object
{
UIC_Manager _uicManager;
InputField _inputField;
public string ID => throw new NotImplementedException();
public Color objectColor { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public int Priority => -10;
public void Action()
{
}
public void OnChangeSelection()
{
_inputField.text = _uicManager.globalLineWidth.ToString();
}
void Awake()
{
_uicManager = GetComponentInParent<UIC_Manager>();
_inputField = GetComponentInChildren<InputField>();
}
private void SetWidth(string arg0)
{
_uicManager.globalLineWidth = int.Parse(_inputField.text);
}
void OnEnable()
{
_inputField.onValueChanged.AddListener(SetWidth);
}
void OnDisable()
{
_inputField.onValueChanged.RemoveAllListeners();
}
public void Remove()
{
throw new NotImplementedException();
}
}
<file_sep>/MP_ARCT/Assets/UI Connect Asset/Scripts/UIC_ContextMenu.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UIC_ContextMenu : MonoBehaviour
{
static List<I_UIC_ContextItem> contextItemList;
void Awake()
{
contextItemList = new List<I_UIC_ContextItem>();
foreach (Transform t in transform)
{
I_UIC_ContextItem item = t.GetComponent<I_UIC_ContextItem>();
if (item != null)
contextItemList.Add(item);
}
}
void Start()
{
UpdateContextMenu();
}
public static void UpdateContextMenu()
{
if (contextItemList != null)
{
foreach (I_UIC_ContextItem item in contextItemList)
{
item.OnChangeSelection();
}
}
}
}
| 1f42f1c94cb014428dd775b6e00f9f1ebbab81a8 | [
"C#"
] | 53 | C# | masaywar/MP_ARCT | de0641da32790e3434fe2f7037430e9e4c568abf | 18111af9e92b6357505daf85b00fb5b247371871 | |
refs/heads/master | <file_sep>import {User} from './User';
export class Conversation {
id: number;
chatName: string;
hidden: boolean;
users: User[];
}
<file_sep>create table conversation
(
id bigserial not null
constraint conversation_pkey
primary key,
chat_name varchar,
creator_id bigint
);
create unique index conversation_id_uindex
on conversation (id);
create table "user"
(
id bigserial not null
constraint user_pkey
primary key,
login varchar not null,
hash varchar not null
);
create unique index user_id_uindex
on "user" (id);
create unique index user_login_uindex
on "user" (login);
create table message
(
id bigserial not null
constraint message_pkey
primary key,
conversation_id bigint not null
constraint message_conversation_id_fk
references conversation,
sent timestamp with time zone not null,
text varchar,
sender_id bigint not null
constraint message_user_id_fk
references "user"
);
create unique index message_id_uindex
on message (id);
create table forwarded_message
(
parent_message_id bigint not null
constraint forwarded_message_message_id_fk
references message,
forwarded_message_id bigint not null
constraint forwarded_message_message_id_fk_2
references message
);
create table token
(
id bigserial not null
constraint token_pk
primary key,
user_id bigint not null
constraint token_user_id_fk
references "user",
token varchar not null
);
create table user_info
(
id bigserial not null
constraint user_main_info_2_pk
primary key,
user_id bigint not null
constraint user_main_info_2_user_id_fk
references "user",
first_name varchar not null,
last_name varchar not null,
gender boolean,
birth_date date,
marital_status varchar,
country varchar,
city varchar,
location varchar,
phone_number varchar,
mail varchar,
place_of_education varchar,
place_of_work varchar,
about varchar
);
create unique index user_main_info_2_id_uindex
on user_info (id);
create table user_online
(
id bigserial not null
constraint user_online_pk
primary key,
user_id bigint not null
constraint user_online_user_id_fk
references "user",
seen timestamp with time zone not null
);
create unique index user_online_id_uindex
on user_online (id);
create table avatar
(
id bigserial not null
constraint avatar_pk
primary key,
user_id bigint not null
constraint avatar_user_id_fk
references "user",
path varchar not null,
uploaded date not null
);
create table image
(
id bigserial not null
constraint image_pk
primary key,
user_id bigint not null
constraint image_user_id_fk
references "user",
message_id bigint not null
constraint image_message_id_fk
references message,
path varchar not null,
uploaded date not null
);
create unique index image_id_uindex
on image (id);
create unique index image_path_uindex
on image (path);
create unique index document_id_uindex
on image (id);
create unique index document_path_uindex
on image (path);
create table document
(
id bigserial not null
constraint document_pkey
primary key,
user_id bigint not null
constraint document_user_id_fk
references "user",
message_id bigint not null
constraint document_message_id_fk
references message,
path varchar not null,
uploaded date not null
);
create table user_conversation
(
id bigserial not null
constraint user_conversation_pk
primary key,
user_id bigint not null
constraint user_conversation_user_id_fk
references "user",
conversation_id bigint not null
constraint user_conversation_conversation_id_fk
references conversation,
hidden boolean default false,
last_read timestamp with time zone not null,
kicked boolean default false
);
create unique index user_conversation_id_uindex
on user_conversation (id);
INSERT INTO public."user" (id, login, hash)
VALUES (0, 'system', '9ORQk/lZ9xIqQRHYpKUnFIPoAz31kj0xCz47u8FHE7k=$/5l1c6S8EZGjrFaJoMXpI0fGSHisgBj3lv9Ldiejou0=');
INSERT INTO public.user_info (id, user_id, first_name, last_name, gender, birth_date, marital_status, country, city,
location, phone_number, mail, place_of_education, place_of_work, about)
VALUES (0, 0, 'system', '', null, null, null, null, null, null, null, null, null, null, null);<file_sep>package com.gmail.ivanjermakov1.messenger.test.unit;
import com.gmail.ivanjermakov1.messenger.dto.NewChatDto;
import com.gmail.ivanjermakov1.messenger.dto.TestingUser;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.service.ChatService;
import com.gmail.ivanjermakov1.messenger.service.TestingService;
import com.gmail.ivanjermakov1.messenger.service.UserService;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Collections;
@Ignore
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class ChatUnitTest {
@Autowired
private UserService userService;
@Autowired
private ChatService chatService;
@Autowired
private TestingService testingService;
private TestingUser user1;
private TestingUser user2;
private Conversation chat;
@Before
public void before() throws RegistrationException, AuthenticationException {
user1 = testingService.registerUser("Jack");
user2 = testingService.registerUser("Ron");
chat = chatService.create(
user1.user,
new NewChatDto(
"chat",
Collections.singletonList(user2.user.id)
)
);
}
}
<file_sep>import {Component, ElementRef, HostListener, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {Title} from '@angular/platform-browser';
import * as moment from 'moment';
import {Subject} from 'rxjs';
import {debounceTime, distinctUntilChanged} from 'rxjs/operators';
import {User} from '../../../dto/User';
import {Preview} from '../../../dto/Preview';
import {Message} from '../../../dto/Message';
import {MessageAttachments} from '../../../dto/MessageAttachments';
import {ImageCompressionMode} from '../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../service/image.service';
import {NewImage} from '../../../dto/NewImage';
import {AppComponent} from '../../../app.component';
import {MeProvider} from '../../../provider/me-provider';
import {MessageService} from '../../../service/message.service';
import {TokenProvider} from '../../../provider/token-provider';
import {PreviewService} from '../../../service/preview.service';
import {AuthService} from '../../../service/auth.service';
import {SearchService} from '../../../service/search.service';
import {CookieService} from '../../../service/cookie.service';
import {MessagingService} from '../../../service/messaging.service';
import {ConversationService} from '../../../service/conversation.service';
import {SoundNotificationService} from '../../../service/sound-notification.service';
import {UserInfoService} from '../../../service/user-info.service';
import {BackgroundUnreadService} from '../../../service/background-unread.service';
import {AvatarService} from '../../../service/avatar.service';
import {APP_TITLE, FILE_URL, MESSAGES_AMOUNT, MINUTES_AS_ONLINE_LIMIT, PREVIEWS_AMOUNT} from '../../../../../globals';
import {NewMessage} from '../../../dto/NewMessage';
import {DateService} from '../../../service/date.service';
import {NewMessageAction} from '../../../dto/action/NewMessageAction';
import {ConversationReadAction} from '../../../dto/action/ConversationReadAction';
import {MessageEditAction} from '../../../dto/action/MessageEditAction';
import {Pageable} from '../../../dto/Pageable';
import {NewDocument} from '../../../dto/NewDocument';
import {MessageImage} from '../../../dto/local/MessageImage';
import {ChatService} from '../../../service/chat.service';
import {NewChat} from '../../../dto/NewChat';
import {PreviewType} from '../../../dto/enum/PreviewType';
import {ConfirmService} from '../../../service/confirm.service';
@Component({
selector: 'app-messaging',
templateUrl: './messaging.component.html',
styleUrls: [
'./messaging.component.scss',
'./style/messaging.component.header-left.scss',
'./style/messaging.component.header-right.scss',
'./style/messaging.component.search.scss',
'./style/messaging.component.select-message.scss',
'./style/messaging.component.content-left.scss',
'./style/messaging.component.conversation.scss'
]
})
export class MessagingComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
readonly PreviewType: typeof PreviewType = PreviewType;
token: string;
isPolling = false;
me: User;
previews: Preview[];
messages: Message[];
routeConversationId: number;
currentPreview: Preview;
messageText = '';
searchText = '';
searchTextChanged: Subject<string> = new Subject();
searchUsers: User[] = [];
searchPreviews: Preview[] = [];
selectedMessages: Message[] = [];
editingMessage: Message;
currentMessageAttachments: MessageAttachments = new MessageAttachments();
currentProfile = {
userInfo: null,
user: null
};
isLeftView = true;
isSelectForwardTo = false;
attachedImages: NewImage[] = [];
attachedDocuments: NewDocument[] = [];
messageImage: MessageImage = null;
showChatInfo = false;
@ViewChild('sendMessageText') sendMessageText: ElementRef;
@ViewChild('previewSearch') previewSearch: ElementRef;
@ViewChild('messageWrapper') messageWrapper: ElementRef;
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.key === 'Escape') {
if (this.messageImage) {
this.messageImage = null;
return;
}
if (this.currentProfile.user) {
this.currentProfile.user = null;
return;
}
if (this.showChatInfo) {
this.showChatInfo = false;
return;
}
if (this.editingMessage) {
this.cancelEditing();
return;
}
if (!this.isSelectForwardTo && this.currentMessageAttachments.forwarded.length !== 0) {
this.currentMessageAttachments.forwarded = [];
return;
}
if (this.isSelectForwardTo) {
this.isSelectForwardTo = false;
this.currentMessageAttachments.forwarded = [];
return;
}
if (this.searchText !== '') {
this.searchText = '';
return;
}
if (this.selectedMessages.length !== 0) {
this.deselectMessages();
return;
}
if (this.currentPreview) {
this.closeConversation();
}
}
}
@HostListener('window:focus', ['$event'])
onFocus(event: any): void {
this.backgroundUnreadService.resetUnreadCount();
this.titleService.setTitle(APP_TITLE);
}
constructor(private app: AppComponent,
private route: ActivatedRoute,
private router: Router,
private titleService: Title,
private previewService: PreviewService,
private tokenProvider: TokenProvider,
private meProvider: MeProvider,
private messageService: MessageService,
private authService: AuthService,
private searchService: SearchService,
private cookieService: CookieService,
private messagingService: MessagingService,
private conversationService: ConversationService,
private chatService: ChatService,
private soundNotificationService: SoundNotificationService,
private userInfoService: UserInfoService,
private backgroundUnreadService: BackgroundUnreadService,
private avatarService: AvatarService,
private imageService: ImageService,
private confirmService: ConfirmService
) {
}
ngOnInit() {
this.searchTextChanged
.pipe(debounceTime(200), distinctUntilChanged())
.subscribe(searchText => {
this.searchForConversationsOrUsers(searchText);
});
this.app.onLoad(() => {
this.route.queryParams.subscribe(params => {
if (!this.isPolling) {
this.meProvider.oMe.subscribe(me => {
return this.me = me;
});
this.tokenProvider.oToken.subscribe(token => {
this.token = token;
this.startListening();
});
}
this.routeConversationId = params['id'];
if (this.routeConversationId) {
this.isLeftView = false;
this.loadCurrentConversation();
} else {
this.isLeftView = true;
this.currentPreview = null;
this.messages = [];
}
this.updatePreviews();
});
});
}
updatePreviews() {
this.previewService.all(this.token, new Pageable(0, PREVIEWS_AMOUNT)).subscribe(previews => {
this.previews = previews.filter(p => p.lastMessage && !p.conversation.hidden);
});
}
updateMessages() {
this.messageService.get(this.token, this.routeConversationId, new Pageable(0, MESSAGES_AMOUNT)).subscribe(messages => {
this.messages = messages;
});
}
previewsOrSearchPreviews(): Preview[] {
if (this.searchText === '') {
return this.previews;
} else {
return this.searchPreviews;
}
}
openConversation(conversationId: number) {
if (this.currentPreview && this.currentPreview.conversation.id === conversationId) return;
this.router.navigate(['/im'], {queryParams: {id: conversationId}});
this.messages = null;
this.isSelectForwardTo = false;
this.sendMessageTextFocus();
}
closeConversation() {
this.router.navigate(['/im']);
}
createConversation(user: User) {
this.conversationService.create(this.token, user.login).subscribe(conversation => {
this.openConversation(conversation.id);
});
}
createChat(chatName: string) {
let newChat = new NewChat();
newChat.name = chatName;
this.chatService.create(this.token, newChat).subscribe(chat => {
this.openConversation(chat.id);
});
}
searchForConversationsOrUsers(searchText: string) {
if (searchText === '') return;
if (searchText[0] === '@') {
this.searchService.searchUsers(this.token, searchText)
.subscribe(users => this.searchUsers = users);
} else {
this.searchService.searchConversations(this.token, searchText)
.subscribe(conversations => this.searchPreviews = conversations);
}
}
sendMessage() {
const message = new NewMessage();
message.senderId = this.me.id;
message.conversationId = this.currentPreview.conversation.id;
message.text = this.messageText;
message.forwarded = this.currentMessageAttachments.forwarded;
message.images = this.attachedImages;
message.documents = this.attachedDocuments;
if ((message.forwarded.length === 0 && message.images.length === 0 && message.documents.length === 0) && message.text.trim().length === 0) return;
this.messageText = '';
this.currentMessageAttachments = new MessageAttachments();
// TODO: use temp unique id to identify temp message instead of unshifting last
const tempViewMessage = new Message();
tempViewMessage.sender = this.me;
tempViewMessage.forwarded = message.forwarded;
tempViewMessage.text = message.text;
this.messages.unshift(tempViewMessage);
this.messagingService.sendMessage(this.token, message).subscribe(m => {
this.updatePreviews();
this.messages = this.messages.filter(mes => mes.id);
this.messages.unshift(m);
this.attachedImages = [];
this.attachedDocuments = [];
});
}
selectMessage(message: Message, event?) {
if (event.target.className === 'avatar') return;
if (!message.selected) {
message.selected = true;
this.selectedMessages.push(message);
} else {
message.selected = false;
this.selectedMessages = this.selectedMessages.filter(m => m.id !== message.id);
}
}
deselectMessages() {
this.selectedMessages.forEach(m => m.selected = false);
this.selectedMessages = [];
}
deleteSelectedMessages() {
this.messageService.delete(this.token, this.selectedMessages).subscribe(
() => {
this.updatePreviews();
this.updateMessages();
},
error => {
this.updatePreviews();
this.updateMessages();
}
);
this.deselectMessages();
}
editSelectedMessage() {
this.editingMessage = this.selectedMessages[0];
this.messageText = this.editingMessage.text;
this.sendMessageTextFocus();
}
editMessage() {
this.editingMessage.text = this.messageText;
this.messagingService.editMessage(this.token, this.editingMessage).subscribe(m => {
this.cancelEditing();
this.messageImage = null;
});
}
attachSelectedMessagesAsForwardedAttachment() {
this.currentMessageAttachments.forwarded = this.selectedMessages;
this.deselectMessages();
}
forwardSelectedMessages() {
this.attachSelectedMessagesAsForwardedAttachment();
this.isSelectForwardTo = true;
this.isLeftView = true;
}
removeForwardedAttachment() {
this.currentMessageAttachments.forwarded = [];
}
cancelEditing() {
this.deselectMessages();
this.editingMessage = null;
this.messageText = '';
}
incrementBackgroundUnread() {
if (document.visibilityState === 'hidden') {
this.backgroundUnreadService.incrementUnreadCount();
this.backgroundUnreadService.oUnreadCount.subscribe(c => {
this.titleService.setTitle(`${APP_TITLE} ${c} new message${c === 1 ? '' : 's'}`);
});
}
}
lastSeenView(lastSeen: Date): string {
return DateService.lastSeenView(lastSeen);
}
isOnline(time: Date): boolean {
return time && moment().diff(time, 'minutes') < MINUTES_AS_ONLINE_LIMIT;
}
loadMoreMessages() {
if (this.messages.length % MESSAGES_AMOUNT !== 0) return;
const pageable = new Pageable(Math.floor(this.messages.length / MESSAGES_AMOUNT), MESSAGES_AMOUNT);
this.messageService.get(this.token, this.currentPreview.conversation.id, pageable).subscribe(messages => {
this.messages = this.messages.concat(messages);
});
}
loadMorePreviews() {
if (this.previews.length % PREVIEWS_AMOUNT !== 0) return;
const pageable = new Pageable(Math.floor(this.previews.length / PREVIEWS_AMOUNT), PREVIEWS_AMOUNT);
this.previewService.all(this.token, pageable).subscribe(previews => {
this.previews = this.previews.concat(previews);
});
}
scrollToBottom() {
if (this.messageWrapper) this.messageWrapper.nativeElement.scrollTop = this.messageWrapper.nativeElement.scrollHeight;
}
openPreviewInfo() {
switch (+PreviewType[this.currentPreview.type]) {
case PreviewType.CONVERSATION:
this.openProfile(this.currentPreview.with);
break;
case PreviewType.CHAT:
this.showChatInfo = true;
break;
}
}
openProfile(user: User) {
this.userInfoService.get(this.token, user.id).subscribe(userInfo => {
this.currentProfile.user = user;
this.currentProfile.userInfo = userInfo;
});
}
editProfile(userInfo) {
this.userInfoService.edit(this.token, userInfo).subscribe(info => {
this.uploadAvatar(userInfo.newAvatar);
this.currentProfile.userInfo = info;
});
}
uploadAvatar(avatar: File) {
if (!avatar) {
return;
}
this.avatarService.upload(this.token, avatar).subscribe(avatarResponse => {
this.currentProfile.user.avatar = avatarResponse;
});
}
removeImageAttachment(image: NewImage) {
this.attachedImages = this.attachedImages.filter(i => i.path === image.path);
}
removeDocumentAttachment(document: NewDocument) {
this.attachedDocuments = this.attachedDocuments.filter(d => d.path === document.path);
}
sendMessageTextFocus() {
setTimeout(() => {
if (this.sendMessageText) this.sendMessageText.nativeElement.focus();
}, 0);
}
previewSearchFocus() {
setTimeout(() => {
if (this.previewSearch) {
this.previewSearch.nativeElement.focus();
}
}, 0);
}
deleteImageFromMessage() {
this.imageService.delete(this.token, this.messageImage.image.id).subscribe(() => {
this.editingMessage = this.messageImage.message;
this.editMessage();
});
}
addToChat(user: User) {
if (this.currentPreview.type.toString() !== PreviewType[PreviewType.CHAT]) return;
this.chatService.addMember(this.token, this.currentPreview.conversation.id, user.id).subscribe(() => {
this.loadOrUpdatePreview(this.currentPreview.conversation.id);
});
}
kickMember(user: User) {
this.confirmService.confirm(`${user.firstName} will be kicked from chat`);
this.chatService.kickMember(this.token, this.currentPreview.conversation.id, user.id).subscribe(() => {
this.loadOrUpdatePreview(this.currentPreview.conversation.id);
});
}
private loadCurrentConversation() {
this.previewService.get(this.token, this.routeConversationId).subscribe(preview => {
this.currentPreview = preview;
this.scrollToBottom();
}, error => this.closeConversation());
this.messageService.get(this.token, this.routeConversationId, new Pageable(0, MESSAGES_AMOUNT)).subscribe(messages => {
this.searchText = '';
this.messages = messages;
});
}
private loadOrUpdatePreview(conversationId: number) {
this.previewService.get(this.token, conversationId).subscribe(preview => {
const existingPreview = this.previews.find(p => p.conversation.id === preview.conversation.id);
if (existingPreview) {
Object.assign(existingPreview, preview);
} else {
this.previews.push(preview);
}
if (preview.conversation.id == this.routeConversationId) {
this.currentPreview = preview;
}
});
}
private startListening() {
this.isPolling = true;
this.messagingService.getEvents(this.token).subscribe(action => {
console.debug(action);
setTimeout(() => {
switch (action.type) {
case 'NEW_MESSAGE':
this.processNewMessage(action);
break;
case 'CONVERSATION_READ':
this.processRead(action);
break;
case 'MESSAGE_EDIT':
this.processEdit(action);
break;
}
// TODO: investigate magic
}, 100);
});
}
private processNewMessage(action: NewMessageAction) {
this.loadOrUpdatePreview(action.message.conversation.id);
if (action.message.sender.id === this.me.id) return;
this.incrementBackgroundUnread();
this.soundNotificationService.notify();
if (this.currentPreview && action.message.conversation.id === this.currentPreview.conversation.id) {
this.messages.unshift(action.message);
}
}
private processRead(action: ConversationReadAction) {
this.loadOrUpdatePreview(action.conversation.id);
if (action.reader.id === this.me.id) return;
if (this.messages && this.currentPreview && action.conversation.id === this.currentPreview.conversation.id) {
this.messages.forEach(m => m.read = true);
}
}
private processEdit(action: MessageEditAction) {
this.loadOrUpdatePreview(action.message.conversation.id);
if (this.currentPreview && action.message.conversation.id === this.currentPreview.conversation.id) {
const updatedMessage = this.messages.find(_m => _m.id === action.message.id);
Object.assign(updatedMessage, action.message);
}
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.repository;
import com.gmail.ivanjermakov1.messenger.entity.Image;
import org.springframework.data.repository.CrudRepository;
public interface ImageRepository extends CrudRepository<Image, Long> {
}
<file_sep>import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class TokenProvider {
private token = new BehaviorSubject<string>('');
oToken = this.token.asObservable();
constructor() {
}
setToken(token: string) {
this.token.next(token);
}
}
<file_sep>export enum MaritalStatus {
SINGLE,
SEEING,
MARRIED
}
<file_sep>package com.gmail.ivanjermakov1.messenger.validator;
import com.github.ivanjermakov.jtrue.core.Validatable;
import com.github.ivanjermakov.jtrue.core.Validator;
import com.github.ivanjermakov.jtrue.predicate.NotEmptyCollection;
import com.github.ivanjermakov.jtrue.predicate.NotNull;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.entity.Document;
import com.gmail.ivanjermakov1.messenger.entity.Image;
import com.gmail.ivanjermakov1.messenger.entity.Message;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.InvalidEntityException;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.function.Function;
@Component
public class MessageValidator implements Validatable<Message> {
private Validator<Message> attachmentValidator = new Validator<Message>()
.map(m -> m.forwarded).rule(new NotNull<List<Message>>().and(new NotEmptyCollection<>()).negate())
.map(m -> m.images).rule(new NotNull<List<Image>>().and(new NotEmptyCollection<>()).negate())
.map(m -> m.documents).rule(new NotNull<List<Document>>().and(new NotEmptyCollection<>()).negate());
private Validator<Message> validator = new Validator<Message>()
.map(m -> m.sender).use(new Validator<User>()
.rule(new NotNull<>(), "user cannot be null")
.map(u -> u.id).rule(new NotNull<>(), "user id cannot be null")
)
.map(m -> m.conversation).use(new Validator<Conversation>()
.rule(new NotNull<>(), "conversation cannot be null")
.map(c -> c.id).rule(new NotNull<>(), "conversation id cannot be null")
)
.rule(m -> !m.text.isEmpty() || !attachmentValidator.validate(m), "message without text must contain attachments")
.throwing((Function<String, Throwable>) InvalidEntityException::new);
@Override
public boolean validate(Message target) {
return validator.validate(target);
}
@Override
public void throwInvalid(Message target) throws InvalidEntityException {
try {
validator.throwInvalid(target);
} catch (InvalidEntityException e) {
throw e;
} catch (Throwable ignored) {
}
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.integration;
import com.gmail.ivanjermakov1.messenger.controller.AuthenticationController;
import com.gmail.ivanjermakov1.messenger.controller.RegistrationController;
import com.gmail.ivanjermakov1.messenger.dto.RegisterUserDto;
import com.gmail.ivanjermakov1.messenger.dto.UserDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.service.UserService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class AuthenticationTest {
@Autowired
private AuthenticationController authenticationController;
@Autowired
private UserService userService;
@Autowired
private RegistrationController registrationController;
@Test
public void shouldAuthenticate() throws RegistrationException, AuthenticationException {
registrationController.register(
new RegisterUserDto("Jack", "Johnson", "jackj", "<PASSWORD>")
);
String token = authenticationController.authenticate("jackj", "<PASSWORD>");
Assert.assertNotNull(token);
UserDto user = authenticationController.validate(
userService.authenticate(token),
token
);
Assert.assertNotNull(user);
Assert.assertEquals("jackj", user.login);
}
@Test(expected = AuthenticationException.class)
public void shouldThrowException_WithWrongPassword() throws RegistrationException, AuthenticationException {
registrationController.register(
new RegisterUserDto("Jack", "Johnson", "jackj", "password")
);
authenticationController.authenticate("jackj", "not_password");
}
@Test(expected = AuthenticationException.class)
public void shouldLogout() throws RegistrationException, AuthenticationException {
registrationController.register(
new RegisterUserDto("Jack", "Johnson", "jackj", "<PASSWORD>")
);
String token = authenticationController.authenticate("jackj", "<PASSWORD>");
Assert.assertNotNull(token);
User user = userService.authenticate(token);
UserDto userDto = authenticationController.validate(user, token);
Assert.assertNotNull(userDto);
Assert.assertEquals("jackj", userDto.login);
authenticationController.logout(user);
authenticationController.validate(user, token);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.mapper;
import com.gmail.ivanjermakov1.messenger.dto.AvatarDto;
import com.gmail.ivanjermakov1.messenger.entity.Avatar;
import com.gmail.ivanjermakov1.messenger.util.Mappers;
import org.springframework.stereotype.Component;
@Component
public class AvatarMapper implements Mapper<Avatar, AvatarDto> {
@Override
public AvatarDto map(Avatar avatar) {
return Mappers.map(avatar, AvatarDto.class);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.unit;
import com.gmail.ivanjermakov1.messenger.dto.TestingUser;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.repository.UserConversationRepository;
import com.gmail.ivanjermakov1.messenger.service.ConversationService;
import com.gmail.ivanjermakov1.messenger.service.MessageService;
import com.gmail.ivanjermakov1.messenger.service.TestingService;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Pageable;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
@Ignore
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class MessageUnitTest {
@InjectMocks
private MessageService messageService;
@Mock
private UserConversationRepository userConversationRepository;
@Autowired
private ConversationService conversationService;
@Autowired
private TestingService testingService;
@Test(expected = NoSuchEntityException.class)
public void shouldThrowException_WhenGetWithInvalidConversationId() throws RegistrationException, AuthenticationException {
TestingUser user1 = testingService.registerUser("Jack");
TestingUser user2 = testingService.registerUser("Ron");
Conversation conversation = conversationService.create(user1.user, user2.user);
when(userConversationRepository.findByUserAndConversation(any(), any()))
.thenReturn(Optional.empty());
messageService.get(user1.user.id, conversation.id, Pageable.unpaged());
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
import java.util.List;
public class ConversationDto {
public Long id;
public String chatName;
public Boolean hidden;
public List<UserDto> users;
public ConversationDto() {
}
public ConversationDto(Long id, String chatName, Boolean hidden, List<UserDto> users) {
this.id = id;
this.chatName = chatName;
this.hidden = hidden;
this.users = users;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.InvalidEntityException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
public interface PasswordRecoveryController {
/**
* Request password recovery using specified in user info mail
*
* @param login user login
* @throws AuthenticationException on invalid @param login
* @throws NoSuchEntityException if mail is not specified
*/
// TODO: eager mail verification
void requestMail(String login) throws AuthenticationException, NoSuchEntityException, InvalidEntityException;
/**
* Request password recovery using specified in user info phone number
*
* @param login user login
* @throws AuthenticationException on invalid @param login
* @throws NoSuchEntityException if phone number is not specified
*/
//TODO: eager mobile verification
void requestPhone(String login) throws AuthenticationException, NoSuchEntityException, InvalidEntityException;
/**
* Sets new password using email token received using `requestMail()` method
*
* @param token received mail token
* @param newPassword <PASSWORD>
* @throws AuthenticationException on invalid @param token
* @throws InvalidEntityException if password is invalid
*/
void changePasswordMail(String token, String newPassword) throws AuthenticationException, InvalidEntityException;
/**
* Sets new password using code received using `requestPhone()` method
*
* @param code received phone code
* @param newPassword <PASSWORD>
* @throws AuthenticationException on invalid @param code
* @throws InvalidEntityException if password is invalid
*/
void changePasswordPhone(String code, String newPassword) throws AuthenticationException, InvalidEntityException;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto.action;
import com.gmail.ivanjermakov1.messenger.dto.MessageDto;
public class MessageEditAction extends Action {
public MessageDto message;
public MessageEditAction() {
type = Type.MESSAGE_EDIT;
}
public MessageEditAction(MessageDto message) {
this();
this.message = message;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.entity;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.time.LocalDate;
/**
* Entity representing file attached to a certain message
*/
@Entity
@Access(AccessType.FIELD)
@Table(name = "document")
public class Document {
/**
* Document id
*/
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
/**
* Owner user of a document
*/
@ManyToOne
@JoinColumn(name = "user_id")
public User user;
/**
* Static resource path to a document
*/
@Column(name = "path")
public String path;
/**
* Date of a document upload
*/
@Column(name = "uploaded")
public LocalDate uploaded;
public Document() {
}
public Document(User user, String path, LocalDate uploaded) {
this.user = user;
this.path = path;
this.uploaded = uploaded;
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Message} from '../../../dto/Message';
import {User} from '../../../dto/User';
import {FILE_URL} from '../../../../../globals';
import {ImageService} from '../../../service/image.service';
import {ImageCompressionMode} from '../../../dto/enum/ImageCompressionMode';
import {Document} from '../../../dto/Document';
import {Image} from '../../../dto/Image';
import {MessageImage} from '../../../dto/local/MessageImage';
@Component({
selector: 'app-message',
templateUrl: './message.component.html',
styleUrls: [
'./message.component.scss',
'./message.component.forwarded.scss'
]
})
export class MessageComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
@Input()
message: Message;
@Input()
isForwarded: boolean;
@Input()
me: User;
@Output()
openProfileEvent = new EventEmitter<User>();
@Output()
openImageEvent = new EventEmitter<MessageImage>();
mine: boolean;
constructor() {
}
ngOnInit() {
this.mine = this.message.sender.id === this.me.id;
}
openProfile(user: User): void {
this.openProfileEvent.emit(user);
}
openDocument(document: Document) {
window.open(FILE_URL + document.path, '_blank');
}
openImage(image: Image) {
let messageImage = new MessageImage();
messageImage.image = image;
messageImage.message = this.message;
this.openImageEvent.emit(messageImage);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {API_URL} from '../../../globals';
import {Observable} from 'rxjs';
import {Avatar} from '../dto/Avatar';
@Injectable({
providedIn: 'root'
})
export class AvatarService {
constructor(private http: HttpClient) {
}
upload(token: string, file): Observable<Avatar> {
const formData = new FormData();
formData.append('avatar', file);
return this.http.post<Avatar>(API_URL + 'avatar/upload', formData, {
headers: {
'Auth-Token': token
}
});
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.integration;
import com.gmail.ivanjermakov1.messenger.controller.ConversationController;
import com.gmail.ivanjermakov1.messenger.controller.MessageController;
import com.gmail.ivanjermakov1.messenger.controller.MessagingController;
import com.gmail.ivanjermakov1.messenger.dto.ConversationDto;
import com.gmail.ivanjermakov1.messenger.dto.MessageDto;
import com.gmail.ivanjermakov1.messenger.dto.NewMessageDto;
import com.gmail.ivanjermakov1.messenger.dto.TestingUser;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.AuthorizationException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.service.TestingService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Arrays;
import java.util.List;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class MessageTest {
@Autowired
private MessageController messageController;
@Autowired
private ConversationController conversationController;
@Autowired
private MessagingController messagingController;
@Autowired
private TestingService testingService;
private TestingUser user1;
private ConversationDto conversationDto;
private MessageDto message1;
private MessageDto message2;
@Before
public void before() throws RegistrationException, AuthenticationException, AuthorizationException {
user1 = testingService.registerUser("Jack");
TestingUser user2 = testingService.registerUser("Ron");
conversationDto = conversationController.create(
user1.user,
user2.user.login
);
message1 = messagingController.sendMessage(
user1.user,
new NewMessageDto(
user1.user.id,
conversationDto.id,
"Hello!"
)
);
message2 = messagingController.sendMessage(
user1.user,
new NewMessageDto(
user1.user.id,
conversationDto.id,
"Hello2!"
)
);
}
@Test
public void shouldGetAllMessagesFromConversation() throws AuthenticationException {
List<MessageDto> messages = messageController.get(
user1.user,
conversationDto.id,
PageRequest.of(0, Integer.MAX_VALUE)
);
Assert.assertEquals(2, messages.size());
}
@Test
public void shouldDeleteAllMessagesFromConversation() throws AuthenticationException {
messageController.delete(
user1.user,
Arrays.asList(message1, message2)
);
List<MessageDto> messages = messageController.get(
user1.user,
conversationDto.id,
PageRequest.of(0, Integer.MAX_VALUE)
);
Assert.assertTrue(messages.isEmpty());
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDateTime;
public class UserDto {
public Long id;
public String login;
public String firstName;
public String lastName;
public AvatarDto avatar;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
public LocalDateTime lastSeen;
public UserDto() {
}
public UserDto(Long id, String login, String firstName, String lastName, AvatarDto avatar, LocalDateTime lastSeen) {
this.id = id;
this.login = login;
this.firstName = firstName;
this.lastName = lastName;
this.avatar = avatar;
this.lastSeen = lastSeen;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.security;
import org.apache.commons.text.CharacterPredicates;
import org.jetbrains.annotations.NotNull;
public class RandomStringGenerator {
private static org.apache.commons.text.RandomStringGenerator randomStringGenerator =
new org.apache.commons.text.RandomStringGenerator.Builder()
.withinRange('0', 'z')
.filteredBy(CharacterPredicates.LETTERS, CharacterPredicates.DIGITS)
.build();
@NotNull
public static String generate(@NotNull Integer length) {
return randomStringGenerator.generate(length);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.entity;
import com.gmail.ivanjermakov1.messenger.dto.enums.MaritalStatus;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import java.time.LocalDate;
/**
* Entity represents user info
*/
@Entity
@Access(AccessType.FIELD)
@Table(name = "user_info")
public class UserInfo {
/**
* User info id
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
/**
* User itself
*/
@OneToOne
@JoinColumn(name = "user_id")
public User user;
/**
* User first name
*/
@Column(name = "first_name")
public String firstName;
/**
* User last name
*/
@Column(name = "last_name")
public String lastName;
/**
* User gender. True is male, False is female
*/
@Column(name = "gender")
public Boolean gender;
/**
* User birth date
*/
@Column(name = "birth_date")
public LocalDate birthDate;
/**
* User marital status
*/
@Enumerated(EnumType.STRING)
@Column(name = "marital_status")
public MaritalStatus maritalStatus;
/**
* User living country
*/
@Column(name = "country")
public String country;
/**
* User living city
*/
@Column(name = "city")
public String city;
/**
* User living location
*/
@Column(name = "location")
public String location;
/**
* User phone number in {@link String} format
*/
@Column(name = "phone_number")
public String phoneNumber;
/**
* User mail in {@link String} format
*/
@Column(name = "mail")
public String mail;
/**
* User place of education
*/
@Column(name = "place_of_education")
public String placeOfEducation;
/**
* User place of work
*/
@Column(name = "place_of_work")
public String placeOfWork;
/**
* User about info
*/
@Column(name = "about")
public String about;
public UserInfo() {
}
public UserInfo(User user, String firstName, String lastName) {
this.user = user;
this.firstName = firstName;
this.lastName = lastName;
}
public UserInfo(User user, String firstName, String lastName, Boolean gender, LocalDate birthDate, MaritalStatus maritalStatus, String country, String city, String location, String phoneNumber, String mail, String placeOfEducation, String placeOfWork, String about) {
this.user = user;
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.birthDate = birthDate;
this.maritalStatus = maritalStatus;
this.country = country;
this.city = city;
this.location = location;
this.phoneNumber = phoneNumber;
this.mail = mail;
this.placeOfEducation = placeOfEducation;
this.placeOfWork = placeOfWork;
this.about = about;
}
}
<file_sep>rootProject.name = 'messenger'
include 'core'
include 'web'
include 'proxy'<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
import com.gmail.ivanjermakov1.messenger.entity.User;
public class TestingUser {
public User user;
public UserDto userDto;
public String token;
public TestingUser() {
}
public TestingUser(User user, UserDto userDto, String token) {
this.user = user;
this.userDto = userDto;
this.token = token;
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_URL} from '../../../globals';
import {NewChat} from '../dto/NewChat';
import {Conversation} from '../dto/Conversation';
@Injectable({
providedIn: 'root'
})
export class ChatService {
constructor(private http: HttpClient) {
}
create(token: string, newChat: NewChat): Observable<Conversation> {
return this.http.post<Conversation>(API_URL + 'chat/create', newChat, {
headers: {
'Auth-Token': token
}
});
}
addMember(token: string, chatId: number, memberId: number): Observable<void> {
return this.http.get<void>(API_URL + 'chat/add', {
headers: {
'Auth-Token': token
},
params: {
'chatId': chatId.toString(),
'memberId': memberId.toString()
}
});
}
addMembers(token: string, chatId: number, memberIds: number[]): Observable<void> {
return this.http.post<void>(API_URL + 'chat/add', memberIds, {
headers: {
'Auth-Token': token
},
params: {
'chatId': chatId.toString(),
}
});
}
kickMember(token: string, chatId: number, memberId: number): Observable<void> {
return this.http.get<void>(API_URL + 'chat/kick', {
headers: {
'Auth-Token': token
},
params: {
'chatId': chatId.toString(),
'memberId': memberId.toString()
}
});
}
delete(token: string, conversationId: number) {
return this.http.get(API_URL + 'chat/delete', {
headers: {
'Auth-Token': token
},
params: {
'id': conversationId.toString()
}
});
}
hide(token: string, conversationId: number) {
return this.http.get(API_URL + 'chat/hide', {
headers: {
'Auth-Token': token
},
params: {
'id': conversationId.toString()
}
});
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.PreviewDto;
import com.gmail.ivanjermakov1.messenger.dto.UserDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.InvalidSearchFormatException;
import com.gmail.ivanjermakov1.messenger.service.SearchService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("search")
@Transactional
public class SearchControllerImpl implements SearchController {
private final SearchService searchService;
@Autowired
public SearchControllerImpl(SearchService searchService) {
this.searchService = searchService;
}
@Override
@GetMapping("conversations")
public List<PreviewDto> searchConversations(@ModelAttribute User user,
@RequestParam("search") String search,
Pageable pageable) {
return searchService.searchConversations(user, search, pageable);
}
@Override
@GetMapping("users")
public List<UserDto> searchUsers(@ModelAttribute User user,
@RequestParam("search") String search,
Pageable pageable) throws InvalidSearchFormatException {
return searchService.searchUsers(search, pageable);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto.enums;
public enum FileType {
IMAGE,
VIDEO,
AVATAR,
DOCUMENT
}
<file_sep>plugins {
id 'java'
id 'org.springframework.boot' version '2.1.1.RELEASE'
// code coverage
id 'jacoco'
id 'com.github.kt3k.coveralls' version '2.8.4'
}
group 'com.gmail.ivanjermakov1'
version '0.3'
sourceCompatibility = 1.8
test {
systemProperties System.properties
systemProperties['user.dir'] = workingDir
}
bootRun {
systemProperties System.properties
}
ext {
springVersion = '2.1.8.RELEASE'
}
jacocoTestReport {
reports {
xml.enabled = true
html.enabled = true
}
}
coveralls {
jacocoReportPath 'build/reports/jacoco/test/jacocoTestReport.xml'
}
dependencies {
compile "org.jetbrains:annotations:16.0.2"
compile "org.springframework.boot:spring-boot-starter-web:$springVersion"
compile "org.springframework.boot:spring-boot-starter-webflux:$springVersion"
compile "org.springframework.boot:spring-boot-starter-data-jpa:$springVersion"
compile "org.springframework.boot:spring-boot-starter-mail:$springVersion"
compile "org.postgresql:postgresql:42.2.4"
compile "dom4j:dom4j:1.6.1"
compile "com.atlassian.commonmark:commonmark:0.12.1"
compile "org.modelmapper:modelmapper:2.3.0"
implementation 'com.github.ivanjermakov:jtrue:0.3.2'
compile "org.apache.commons:commons-io:1.3.2"
compile "org.apache.commons:commons-text:1.6"
compile "javax.mail:mail:1.4"
compile "com.twilio.sdk:twilio:7.35.1"
testCompile "org.springframework.boot:spring-boot-starter-test:$springVersion"
testCompile "io.projectreactor:reactor-test:3.1.0.RELEASE"
testCompile "org.jacoco:org.jacoco.agent:0.8.4"
}<file_sep>import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class BackgroundUnreadService {
private unreadCount = new BehaviorSubject<number>(0);
oUnreadCount = this.unreadCount.asObservable();
constructor() {
}
incrementUnreadCount() {
this.unreadCount.next(this.unreadCount.getValue() + 1);
}
resetUnreadCount() {
this.unreadCount.next(0);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import com.gmail.ivanjermakov1.messenger.dto.enums.FileType;
import com.gmail.ivanjermakov1.messenger.exception.InvalidEntityException;
import com.gmail.ivanjermakov1.messenger.security.RandomStringGenerator;
import com.gmail.ivanjermakov1.messenger.util.ImageCompressionMode;
import com.gmail.ivanjermakov1.messenger.util.ImageCompressor;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
@Service
public class FileUploadService {
private final static Logger LOG = LoggerFactory.getLogger(FileUploadService.class);
@Value("${fileupload.path}")
private String uploadPlaceholder;
public String upload(MultipartFile multipartFile, FileType fileType) throws IOException {
String generatedFilename =
RandomStringGenerator.generate(10) + "." + FilenameUtils.getExtension(multipartFile.getOriginalFilename());
LOG.info("upload [" + fileType + "] \'" + multipartFile.getOriginalFilename() + "\'; size: " + multipartFile.getSize() / 1000 + "KB with name: " + generatedFilename);
new File(uploadPlaceholder + "/" + fileType.toString().toLowerCase()).mkdirs();
String fullFilePath = uploadPlaceholder + "/" + fileType.toString().toLowerCase() + "/" + generatedFilename;
File file = new File(fullFilePath);
if (file.exists()) throw new InvalidEntityException("such file already exists");
multipartFile.transferTo(Paths.get(fullFilePath));
uploadCompressedVersions(multipartFile, fullFilePath);
return fileType.toString().toLowerCase() + "/" + generatedFilename;
}
public void uploadCompressedVersions(MultipartFile multipartFile, String filePath) throws IOException {
String extension = "." + FilenameUtils.getExtension(filePath);
String fileName = FilenameUtils.getBaseName(filePath);
String path = FilenameUtils.getFullPath(filePath);
// so {path}{fileName}.{extension} is {filePath}
ImageCompressor.compress(filePath, path + fileName + "_" + ImageCompressionMode.MEDIUM.getFilePathMark() + extension, .4f);
ImageCompressor.compress(filePath, path + fileName + "_" + ImageCompressionMode.SMALL.getFilePathMark() + extension, .1f);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {API_URL} from '../../../globals';
import {HttpClient} from '@angular/common/http';
import {RegisterUser} from '../dto/RegisterUser';
@Injectable({
providedIn: 'root'
})
export class RegisterService {
constructor(private http: HttpClient) {
}
register(registerUser: RegisterUser) {
return this.http.post(API_URL + 'register', registerUser);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.ConversationDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
public interface ConversationController {
/**
* Create conversation with specified user.
* If specified @param withLogin is user himself then "self-conversation" is created.
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param withLogin login of user to create conversation with
* @return created conversation
*/
// TODO: use withId instead of withLogin to be more consistent
ConversationDto create(User user, String withLogin);
/**
* Hide conversation for calling user and delete all messages sent by him.
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param id id of conversation to delete
* @throws AuthenticationException on invalid @param token
*/
void delete(User user, Long id) throws AuthenticationException;
/**
* Hide conversation from calling user
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param id id of conversation to hide
*/
void hide(User user, Long id);
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.integration;
import com.gmail.ivanjermakov1.messenger.controller.RegistrationController;
import com.gmail.ivanjermakov1.messenger.dto.RegisterUserDto;
import com.gmail.ivanjermakov1.messenger.exception.InvalidEntityException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.google.common.base.Strings;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class PasswordTest {
@Autowired
private RegistrationController registrationController;
@Test(expected = InvalidEntityException.class)
public void shouldThrowException_WithEmptyPassword() throws RegistrationException {
registrationController.register(
new RegisterUserDto("Jack", "Johnson", "jackj", ""));
}
@Test(expected = InvalidEntityException.class)
public void shouldThrowException_WithLessThen8Characters() throws RegistrationException {
registrationController.register(
new RegisterUserDto("Jack", "Johnson", "jackj", Strings.repeat("1", 7)));
}
@Test(expected = InvalidEntityException.class)
public void shouldThrowException_WithMoreThen32Characters() throws RegistrationException {
registrationController.register(
new RegisterUserDto("Jack", "Johnson", "jackj", Strings.repeat("1", 33)));
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.ConversationDto;
import com.gmail.ivanjermakov1.messenger.dto.NewChatDto;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.AuthorizationException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.mapper.ConversationMapper;
import com.gmail.ivanjermakov1.messenger.repository.ConversationRepository;
import com.gmail.ivanjermakov1.messenger.service.ChatService;
import com.gmail.ivanjermakov1.messenger.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequestMapping("chat")
@Transactional
public class ChatControllerImpl implements ChatController {
private final ChatService chatService;
private final UserService userService;
private final ConversationController conversationController;
private final ConversationRepository conversationRepository;
private ConversationMapper conversationMapper;
@Autowired
public ChatControllerImpl(UserService userService, ChatService chatService, ConversationController conversationController, ConversationRepository conversationRepository) {
this.userService = userService;
this.chatService = chatService;
this.conversationController = conversationController;
this.conversationRepository = conversationRepository;
}
@Autowired
public void setConversationMapper(ConversationMapper conversationMapper) {
this.conversationMapper = conversationMapper;
}
@Override
@PostMapping("create")
public ConversationDto create(@ModelAttribute User user,
@RequestBody NewChatDto chat) {
return conversationMapper.with(user).map(chatService.create(user, chat));
}
@Override
@GetMapping("add")
public void addMember(@ModelAttribute User user,
@RequestParam("chatId") Long chatId,
@RequestParam("memberId") Long memberId) throws NoSuchEntityException {
Conversation chat = conversationRepository.findById(chatId)
.orElseThrow(() -> new NoSuchEntityException("no such chat"));
User member = userService.getUser(memberId);
chatService.addMembers(user, chat, new ArrayList<>(Collections.singletonList(member)));
}
@Override
@PostMapping("add")
public void addMembers(@ModelAttribute User user,
@RequestParam("chatId") Long chatId,
@RequestBody List<Long> memberIds) throws NoSuchEntityException {
Conversation chat = conversationRepository.findById(chatId)
.orElseThrow(() -> new NoSuchEntityException("no such chat"));
List<User> members = memberIds
.stream()
.map(userService::getUser)
.collect(Collectors.toList());
chatService.addMembers(user, chat, members);
}
@Override
@GetMapping("kick")
public void kickMember(@ModelAttribute User user,
@RequestParam("chatId") Long chatId,
@RequestParam("memberId") Long memberId) throws AuthorizationException, IllegalStateException {
Conversation chat = conversationRepository.findById(chatId)
.orElseThrow(() -> new NoSuchEntityException("no such chat"));
User member = userService.getUser(memberId);
chatService.kickMember(user, chat, member);
}
@Override
@GetMapping("delete")
public void delete(@ModelAttribute User user,
@RequestParam("id") Long conversationId) throws AuthenticationException {
conversationController.delete(user, conversationId);
}
@Override
@GetMapping("hide")
public void hide(@ModelAttribute User user,
@RequestParam("id") Long id) {
conversationController.hide(user, id);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import com.gmail.ivanjermakov1.messenger.dto.MessageDto;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.entity.Message;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.entity.UserConversation;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.mapper.MessageMapper;
import com.gmail.ivanjermakov1.messenger.repository.MessageRepository;
import com.gmail.ivanjermakov1.messenger.repository.UserConversationRepository;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
@Service
public class MessageService {
private final MessageRepository messageRepository;
private final UserService userService;
private ConversationService conversationService;
private final ImageService imageService;
private final UserConversationRepository userConversationRepository;
private MessageMapper messageMapper;
@Autowired
public MessageService(MessageRepository messageRepository, UserService userService, ImageService imageService, UserConversationRepository userConversationRepository) {
this.messageRepository = messageRepository;
this.userService = userService;
this.imageService = imageService;
this.userConversationRepository = userConversationRepository;
}
@Autowired
public void setConversationService(ConversationService conversationService) {
this.conversationService = conversationService;
}
@Autowired
public void setMessageMapper(MessageMapper messageMapper) {
this.messageMapper = messageMapper;
}
public List<MessageDto> get(@NotNull Long userId, @NotNull Long conversationId, Pageable pageable) {
User user = userService.getUser(userId);
Conversation conversation = conversationService.get(conversationId);
UserConversation userConversation = userConversationRepository.findByUserAndConversation(user, conversation)
.orElseThrow(() -> new NoSuchEntityException("invalid conversation id"));
List<Message> messages = messageRepository.findAllByConversationOrderBySentDesc(
conversation,
PageRequest.of(0, Integer.MAX_VALUE)
);
return messages
.stream()
.filter(m -> !(userConversation.kicked && userConversation.lastRead.isBefore(m.sent)))
.skip(pageable.getOffset())
.limit(pageable.getPageSize())
.map(message -> messageMapper.with(user).map(message))
.collect(Collectors.toList());
}
public void read(User user, Conversation conversation) {
UserConversation userConversation = userConversationRepository.findByUserAndConversation(user, conversation)
.orElseThrow(() -> new NoSuchEntityException("no such user's conversation"));
if (!userConversation.kicked) {
userConversation.lastRead = LocalDateTime.now();
}
}
/**
* Allowed to delete only user-self messages
*
* @param user messages owner
* @param deleteMessages messages which going to be removed
*/
public void delete(User user, List<MessageDto> deleteMessages) {
deleteMessages
.stream()
.map(dto -> messageRepository.getById(dto.id))
.filter(Optional::isPresent)
.map(Optional::get)
.filter(m -> m.sender.id.equals(user.id))
.forEach(this::delete);
}
public void deleteImages(Message message) {
message.images.forEach(i -> imageService.delete(message.sender, i.id));
}
public Message get(Long messageId) {
return messageRepository.getById(messageId)
.orElseThrow(() -> new NoSuchEntityException("no such message"));
}
public void deleteAll(User user, Conversation conversation) {
// TODO: optimize
messageRepository.getAllBySenderAndConversation(user, conversation)
.stream()
.parallel()
.forEach(this::delete);
}
/**
* Delete messages different way then just <code>.delete()</code>. Firstly deleting current message from all over
* forwarded messages (including originally attached images), then deletes itself
*
* @param message message that will be deleted
*/
public void delete(Message message) {
messageRepository.deleteFromForwarded(message.id);
deleteImages(message);
messageRepository.delete(message);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.repository;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.entity.Message;
import com.gmail.ivanjermakov1.messenger.entity.User;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;
public interface MessageRepository extends CrudRepository<Message, Long> {
Optional<Message> getById(Long messageId);
Optional<Message> getTop1ByConversationOrderBySentDesc(Conversation conversation);
List<Message> getAllBySenderAndConversation(User sender, Conversation conversation);
List<Message> findAllByConversationOrderBySentDesc(Conversation conversation, Pageable pageable);
@Query("select count(m) from Message m where m.conversation = :conversation and m.sender <> :user and m.sent > :lastRead")
Integer countUnread(@Param("user") User user, @Param("conversation") Conversation conversation, @Param("lastRead") LocalDateTime lastRead);
@Modifying
@Transactional
@Query(value = "delete from forwarded_message where forwarded_message_id = :id", nativeQuery = true)
void deleteFromForwarded(@Param("id") Long id);
@Modifying
@Transactional
@Query(value = "delete from forwarded_message where parent_message_id = :id", nativeQuery = true)
void deleteForwarded(@Param("id") Long id);
}
<file_sep>import {Directive, HostListener} from '@angular/core';
import {MessagingComponent} from '../component/routed/messaging/messaging.component';
@Directive({selector: '[appMessageSend]'})
export class MessageSendDirective {
constructor(private messagingComponent: MessagingComponent) {
}
@HostListener('document:keypress', ['$event'])
handleKeydown(event) {
if (event.code === 'Enter' && !event.shiftKey) {
if (this.messagingComponent.editingMessage) {
this.messagingComponent.editMessage();
} else {
this.messagingComponent.sendMessage();
}
event.preventDefault();
}
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
public class ChannelDto {
public Long id;
public String name;
public Boolean hidden;
public ChannelDto() {
}
public ChannelDto(Long id, String name, Boolean hidden) {
this.id = id;
this.name = name;
this.hidden = hidden;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.util;
public class Strings {
public static boolean startsWith(String source, String target) {
return target.toLowerCase().startsWith(source.toLowerCase());
}
}
<file_sep>export const API_URL = 'http://localhost:8080/api/';
export const FILE_URL = API_URL + 'file/';
export const MESSAGES_AMOUNT = 20;
export const PREVIEWS_AMOUNT = 20;
export const APP_TITLE = 'Messenger';
export const MINUTES_AS_ONLINE_LIMIT = 2;
<file_sep>import {Component, Input, OnInit} from '@angular/core';
import {FILE_URL} from '../../../../../../globals';
import {Preview} from '../../../../dto/Preview';
import {User} from '../../../../dto/User';
import {MeProvider} from '../../../../provider/me-provider';
import {ImageCompressionMode} from '../../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../../service/image.service';
import {PreviewType} from '../../../../dto/enum/PreviewType';
@Component({
selector: 'app-conversation-preview',
templateUrl: './conversation-preview.component.html',
styleUrls: ['./conversation-preview.component.scss']
})
export class ConversationPreviewComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
readonly PreviewType: typeof PreviewType = PreviewType;
@Input() preview: Preview;
@Input() selected: boolean;
@Input() isOnline: boolean;
me: User;
constructor(private meProvider: MeProvider) {
}
ngOnInit() {
this.meProvider.oMe.subscribe(me => this.me = me);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
import {User} from '../dto/User';
@Injectable({
providedIn: 'root'
})
export class MeProvider {
private me = new BehaviorSubject<User>(null);
oMe = this.me.asObservable();
constructor() {
}
setMe(me: User) {
this.me.next(me);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Service;
@Service
public class HashServiceImpl implements HashService {
@Override
public String getHash(String input) {
return DigestUtils.sha256Hex(input);
}
@Override
public boolean check(String input, String stored) {
return getHash(input).equals(stored);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.entity;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import java.util.List;
/**
* Entity representing conversation
*/
@Entity
@Access(AccessType.FIELD)
@Table(name = "conversation")
public class Conversation {
/**
* Conversation id
*/
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
/**
* If conversation is chat then this field represents its name. Otherwise field is {@code null}
*/
@Column(name = "chat_name")
public String chatName;
/**
* List of intermediate table entities user conversations
*/
@OneToMany(mappedBy = "conversation", cascade = {CascadeType.ALL}, orphanRemoval = true)
public List<UserConversation> userConversations;
/**
* Creator user of conversation
*/
@ManyToOne
@JoinColumn(name = "creator_id")
public User creator;
public Conversation() {
}
public Conversation(String chatName, List<UserConversation> userConversations, User creator) {
this.chatName = chatName;
this.userConversations = userConversations;
this.creator = creator;
}
}
<file_sep>import {Message} from './Message';
import {Image} from './Image';
export class EditMessage {
id: number;
text: string;
forwarded: Message[];
images: Image[];
}
<file_sep>package com.gmail.ivanjermakov1.messenger.util;
import org.apache.commons.io.IOUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Files {
public static MultipartFile multipartFileFromFile(File file) throws IOException {
FileInputStream input = new FileInputStream(file);
return new MockMultipartFile(file.getName(),
file.getName(),
"text/plain",
IOUtils.toByteArray(input)
);
}
}
<file_sep>import {User} from './User';
import {Conversation} from './Conversation';
import {Message} from './Message';
import {PreviewType} from './enum/PreviewType';
import {Avatar} from './Avatar';
export class Preview {
type: PreviewType;
conversation: Conversation;
with: User;
lastMessage: Message;
avatar: Avatar;
unread: number;
kicked: boolean;
}
<file_sep>import {Message} from './Message';
export class MessageAttachments {
forwarded: Message[] = [];
}
<file_sep>import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SoundNotificationService {
constructor() {
}
notify() {
const notificationAudio = new Audio('assets/sound/newmsg.mp3');
let promise = notificationAudio.play();
// required due to browser policy
// described here: https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
if (promise) {
promise.catch(e => {
});
}
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_URL} from '../../../globals';
import {NewImage} from '../dto/NewImage';
import {ImageCompressionMode} from '../dto/enum/ImageCompressionMode';
@Injectable({
providedIn: 'root'
})
export class ImageService {
constructor(private http: HttpClient) {
}
upload(token: string, file): Observable<NewImage> {
const formData = new FormData();
formData.append('image', file);
return this.http.post<NewImage>(API_URL + 'image/upload', formData, {
headers: {
'Auth-Token': token
}
});
}
delete(token: string, imageId: number): Observable<void> {
return this.http.get<void>(API_URL + 'image/delete', {
headers: {
'Auth-Token': token
},
params: {
'imageId': imageId.toString()
}
});
}
static getImagePathByCompressionMode(path: string, compressionMode: ImageCompressionMode): string {
if (compressionMode === ImageCompressionMode.FULL) return path;
const pathName = path.substring(0, path.lastIndexOf('.'));
const extension = path.substring(path.lastIndexOf('.'));
return `${pathName}_${compressionMode.toString()}${extension}`;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
import com.gmail.ivanjermakov1.messenger.dto.enums.PreviewType;
public class PreviewDto {
public PreviewType type;
public ConversationDto conversation;
public ChannelDto channel;
public UserDto with;
public MessageDto lastMessage;
public AvatarDto avatar;
public Integer unread;
public Boolean kicked;
public PreviewDto() {
}
public PreviewDto(PreviewType type, ConversationDto conversation, ChannelDto channel, UserDto with, MessageDto lastMessage, AvatarDto avatar, Integer unread, Boolean kicked) {
this.type = type;
this.conversation = conversation;
this.channel = channel;
this.with = with;
this.lastMessage = lastMessage;
this.avatar = avatar;
this.unread = unread;
this.kicked = kicked;
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {API_URL} from '../../../globals';
import {Observable} from 'rxjs';
import {UserInfo} from '../dto/UserInfo';
@Injectable({
providedIn: 'root'
})
export class UserInfoService {
constructor(private http: HttpClient) {
}
get(token: string, userId: number): Observable<UserInfo> {
return this.http.get<UserInfo>(API_URL + 'info', {
headers: {
'Auth-Token': token
},
params: {
userId: userId.toString()
}
});
}
edit(token: string, userInfo: UserInfo): Observable<UserInfo> {
return this.http.post<UserInfo>(API_URL + 'info', userInfo, {
headers: {
'Auth-Token': token
}
});
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.util;
import org.modelmapper.ModelMapper;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
public class Mappers {
private static ModelMapper modelMapper;
static {
modelMapper = new ModelMapper();
modelMapper
.getConfiguration()
.setFieldMatchingEnabled(true)
.setSkipNullEnabled(true);
}
public static <D, T> D map(T entity, Class<D> outClass) {
return modelMapper.map(entity, outClass);
}
public static <D, T> List<D> mapAll(Collection<T> entities, Class<D> outCLass) {
return entities
.stream()
.map(e -> map(e, outCLass))
.collect(Collectors.toList());
}
}<file_sep>import {Injectable} from '@angular/core';
import {API_URL} from '../../../globals';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {User} from '../dto/User';
@Injectable({
providedIn: 'root'
})
export class AuthService {
constructor(private http: HttpClient) {
}
authenticate(login: string, password: string): Observable<string> {
return this.http.get(API_URL + 'auth', {
params: {'login': login, 'password': <PASSWORD>},
responseType: 'text'
});
}
validate(token: string): Observable<User> {
return this.http.get<User>(API_URL + 'auth/validate', {
headers: {
'Auth-Token': token
}
});
}
logout(token: string) {
return this.http.get<User>(API_URL + 'auth/logout', {
headers: {
'Auth-Token': token
}
});
}
}
<file_sep>import {User} from './User';
export class Image {
id: number;
user: User;
path: string;
uploaded: Date;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
public class NewImageDto {
public String path;
public NewImageDto() {
}
public NewImageDto(String path) {
this.path = path;
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Message} from '../../../../dto/Message';
@Component({
selector: 'app-forwarded-attachment',
templateUrl: './forwarded-attachment.component.html',
styleUrls: [
'./forwarded-attachment.component.scss',
'./../attachment.scss',
]
})
export class ForwardedAttachmentComponent implements OnInit {
@Input() forwarded: Message[];
@Output() removeForwardedAttachmentEvent = new EventEmitter();
constructor() {
}
ngOnInit() {
}
removeForwardedAttachment() {
this.removeForwardedAttachmentEvent.next();
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.util;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;
import java.util.Arrays;
public class Uploads {
public static boolean isSupportedImage(MultipartFile file) {
if (file == null || file.getOriginalFilename() == null) return false;
return Arrays.stream(ImageFileType.values())
.anyMatch(e -> e.toString().toLowerCase().equals(FilenameUtils.getExtension(file.getOriginalFilename()).toLowerCase()));
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {User} from '../../../../dto/User';
import {ImageCompressionMode} from '../../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../../service/image.service';
import {FILE_URL} from '../../../../../../globals';
import {Preview} from '../../../../dto/Preview';
import {PreviewType} from '../../../../dto/enum/PreviewType';
@Component({
selector: 'app-user-preview',
templateUrl: './user-preview.component.html',
styleUrls: ['./user-preview.component.scss']
})
export class UserPreviewComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
readonly PreviewType: typeof PreviewType = PreviewType;
@Input() user: User;
@Input() currentPreview: Preview;
@Output() addToChatEvent = new EventEmitter<User>();
constructor() {
}
ngOnInit() {
}
}
<file_sep>import {Message} from '../Message';
import {Image} from '../Image';
export class MessageImage {
message: Message;
image: Image;
}
<file_sep>import {Message} from './Message';
import {NewImage} from './NewImage';
import {NewDocument} from './NewDocument';
export class NewMessage {
senderId: number;
conversationId: number;
text: string;
forwarded: Message[] = [];
images: NewImage[] = [];
documents: NewDocument[] = [];
}
<file_sep>import {Directive, EventEmitter, HostListener, Output} from '@angular/core';
@Directive({selector: '[appScroll]'})
export class ScrollPositionDirective {
@Output('appScrollTop') scrollTop = new EventEmitter();
@Output('appScrollBottom') scrollBottom = new EventEmitter();
constructor() {
}
@HostListener('scroll', ['$event'])
handleScroll(event) {
if (event.target.scrollTop === 0) this.scrollTop.emit();
if (event.target.scrollTop === event.target.scrollHeight - event.target.clientHeight) this.scrollBottom.emit();
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {NewImage} from '../../../../dto/NewImage';
import {ImageCompressionMode} from '../../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../../service/image.service';
import {FILE_URL} from '../../../../../../globals';
@Component({
selector: 'app-image-attachment',
templateUrl: './image-attachment.component.html',
styleUrls: [
'./image-attachment.component.scss',
'./../attachment.scss',
]
})
export class ImageAttachmentComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
@Input() image: NewImage;
@Output() removeImageAttachment = new EventEmitter();
constructor() {
}
ngOnInit() {
}
remove() {
this.removeImageAttachment.next();
}
}
<file_sep>SELECT setval('avatar_id_seq', (select id from avatar order by id desc limit 1));
SELECT setval('conversation_id_seq', (select id from conversation order by id desc limit 1));
SELECT setval('document_id_seq', (select id from document order by id desc limit 1));
SELECT setval('image_id_seq', (select id from image order by id desc limit 1));
SELECT setval('message_id_seq', (select id from message order by id desc limit 1));
SELECT setval('token_id_seq', (select id from token order by id desc limit 1));
SELECT setval('user_conversation_id_seq', (select id from user_conversation order by id desc limit 1));
SELECT setval('user_id_seq', (select id from "user" order by id desc limit 1));
SELECT setval('user_info_id_seq', (select id from user_info order by id desc limit 1));
SELECT setval('user_online_id_seq', (select id from user_online order by id desc limit 1));<file_sep>export enum PreviewType {
CONVERSATION,
CHAT,
CHANNEL
}
<file_sep>import {Conversation} from '../Conversation';
import {User} from '../User';
export class ConversationReadAction {
conversation: Conversation;
reader: User;
}
<file_sep>import {Component, ElementRef, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import {AppComponent} from '../../../../app.component';
import {TokenProvider} from '../../../../provider/token-provider';
import {ImageService} from '../../../../service/image.service';
import {NewImage} from '../../../../dto/NewImage';
import {Message} from '../../../../dto/Message';
import {NewDocument} from '../../../../dto/NewDocument';
import {DocumentService} from '../../../../service/document.service';
@Component({
selector: 'app-attachments-menu',
templateUrl: './attachments-menu.component.html',
styleUrls: ['./attachments-menu.component.scss']
})
export class AttachmentsMenuComponent implements OnInit {
@Input() editingMessage: Message;
@Output() attachedImages = new EventEmitter<NewImage>();
@Output() attachedDocuments = new EventEmitter<NewDocument>();
@ViewChild('imageInput') imageInput: ElementRef;
@ViewChild('documentInput') documentInput: ElementRef;
visible = false;
private token: string;
constructor(
private app: AppComponent,
private tokenProvider: TokenProvider,
private imageService: ImageService,
private documentService: DocumentService
) {
}
ngOnInit() {
this.app.onLoad(() => {
this.tokenProvider.oToken.subscribe(token => {
this.token = token;
});
});
}
selectImage() {
this.imageInput.nativeElement.click();
}
selectDocument() {
this.documentInput.nativeElement.click();
}
onImageSelect() {
this.visible = false;
Array.from(this.imageInput.nativeElement.files).forEach(f =>
this.imageService.upload(this.token, f).subscribe(newImage => {
this.attachedImages.emit(newImage);
}, err => {
})
);
}
onDocumentSelect() {
this.visible = false;
Array.from(this.documentInput.nativeElement.files).forEach(f =>
this.documentService.upload(this.token, f).subscribe(newDocument => {
this.attachedDocuments.emit(newDocument);
}, err => {
})
);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import java.time.LocalDate;
public class DocumentDto {
public Long id;
public UserDto user;
public String path;
@JsonFormat(pattern = "yyyy-MM-dd")
public LocalDate uploaded;
public DocumentDto() {
}
public DocumentDto(Long id, UserDto user, String path, LocalDate uploaded) {
this.id = id;
this.user = user;
this.path = path;
this.uploaded = uploaded;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import com.twilio.Twilio;
import com.twilio.rest.api.v2010.account.Message;
import com.twilio.type.PhoneNumber;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
@Service
public class SmsServiceImpl implements SmsService {
private final static Logger LOG = LoggerFactory.getLogger(SmsServiceImpl.class);
@Value("${twilio.account.sid}")
private String accountSid;
@Value("${twilio.auth.token}")
private String token;
@Value("${twilio.from.number}")
private String from;
@Override
public void send(String to, String content) {
LOG.debug("sending sms to @" + to);
Twilio.init(accountSid, token);
Message message = Message.creator(new PhoneNumber(from), new PhoneNumber(to), content).create();
LOG.info("sent sms to @" + to);
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {Conversation} from '../../../dto/Conversation';
import {ImageCompressionMode} from '../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../service/image.service';
import {FILE_URL} from '../../../../../globals';
import {PreviewType} from '../../../dto/enum/PreviewType';
import {User} from '../../../dto/User';
@Component({
selector: 'app-chat-info',
templateUrl: './chat-info.component.html',
styleUrls: [
'./chat-info.component.scss',
'./../profile/profile.component.scss',
'./../preview/user-preview/user-preview.component.scss'
]
})
export class ChatInfoComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
readonly PreviewType: typeof PreviewType = PreviewType;
@Input()
chat: Conversation;
@Output()
close = new EventEmitter();
@Output()
openProfile = new EventEmitter<User>();
@Output()
kickMember = new EventEmitter<User>();
constructor() {
}
ngOnInit() {
}
}
<file_sep>import {User} from './User';
import {MaritalStatus} from './enum/MaritalStatus';
import {Avatar} from './Avatar';
export class UserInfo {
user: User;
firstName: string;
lastName: string;
gender: boolean;
birthDate: Date;
maritalStatus: MaritalStatus;
country: string;
city: string;
location: string;
phoneNumber: string;
mail: string;
placeOfEducation: string;
placeOfWork: string;
about: string;
avatars: Avatar[];
newAvatar: File;
}
<file_sep>import {HttpParams} from '@angular/common/http';
import {Direction} from './enum/SortDirection';
export class Pageable {
page: number;
size: number;
sort: string;
direction: Direction;
constructor(page: number, size: number, sort?: string, direction?: Direction) {
this.page = page;
this.size = size;
this.sort = sort;
this.direction = direction;
}
toHttpParams(): HttpParams {
let params = new HttpParams()
.append('page', this.page.toString())
.append('size', this.size.toString());
params = this.sort && this.direction !== null
? params.append('sort', `${this.sort},${Direction[this.direction]}`)
: params;
return params;
}
}
<file_sep>import {Injectable} from '@angular/core';
import {MINUTES_AS_ONLINE_LIMIT} from '../../../globals';
import * as moment from 'moment';
@Injectable({
providedIn: 'root'
})
export class DateService {
constructor() {
}
static lastSeenView(lastSeen: Date): string {
if (!lastSeen) return 'Offline';
const now = moment();
const time = moment(lastSeen);
const minDiff = now.diff(time, 'minutes');
if (minDiff < MINUTES_AS_ONLINE_LIMIT) return 'Online';
if (minDiff < 60) return 'Seen ' + minDiff + ' minutes ago';
const hourDiff = now.diff(time, 'hours');
if (hourDiff < 24) return 'Seen today at ' + time.format('hh:mm');
return hourDiff < 48 ? 'Seen tomorrow at ' + time.format('hh:mm') : time.format('[Seen ] MMM Do [ at ] hh:mm');
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.NewImageDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.AuthorizationException;
import com.gmail.ivanjermakov1.messenger.exception.InvalidEntityException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
public interface ImageController {
/**
* Upload image.
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param image multipart image file
* @return uploaded image
* @throws IOException on server file system error
* @throws InvalidEntityException on upload of invalid file (mostly caused by invalid file extension or file size
* specified in @value {@code spring.servlet.multipart.max-file-size})
*/
NewImageDto upload(User user, MultipartFile image) throws IOException;
/**
* Delete image from certain message
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param imageId image id to delete
* @throws NoSuchEntityException on invalid image id
* @throws AuthorizationException if user is not an a sender of a message image attached to
*/
void delete(User user, Long imageId);
}
<file_sep>package com.gmail.ivanjermakov1.messenger.mapper;
import com.gmail.ivanjermakov1.messenger.dto.AvatarDto;
import com.gmail.ivanjermakov1.messenger.dto.UserInfoDto;
import com.gmail.ivanjermakov1.messenger.entity.UserInfo;
import com.gmail.ivanjermakov1.messenger.service.AvatarService;
import com.gmail.ivanjermakov1.messenger.util.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class UserInfoMapper implements Mapper<UserInfo, UserInfoDto> {
private AvatarService avatarService;
private UserMapper userMapper;
@Autowired
public void setAvatarService(AvatarService avatarService) {
this.avatarService = avatarService;
}
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Override
public UserInfoDto map(UserInfo userInfo) {
UserInfoDto userInfoDto = Mappers.map(userInfo, UserInfoDto.class);
userInfoDto.avatars = Mappers.mapAll(avatarService.getAll(userInfo.user), AvatarDto.class);
userInfoDto.user = userMapper.map(userInfo.user);
return userInfoDto;
}
}
<file_sep>import {User} from './User';
import {Conversation} from './Conversation';
import {Image} from './Image';
import {Document} from './Document';
export class Message {
id: number;
sent: Date;
text: string;
read: boolean;
sender: User;
conversation: Conversation;
forwarded: Message[];
images: Image[];
documents: Document[];
selected = false;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.mapper;
import com.gmail.ivanjermakov1.messenger.dto.DocumentDto;
import com.gmail.ivanjermakov1.messenger.dto.ImageDto;
import com.gmail.ivanjermakov1.messenger.dto.MessageDto;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.entity.Message;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.entity.UserConversation;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.repository.MessageRepository;
import com.gmail.ivanjermakov1.messenger.repository.UserConversationRepository;
import com.gmail.ivanjermakov1.messenger.service.ConversationService;
import com.gmail.ivanjermakov1.messenger.service.UserService;
import com.gmail.ivanjermakov1.messenger.util.Mappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.Collections;
import java.util.stream.Collectors;
@Component
public class MessageMapper implements Mapper<Message, MessageDto>, MapperBuilder<User> {
private UserConversationRepository userConversationRepository;
private ConversationService conversationService;
private ConversationMapper conversationMapper;
private UserService userService;
private UserMapper userMapper;
private MessageRepository messageRepository;
private User user;
@Autowired
public void setUserConversationRepository(UserConversationRepository userConversationRepository) {
this.userConversationRepository = userConversationRepository;
}
@Autowired
public void setConversationService(ConversationService conversationService) {
this.conversationService = conversationService;
}
@Autowired
public void setConversationMapper(ConversationMapper conversationMapper) {
this.conversationMapper = conversationMapper;
}
@Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Autowired
public void setMessageRepository(MessageRepository messageRepository) {
this.messageRepository = messageRepository;
}
@Override
public MessageDto map(Message message) {
if (message.sender.id.equals(0L)) {
return new MessageDto(
message.id,
message.sent,
message.text,
true,
userMapper.map(message.sender),
conversationMapper.with(user).map(message.conversation),
Collections.emptyList(),
Collections.emptyList(),
Collections.emptyList()
);
}
UserConversation userConversation = userConversationRepository.findByUserAndConversation(user, message.conversation)
.orElseThrow(() -> new NoSuchEntityException("no such user's conversation"));
MessageDto messageDto = new MessageDto();
messageDto.id = message.id;
messageDto.sent = message.sent;
boolean read = userConversation.conversation.userConversations
.stream()
.filter(uc -> !uc.user.id.equals(user.id))
.anyMatch(uc -> uc.lastRead.isAfter(message.sent));
if (userConversation.conversation.userConversations.size() == 1) read = true;
messageDto.read = read;
messageDto.text = message.text;
Conversation conversation = conversationService.get(message.conversation.id);
messageDto.conversation = conversationMapper
.with(message.sender)
.map(conversation);
User sender = userService.getUser(message.sender.id);
messageDto.sender = userMapper.map(sender);
messageDto.forwarded = messageRepository.getById(message.id)
.map(m -> m.forwarded)
.orElse(Collections.emptyList())
.stream()
.map(m -> this.with(user).map(m))
.collect(Collectors.toList());
messageDto.images = Mappers.mapAll(
message.images,
ImageDto.class
);
messageDto.documents = Mappers.mapAll(
message.documents,
DocumentDto.class
);
return messageDto;
}
@Override
public Mapper<Message, MessageDto> with(User user) {
this.user = user;
return this;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.mapper;
import com.gmail.ivanjermakov1.messenger.dto.AvatarDto;
import com.gmail.ivanjermakov1.messenger.dto.PreviewDto;
import com.gmail.ivanjermakov1.messenger.dto.enums.PreviewType;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.service.ConversationService;
import com.gmail.ivanjermakov1.messenger.service.MessageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;
@Component
public class PreviewMapper implements Mapper<Conversation, PreviewDto>, MapperBuilder<User> {
@Value("${default.avatar.chat.path}")
private String defaultAvatarChatPath;
private MessageService messageService;
private ConversationService conversationService;
private UserMapper userMapper;
private ConversationMapper conversationMapper;
private User user;
@Autowired
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
@Autowired
public void setConversationService(ConversationService conversationService) {
this.conversationService = conversationService;
}
@Autowired
public void setUserMapper(UserMapper userMapper) {
this.userMapper = userMapper;
}
@Autowired
public void setConversationMapper(ConversationMapper conversationMapper) {
this.conversationMapper = conversationMapper;
}
@Override
public PreviewDto map(Conversation conversation) {
PreviewDto previewDto = new PreviewDto();
previewDto.type = conversation.chatName == null ? PreviewType.CONVERSATION : PreviewType.CHAT;
previewDto.conversation = conversationMapper
.with(user)
.map(conversation);
previewDto.lastMessage = messageService.get(user.id, conversation.id, PageRequest.of(0, 1))
.stream()
.findFirst()
.orElse(null);
if (previewDto.type.equals(PreviewType.CONVERSATION)) {
User with = conversation.userConversations
.stream()
.map(uc -> uc.user)
.filter(u -> !u.id.equals(user.id))
.findFirst()
.orElse(user);
previewDto.with = userMapper.map(with);
}
if (previewDto.type.equals(PreviewType.CONVERSATION)) {
previewDto.avatar = previewDto.with.avatar;
} else {
previewDto.avatar = new AvatarDto(null, defaultAvatarChatPath, null);
}
if (previewDto.type.equals(PreviewType.CHAT)) {
previewDto.kicked = conversation.userConversations
.stream()
.filter(uc -> uc.user.id.equals(user.id))
.findFirst()
.map(uc -> uc.kicked)
.orElse(null);
}
previewDto.unread = conversationService.unreadCount(user, conversation);
return previewDto;
}
@Override
public Mapper<Conversation, PreviewDto> with(User user) {
this.user = user;
return this;
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
@Service
public class MailService {
private final static Logger LOG = LoggerFactory.getLogger(MailService.class);
@Value("${mail.from}")
private String from;
private final JavaMailSender javaMailSender;
@Autowired
public MailService(JavaMailSender javaMailSender) {
this.javaMailSender = javaMailSender;
}
public void send(String to, String subject, String content) {
LOG.info("Sending message to @", to);
SimpleMailMessage message = new SimpleMailMessage();
message.setFrom(from);
message.setTo(to);
message.setSubject(subject);
message.setText(content);
javaMailSender.send(message);
LOG.info("Sent message to @", to);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_URL} from '../../../globals';
import {Preview} from '../dto/Preview';
import {Pageable} from '../dto/Pageable';
@Injectable({
providedIn: 'root'
})
export class PreviewService {
constructor(private http: HttpClient) {
}
all(token: string, pageable: Pageable): Observable<Preview[]> {
return this.http.get<Preview[]>(API_URL + 'preview/all', {
headers: {
'Auth-Token': token
},
params: pageable.toHttpParams()
});
}
get(token: string, conversationId: number): Observable<Preview> {
return this.http.get<Preview>(API_URL + 'preview/get', {
headers: {
'Auth-Token': token
},
params: {
'conversationId': conversationId.toString()
}
});
}
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {RegisterUser} from '../../../dto/RegisterUser';
import {RegisterService} from '../../../service/register.service';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss', './../auth/auth.component.scss']
})
export class RegisterComponent implements OnInit {
registerUser: RegisterUser = new RegisterUser();
passwordConfirmation = '';
constructor(private router: Router,
private registerService: RegisterService) {
}
ngOnInit() {
}
register() {
if (this.registerUser.password === this.passwordConfirmation) {
this.registerService.register(this.registerUser).subscribe(() => {
this.router.navigate(['/auth']);
}, error => {
});
}
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.repository;
import com.gmail.ivanjermakov1.messenger.entity.UserOnline;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;
public interface UserOnlineRepository extends CrudRepository<UserOnline, Long> {
@Query(value = "select * from user_online " +
"where user_id = :userId " +
"order by seen desc " +
"limit 1", nativeQuery = true)
UserOnline lastSeen(@Param("userId") Long userId);
UserOnline findFirstByUserIdOrderBySeenDesc(Long user_id);
@Modifying
@Transactional
@Query(value = "delete from user_online uo where extract(day from now() - uo.seen) >= :days", nativeQuery = true)
void deleteOlderThanDays(@Param("days") Integer onlineLifetimeDays);
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.integration;
import com.gmail.ivanjermakov1.messenger.controller.ConversationController;
import com.gmail.ivanjermakov1.messenger.controller.PreviewController;
import com.gmail.ivanjermakov1.messenger.dto.ConversationDto;
import com.gmail.ivanjermakov1.messenger.dto.PreviewDto;
import com.gmail.ivanjermakov1.messenger.dto.TestingUser;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.AuthorizationException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.service.TestingService;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class ConversationTest {
@Autowired
private ConversationController conversationController;
@Autowired
private PreviewController previewController;
@Autowired
private TestingService testingService;
private TestingUser user1;
private TestingUser user2;
private ConversationDto conversationDto;
@Before
public void before() {
user1 = testingService.registerUser("Jack");
user2 = testingService.registerUser("Ron");
conversationDto = conversationController.create(
user1.user,
user2.user.login
);
}
@Test
public void shouldCreateConversation() throws RegistrationException, AuthenticationException, NoSuchEntityException, AuthorizationException {
Assert.assertNotNull(conversationDto);
Assert.assertEquals(2, conversationDto.users.size());
}
@Test
public void shouldCreateSelfConversation() throws RegistrationException, AuthenticationException, NoSuchEntityException, AuthorizationException {
ConversationDto self = conversationController.create(
user1.user,
user1.user.login
);
Assert.assertNotNull(self);
Assert.assertEquals(1, self.users.size());
}
@Test
public void shouldDeleteConversation() throws RegistrationException, AuthenticationException {
conversationController.delete(user1.user, conversationDto.id);
PreviewDto previewDto = previewController.get(user1.user, conversationDto.id);
Assert.assertTrue(previewDto.conversation.hidden);
}
@Test
public void shouldHideConversation() throws RegistrationException, AuthenticationException {
conversationController.hide(user1.user, conversationDto.id);
PreviewDto previewDto = previewController.get(user1.user, conversationDto.id);
Assert.assertTrue(previewDto.conversation.hidden);
}
@Test
public void shouldCreateHiddenConversation() {
shouldHideConversation();
conversationDto = conversationController.create(
user1.user,
user2.user.login
);
PreviewDto previewDto = previewController.get(user1.user, conversationDto.id);
Assert.assertFalse(previewDto.conversation.hidden);
}
}
<file_sep>import {Component} from '@angular/core';
import {CookieService} from './service/cookie.service';
import {AuthService} from './service/auth.service';
import {ActivatedRoute, NavigationEnd, Router} from '@angular/router';
import {TokenProvider} from './provider/token-provider';
import {MeProvider} from './provider/me-provider';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
isLoaded: boolean = false;
constructor(private cookieService: CookieService,
private authService: AuthService,
private tokenProvider: TokenProvider,
private meProvider: MeProvider,
private router: Router,
private route: ActivatedRoute) {
this.autoLogin();
}
private autoLogin() {
this.router.events.subscribe(
(event: any) => {
if (event instanceof NavigationEnd) {
if (this.router.url === '/auth' || this.router.url === '/register') {
return;
}
const token = this.cookieService.getToken();
if (token !== null) {
this.authService.validate(token).subscribe(
user => {
this.tokenProvider.setToken(token);
this.meProvider.setMe(user);
this.isLoaded = true;
this.route.queryParams.subscribe(params => {
if (params['id']) {
this.router.navigate(['/im'], {queryParams: {id: params['id']}, replaceUrl: true});
} else {
this.router.navigate(['/im'], {replaceUrl: true});
}
});
},
error => {
this.router.navigate(['/auth']);
}
);
} else {
this.router.navigate(['/auth']);
}
}
}
);
}
onLoad(loaded: () => void) {
setTimeout(() => {
if (this.isLoaded) {
loaded();
} else {
this.onLoad(loaded);
}
}, 10);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.exception;
import org.springframework.http.HttpStatus;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
public class WebException {
public Long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
public Integer status;
public String error;
public String message;
public String path;
public WebException(Integer status, String error, String message, String path) {
this.status = status;
this.error = error;
this.message = message;
this.path = path;
}
public static Builder builder() {
return new Builder();
}
public static class Builder {
public HttpStatus status;
public String message;
public String path;
public HttpServletRequest request;
public Exception exception;
public Builder status(HttpStatus status) {
this.status = status;
return this;
}
public Builder message(String message) {
this.message = message;
return this;
}
public Builder path(String path) {
this.path = path;
return this;
}
public Builder request(HttpServletRequest request) {
this.request = request;
return this;
}
public Builder exception(Exception exception) {
this.exception = exception;
return this;
}
public WebException build() {
WebException webException = new WebException(
status.value(),
status.getReasonPhrase(),
message,
path
);
if (request != null) {
webException.path = request.getRequestURI();
}
if (exception != null) {
webException.message = exception.getMessage();
}
return webException;
}
}
}
<file_sep><div class="preview" [ngClass]="{'selected': selected}" *ngIf="preview.lastMessage">
<img class="avatar"
[src]="ImageService.getImagePathByCompressionMode(FILE_URL + preview.avatar.path, ImageCompressionMode.SMALL)"
alt="">
<div class="info">
<div class="text"
*ngIf="!preview.conversation.chatName">{{preview.with.firstName}} {{preview.with.lastName}}</div>
<div class="text" *ngIf="preview.conversation.chatName">{{preview.conversation.chatName}}</div>
<i class="fas fa-circle" *ngIf="isOnline"></i>
</div>
<div class="message-preview">
<div class="from">
{{preview.lastMessage.sender.login === me.login ? 'You' :
preview.lastMessage.sender.firstName}}:
</div>
<div class="text">{{preview.lastMessage.text ? preview.lastMessage.text : 'forwarded messages'}}</div>
</div>
<!--<div class="delete"><i class="fas fa-times"></i></div>-->
<div class="unread-wrapper">
<div class="unread" *ngIf="preview.lastMessage.sender.login !== me.login && preview.unread !== 0">
{{preview.unread}}
</div>
<div class="unread-mine" *ngIf="!preview.lastMessage.read && preview.lastMessage.sender.login === me.login">
<i class="fas fa-circle"></i>
</div>
</div>
<div class="sent">{{preview.lastMessage.sent | date:'HH:mm'}}</div>
</div>
<file_sep>import {User} from './User';
import {MaritalStatus} from './enum/MaritalStatus';
import {Avatar} from './Avatar';
export class EditUserInfo {
user: User;
firstName: string;
lastName: string;
gender: boolean;
birthDate: string;
maritalStatus: MaritalStatus;
country: string;
city: string;
location: string;
phoneNumber: string;
mail: string;
placeOfEducation: string;
placeOfWork: string;
about: string;
avatars: Avatar[];
newAvatar: File;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.exception;
public class NoSuchEntityException extends RuntimeException {
public NoSuchEntityException() {
}
public NoSuchEntityException(String message) {
super(message);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.ConversationDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.mapper.ConversationMapper;
import com.gmail.ivanjermakov1.messenger.service.ConversationService;
import com.gmail.ivanjermakov1.messenger.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("conversation")
@Transactional
public class ConversationControllerImpl implements ConversationController {
private final ConversationService conversationService;
private final UserService userService;
private ConversationMapper conversationMapper;
@Autowired
public ConversationControllerImpl(ConversationService conversationService, UserService userService) {
this.conversationService = conversationService;
this.userService = userService;
}
@Autowired
public void setConversationMapper(ConversationMapper conversationMapper) {
this.conversationMapper = conversationMapper;
}
@Override
@GetMapping("create")
public ConversationDto create(@ModelAttribute User user, @RequestParam("with") String withLogin) {
return conversationMapper
.with(user)
.map(conversationService.create(user, userService.getUser(withLogin)));
}
@Override
@GetMapping("delete")
public void delete(@ModelAttribute User user, @RequestParam("id") Long id) throws AuthenticationException {
conversationService.delete(user, conversationService.get(id));
}
@Override
@GetMapping("hide")
public void hide(@ModelAttribute User user, @RequestParam("id") Long id) {
conversationService.hide(user, conversationService.get(id));
}
}
<file_sep>import {Avatar} from './Avatar';
export class User {
id: number;
login: string;
firstName: string;
lastName: string;
lastSeen: Date;
avatar: Avatar;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.MessageDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import org.springframework.data.domain.Pageable;
import java.util.List;
public interface MessageController {
/**
* Get list of messages.
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param conversationId conversation id to get messages within
* @param pageable pageable
* @return list of messages. Return empty list on empty conversation
*/
List<MessageDto> get(User user, Long conversationId, Pageable pageable);
/**
* Delete list of messages.
* It is possible to delete only user-self messages. If in list are messages from another user they will be ignored.
*
* @param user authenticated user. automatically maps, when {@literal Auth-Token} parameter present
* @param deleteMessages list of messages to delete
*/
void delete(User user, List<MessageDto> deleteMessages);
}
<file_sep>import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AuthService} from '../../../service/auth.service';
import {TokenProvider} from '../../../provider/token-provider';
import {MeProvider} from '../../../provider/me-provider';
import {CookieService} from '../../../service/cookie.service';
@Component({
selector: 'app-auth',
templateUrl: './auth.component.html',
styleUrls: ['./auth.component.scss']
})
export class AuthComponent implements OnInit {
credentials = {
login: null,
password: <PASSWORD>
};
constructor(private authService: AuthService,
private tokenProvider: TokenProvider,
private meProvider: MeProvider,
private cookieService: CookieService,
private router: Router) {
}
ngOnInit() {
}
login() {
this.authService.authenticate(this.credentials.login, this.credentials.password).subscribe(
token => {
this.credentials.password = <PASSWORD>;
this.tokenProvider.setToken(token);
// TODO: refactor so tokenProvider deal with cookies
this.cookieService.setToken(token);
this.authService.validate(token).subscribe(user => {
this.meProvider.setMe(user);
this.router.navigate(['/im'], {replaceUrl: true});
});
},
error => {
this.credentials.password = <PASSWORD>;
return console.error(error);
}
);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_URL} from '../../../globals';
import {EditMessage} from '../dto/EditMessage';
import {Message} from '../dto/Message';
import {NewMessage} from '../dto/NewMessage';
// TODO: deal with 2s lag between EventSource reconnections
@Injectable({
providedIn: 'root'
})
export class MessagingService {
constructor(private http: HttpClient) {
}
getEvents(token: string): Observable<any> {
return new Observable(o => {
const es = new EventSource(API_URL + 'messaging/listen' + '?token=' + token);
es.addEventListener('message', (e: any) => {
o.next(JSON.parse(e.data));
});
});
}
sendMessage(token: string, newMessage: NewMessage): Observable<Message> {
return this.http.post<Message>(API_URL + 'messaging/send', newMessage, {
headers: {
'Auth-Token': token
}
});
}
editMessage(token: string, editMessage: EditMessage): Observable<Message> {
return this.http.post<Message>(API_URL + 'messaging/edit', editMessage, {
headers: {
'Auth-Token': token
}
});
}
}
<file_sep>import {Message} from '../Message';
export class NewMessageAction {
message: Message;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.entity;
import javax.persistence.Access;
import javax.persistence.AccessType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import java.time.LocalDate;
/**
* Entity representing image attached to a certain message
*/
@Entity
@Access(AccessType.FIELD)
@Table(name = "image")
public class Image {
/**
* Image id
*/
@Id
@Column(name = "id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Long id;
/**
* Owner user of an image
*/
@ManyToOne
@JoinColumn(name = "user_id")
public User user;
@ManyToOne
@JoinColumn(name = "message_id")
public Message message;
/**
* Static resource path to an image
*/
@Column(name = "path")
public String path;
/**
* Date of an image upload
*/
@Column(name = "uploaded")
public LocalDate uploaded;
public Image() {
}
public Image(User user, Message message, String path, LocalDate uploaded) {
this.user = user;
this.message = message;
this.path = path;
this.uploaded = uploaded;
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {AppComponent} from '../../../../app.component';
import {TokenProvider} from '../../../../provider/token-provider';
import {ConversationService} from '../../../../service/conversation.service';
import {Preview} from '../../../../dto/Preview';
import {ConfirmService} from '../../../../service/confirm.service';
@Component({
selector: 'app-conversation-menu',
templateUrl: './conversation-menu.component.html',
styleUrls: ['./conversation-menu.component.scss']
})
export class ConversationMenuComponent implements OnInit {
@Input() currentPreview: Preview;
@Output() closeConversation = new EventEmitter();
visible = false;
private token: string;
constructor(
private app: AppComponent,
private tokenProvider: TokenProvider,
private conversationService: ConversationService,
private confirmService: ConfirmService
) {
}
ngOnInit() {
this.app.onLoad(() => {
this.tokenProvider.oToken.subscribe(token => {
this.token = token;
});
});
}
deleteConversation(conversationId: number) {
if (this.confirmService.confirm('All conversation messages will be deleted')) {
this.conversationService.delete(this.token, conversationId).subscribe(() => {
this.visible = false;
this.closeConversation.next();
});
}
}
hideConversation(conversationId: number) {
this.conversationService.hide(this.token, conversationId).subscribe(() => {
this.visible = false;
this.closeConversation.next();
});
}
}
<file_sep>import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {AppRoutingModule} from './app-routing.module';
import {AppComponent} from './app.component';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
import {AutosizeModule} from 'ngx-autosize';
import {ArraySortPipeAsc, ArraySortPipeDesc} from './pipe/array-sort.pipe';
import {AuthComponent} from './component/routed/auth/auth.component';
import {RegisterComponent} from './component/routed/register/register.component';
import {ImageAttachmentComponent} from './component/embedded/attachment/image-attachment/image-attachment.component';
import {ProfileComponent} from './component/embedded/profile/profile.component';
import {ForwardedAttachmentComponent} from './component/embedded/attachment/forwarded-attachment/forwarded-attachment.component';
import {MessageComponent} from './component/embedded/message/message.component';
import {MessagingComponent} from './component/routed/messaging/messaging.component';
import {ConversationPreviewComponent} from './component/embedded/preview/conversation-preview/conversation-preview.component';
import {UserPreviewComponent} from './component/embedded/preview/user-preview/user-preview.component';
import {ProfileMenuComponent} from './component/embedded/menu/profile-menu/profile-menu.component';
import {AttachmentsMenuComponent} from './component/embedded/menu/attachments-menu/attachments-menu.component';
import {ConversationMenuComponent} from './component/embedded/menu/conversation-menu/conversation-menu.component';
import {MessageSendDirective} from './directive/message-send.directive';
import {ScrollPositionDirective} from './directive/scroll-position.directive';
import { DocumentAttachmentComponent } from './component/embedded/attachment/document-attachment/document-attachment.component';
import { ImagePreviewComponent } from './component/embedded/image-preview/image-preview.component';
import { ChatInfoComponent } from './component/embedded/chat-info/chat-info.component';
@NgModule({
declarations: [
AppComponent,
AuthComponent,
RegisterComponent,
MessagingComponent,
MessageComponent,
MessageSendDirective,
ScrollPositionDirective,
ArraySortPipeAsc,
ArraySortPipeDesc,
ForwardedAttachmentComponent,
ProfileComponent,
ImageAttachmentComponent,
ConversationPreviewComponent,
UserPreviewComponent,
ProfileMenuComponent,
AttachmentsMenuComponent,
ConversationMenuComponent,
DocumentAttachmentComponent,
ImagePreviewComponent,
ChatInfoComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
AutosizeModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule {
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {FILE_URL} from '../../../../../../globals';
import {NewDocument} from '../../../../dto/NewDocument';
@Component({
selector: 'app-document-attachment',
templateUrl: './document-attachment.component.html',
styleUrls: [
'./document-attachment.component.scss',
'./../attachment.scss',]
})
export class DocumentAttachmentComponent implements OnInit {
readonly FILE_URL = FILE_URL;
@Input() document: NewDocument;
@Output() removeDocumentAttachment = new EventEmitter();
constructor() {
}
ngOnInit() {
}
remove() {
this.removeDocumentAttachment.next();
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.repository;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.entity.UserInfo;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserInfoRepository extends CrudRepository<UserInfo, Long> {
Optional<UserInfo> findByUser(User user);
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import com.gmail.ivanjermakov1.messenger.dto.NewDocumentDto;
import com.gmail.ivanjermakov1.messenger.dto.enums.FileType;
import com.gmail.ivanjermakov1.messenger.entity.Document;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.exception.AuthorizationException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.repository.DocumentRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@Service
public class DocumentService {
private final FileUploadService fileUploadService;
private final DocumentRepository documentRepository;
@Autowired
public DocumentService(FileUploadService fileUploadService, DocumentRepository documentRepository) {
this.fileUploadService = fileUploadService;
this.documentRepository = documentRepository;
}
// TODO: store original document name
public NewDocumentDto upload(MultipartFile documentFile) throws IOException {
return new NewDocumentDto(fileUploadService.upload(documentFile, FileType.DOCUMENT));
}
public void delete(User user, Long documentId) throws AuthorizationException {
Document document = documentRepository.findById(documentId)
.orElseThrow(() -> new NoSuchEntityException("such document does not exist"));
if (!document.user.id.equals(user.id))
throw new AuthorizationException("user can delete only own documents");
documentRepository.delete(document);
}
}
<file_sep># messenger
[](https://travis-ci.com/ivanjermakov/messenger)
[](https://coveralls.io/github/ivanjermakov/messenger?branch=master)
[](https://github.com/ivanjermakov/messenger/releases)
[](https://hitsofcode.com/view/github/ivanjermakov/messenger)
Just a messenger.
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_URL} from '../../../globals';
import {Preview} from '../dto/Preview';
import {User} from '../dto/User';
@Injectable({
providedIn: 'root'
})
export class SearchService {
constructor(private http: HttpClient) {
}
searchConversations(token: string, search: string): Observable<Preview[]> {
return this.http.get<Preview[]>(API_URL + 'search/conversations', {
headers: {
'Auth-Token': token
},
params: {
'search': search
}
});
}
searchUsers(token: string, search: string): Observable<User[]> {
return this.http.get<User[]>(API_URL + 'search/users', {
headers: {
'Auth-Token': token
},
params: {
'search': search
}
});
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.integration;
import com.gmail.ivanjermakov1.messenger.controller.ConversationController;
import com.gmail.ivanjermakov1.messenger.controller.MessagingController;
import com.gmail.ivanjermakov1.messenger.controller.SearchController;
import com.gmail.ivanjermakov1.messenger.dto.ConversationDto;
import com.gmail.ivanjermakov1.messenger.dto.NewMessageDto;
import com.gmail.ivanjermakov1.messenger.dto.PreviewDto;
import com.gmail.ivanjermakov1.messenger.dto.TestingUser;
import com.gmail.ivanjermakov1.messenger.dto.UserDto;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.InvalidEntityException;
import com.gmail.ivanjermakov1.messenger.exception.InvalidSearchFormatException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.service.TestingService;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.PageRequest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class SearchTest {
@Autowired
private SearchController searchController;
@Autowired
private ConversationController conversationController;
@Autowired
private MessagingController messagingController;
@Autowired
private TestingService testingService;
@Test
public void shouldFindUserByLogin() throws RegistrationException, AuthenticationException, InvalidSearchFormatException {
TestingUser user = testingService.registerUser("John");
List<UserDto> searchResult = searchController.searchUsers(
user.user,
"@John",
PageRequest.of(0, Integer.MAX_VALUE)
);
Assert.assertTrue(searchResult
.stream()
.anyMatch(dto -> dto.login.equals(user.user.login))
);
}
@Test(expected = InvalidSearchFormatException.class)
public void shouldThrowException_WithInvalidUserSearch() throws RegistrationException, AuthenticationException, InvalidSearchFormatException {
TestingUser user = testingService.registerUser("John");
searchController.searchUsers(
user.user,
"John",
PageRequest.of(0, Integer.MAX_VALUE)
);
}
@Test(expected = InvalidEntityException.class)
public void shouldFindConversation() throws RegistrationException, AuthenticationException {
TestingUser user1 = testingService.registerUser("Jack");
TestingUser user2 = testingService.registerUser("Ron");
ConversationDto conversationDto = conversationController.create(
user1.user,
user2.user.login
);
NewMessageDto message = new NewMessageDto(
user1.user.id,
conversationDto.id,
"Hello!"
);
// at least one message is required for conversation to be visible
messagingController.sendMessage(user1.user, message);
List<PreviewDto> previews = searchController.searchConversations(
user1.user,
user2.userDto.lastName,
PageRequest.of(0, Integer.MAX_VALUE)
);
Assert.assertEquals(1, previews.size());
Assert.assertEquals(
conversationDto.id,
previews
.stream()
.findFirst()
.orElseThrow(NoSuchEntityException::new)
.conversation.id
);
Assert.assertEquals(
1,
searchController
.searchConversations(
user1.user,
"ron",
PageRequest.of(0, Integer.MAX_VALUE)
)
.size()
);
Assert.assertEquals(
1,
searchController
.searchConversations(
user1.user,
"ro",
PageRequest.of(0, Integer.MAX_VALUE)
)
.size()
);
Assert.assertEquals(
1,
searchController
.searchConversations(
user1.user,
"ron",
PageRequest.of(0, Integer.MAX_VALUE)
)
.size()
);
Assert.assertEquals(
0,
searchController
.searchConversations(
user1.user,
"abcdef",
PageRequest.of(0, Integer.MAX_VALUE)
)
.size()
);
searchController
.searchConversations(
user1.user,
"",
PageRequest.of(0, Integer.MAX_VALUE)
);
}
}
<file_sep>import {Component, EventEmitter, HostListener, Input, OnInit, Output} from '@angular/core';
import {Image} from '../../../dto/Image';
import {MessageImage} from '../../../dto/local/MessageImage';
import {ImageCompressionMode} from '../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../service/image.service';
import {FILE_URL} from '../../../../../globals';
import * as moment from 'moment';
import {ConfirmService} from '../../../service/confirm.service';
import {MeProvider} from '../../../provider/me-provider';
import {AppComponent} from '../../../app.component';
import {User} from '../../../dto/User';
@Component({
selector: 'app-image-preview',
templateUrl: './image-preview.component.html',
styleUrls: ['./image-preview.component.scss']
})
export class ImagePreviewComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
@Input()
messageImage: MessageImage;
@Output()
deleteImageEvent = new EventEmitter();
images: Image[];
currentImageIndex: number;
me: User;
@HostListener('document:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (event.code === 'ArrowLeft') {
this.openPrevious();
return;
}
if (event.code === 'ArrowRight') {
this.openNext();
return;
}
}
constructor(
private app: AppComponent,
private meProvider: MeProvider,
private confirmService: ConfirmService,
) {
}
ngOnInit() {
this.app.onLoad(() => {
this.meProvider.oMe.subscribe(me => {
this.me = me;
});
});
this.images = this.messageImage.message.images;
this.currentImageIndex = this.images.findIndex(i => i.id === this.messageImage.image.id);
}
openFullImage() {
window.open(FILE_URL + this.images[this.currentImageIndex].path, '_blank');
}
formatTime(date: Date) {
return moment(date).format('hh:mm');
}
deleteImage() {
if (this.confirmService.confirm('This image will be deleted')) {
this.deleteImageEvent.emit();
}
}
openPrevious() {
if (this.currentImageIndex !== 0) {
this.currentImageIndex--;
}
}
openNext() {
if (this.currentImageIndex !== this.images.length - 1) {
this.currentImageIndex++;
}
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {Observable} from 'rxjs';
import {API_URL} from '../../../globals';
import {Message} from '../dto/Message';
import {Pageable} from '../dto/Pageable';
@Injectable({
providedIn: 'root'
})
export class MessageService {
constructor(private http: HttpClient) {
}
get(token: string, conversationId: number, pageable: Pageable): Observable<Message[]> {
return this.http.get<Message[]>(API_URL + 'message/get', {
headers: {
'Auth-Token': token
},
params: pageable.toHttpParams()
.append('conversationId', conversationId.toString())
});
}
delete(token: string, deleteMessages: Message[]) {
return this.http.post(API_URL + 'message/delete', deleteMessages, {
headers: {
'Auth-Token': token
}
});
}
}
<file_sep>export class Avatar {
id: number;
path: string;
uploaded: Date;
}
<file_sep>import {NgModule} from '@angular/core';
import {RouterModule, Routes} from '@angular/router';
import {AuthComponent} from './component/routed/auth/auth.component';
import {RegisterComponent} from './component/routed/register/register.component';
import {MessagingComponent} from './component/routed/messaging/messaging.component';
const routes: Routes = [
{
path: 'auth',
component: AuthComponent
},
{
path: 'register',
component: RegisterComponent
},
{
path: 'im',
component: MessagingComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule {
}
<file_sep>export class RegisterUser {
firstName: string;
lastName: string;
login: string;
password: string;
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import com.gmail.ivanjermakov1.messenger.dto.PreviewDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.mapper.ConversationMapper;
import com.gmail.ivanjermakov1.messenger.mapper.PreviewMapper;
import com.gmail.ivanjermakov1.messenger.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
@Service
public class PreviewService {
private final ConversationService conversationService;
private final PreviewMapper previewMapper;
@Autowired
public PreviewService(ConversationService conversationService, UserMapper userMapper, MessageService messageService, PreviewMapper previewMapper) {
this.conversationService = conversationService;
this.previewMapper = previewMapper;
}
@Autowired
public void setConversationMapper(ConversationMapper conversationMapper) {
}
public List<PreviewDto> all(User user, Pageable pageable) {
return conversationService.getConversations(user, PageRequest.of(0, Integer.MAX_VALUE))
.stream()
.map(c -> previewMapper.with(user).map(c))
.filter(p -> p.lastMessage != null)
.sorted(Comparator.comparing(p -> p.lastMessage.sent, Comparator.reverseOrder()))
.skip(pageable.getOffset())
.limit(pageable.getPageSize())
.collect(Collectors.toList());
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.repository;
import com.gmail.ivanjermakov1.messenger.entity.Conversation;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;
import java.util.List;
public interface ConversationRepository extends CrudRepository<Conversation, Long> {
@Query("select c from Conversation c join c.userConversations uc join uc.user u on u.id = :id")
List<Conversation> getConversations(@Param("id") Long userId, Pageable pageable);
/**
* TODO: docs
*
* @param userId
* @param search
* @return
*/
@Query(value = "select c.id, c.chat_name, c.creator_id\n" +
"from conversation c\n" +
" join user_conversation uc on uc.conversation_id = c.id\n" +
" join \"user\" u on u.id = uc.user_id\n" +
" join user_info ui on ui.user_id = u.id\n" +
"where u.id <> :id\n" +
" and (\n" +
" lower(u.login) like '%' || lower(:s) || '%' or\n" +
" lower(ui.first_name) like '%' || lower(:s) || '%' or\n" +
" lower(ui.last_name) like '%' || lower(:s) || '%'\n" +
" )", nativeQuery = true)
List<Conversation> findConversationsBySearchQuery(@Param("id") Long userId, @Param("s") String search);
}
<file_sep>package com.gmail.ivanjermakov1.messenger.controller;
import com.gmail.ivanjermakov1.messenger.dto.MessageDto;
import com.gmail.ivanjermakov1.messenger.entity.User;
import com.gmail.ivanjermakov1.messenger.service.MessageService;
import com.gmail.ivanjermakov1.messenger.service.MessagingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("message")
@Transactional
public class MessageControllerImpl implements MessageController {
private final MessageService messageService;
private final MessagingService messagingService;
@Autowired
public MessageControllerImpl(MessageService messageService, MessagingService messagingService) {
this.messageService = messageService;
this.messagingService = messagingService;
}
@Override
@GetMapping("get")
public List<MessageDto> get(@ModelAttribute User user,
@RequestParam("conversationId") Long conversationId,
@PageableDefault(direction = Sort.Direction.DESC, sort = {"sent"}) Pageable pageable) {
messagingService.processConversationRead(user, conversationId);
return messageService.get(user.id, conversationId, pageable);
}
@Override
@PostMapping("delete")
public void delete(@ModelAttribute User user,
@RequestBody List<MessageDto> deleteMessages) {
messageService.delete(user, deleteMessages);
}
}
<file_sep>package com.gmail.ivanjermakov1.messenger.service;
import org.commonmark.parser.Parser;
import org.commonmark.renderer.html.HtmlRenderer;
import org.springframework.stereotype.Service;
@Service
public class MarkdownService {
private final Parser parser = Parser.builder().build();
private final HtmlRenderer renderer = HtmlRenderer.builder().build();
public String format(String plain) {
return renderer.render(parser.parse(plain)).trim();
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output} from '@angular/core';
import {User} from '../../../../dto/User';
import {AppComponent} from '../../../../app.component';
import {MeProvider} from '../../../../provider/me-provider';
import {ImageCompressionMode} from '../../../../dto/enum/ImageCompressionMode';
import {ImageService} from '../../../../service/image.service';
import {FILE_URL} from '../../../../../../globals';
import {Preview} from '../../../../dto/Preview';
import {CookieService} from '../../../../service/cookie.service';
import {Router} from '@angular/router';
@Component({
selector: 'app-profile-menu',
templateUrl: './profile-menu.component.html',
styleUrls: ['./profile-menu.component.scss']
})
export class ProfileMenuComponent implements OnInit {
readonly ImageCompressionMode: typeof ImageCompressionMode = ImageCompressionMode;
readonly ImageService: typeof ImageService = ImageService;
readonly FILE_URL = FILE_URL;
@Input() currentPreview: Preview;
@Output() openProfile = new EventEmitter<User>();
visible = false;
me: User;
constructor(
private app: AppComponent,
private meProvider: MeProvider,
private cookieService: CookieService,
private router: Router,
) {
}
ngOnInit() {
this.app.onLoad(() => {
this.meProvider.oMe.subscribe(me => {
this.me = me;
});
});
}
logout() {
this.cookieService.deleteToken();
location.replace('/');
}
open(me: User) {
this.visible = false;
this.openProfile.next(me);
}
}
<file_sep>import {Injectable} from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class CookieService {
LOCAL_STORAGE_TOKEN_NAME = 'Auth-Token';
constructor() {
}
getToken(): string {
return localStorage.getItem(this.LOCAL_STORAGE_TOKEN_NAME);
}
setToken(token: string) {
localStorage.setItem(this.LOCAL_STORAGE_TOKEN_NAME, token);
}
deleteToken() {
localStorage.removeItem(this.LOCAL_STORAGE_TOKEN_NAME);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {HttpClient} from '@angular/common/http';
import {API_URL} from '../../../globals';
import {Observable} from 'rxjs';
import {Conversation} from '../dto/Conversation';
@Injectable({
providedIn: 'root'
})
export class ConversationService {
constructor(private http: HttpClient) {
}
create(token: string, withLogin: string): Observable<Conversation> {
return this.http.get<Conversation>(API_URL + 'conversation/create', {
headers: {
'Auth-Token': token
},
params: {
'with': withLogin
}
});
}
delete(token: string, conversationId: number) {
return this.http.get(API_URL + 'conversation/delete', {
headers: {
'Auth-Token': token
},
params: {
'id': conversationId.toString()
}
});
}
hide(token: string, conversationId: number) {
return this.http.get(API_URL + 'conversation/hide', {
headers: {
'Auth-Token': token
},
params: {
'id': conversationId.toString()
}
});
}
}
<file_sep>import {Component, EventEmitter, Input, OnInit, Output, ViewChild} from '@angular/core';
import * as moment from 'moment';
import {FILE_URL} from '../../../../../globals';
import {User} from '../../../dto/User';
import {UserInfo} from '../../../dto/UserInfo';
import {MaritalStatus} from '../../../dto/enum/MaritalStatus';
@Component({
selector: 'app-profile',
templateUrl: './profile.component.html',
styleUrls: [
'./profile.component.scss',
'./../../routed/messaging/style/messaging.component.search.scss'
]
})
export class ProfileComponent implements OnInit {
readonly FILE_URL = FILE_URL;
@Input() currentProfile;
@Input() me: User;
@Output() closeProfile = new EventEmitter();
@Output() editProfile = new EventEmitter<UserInfo>();
@ViewChild('fileInput') fileInput;
unloadedAvatar = {
path: null
};
maritalStatuses = Object.keys(MaritalStatus).filter(key => typeof MaritalStatus[key] === 'number');
editable = false;
editView = false;
date = {
days: Array.from({length: 31}, (x, i) => i + 1),
months: Array.from({length: 12}, (x, i) => i + 1),
years: Array.from({length: 100}, (x, i) => moment().year() - i),
};
selectedDate = {
day: null,
month: null,
year: null
};
constructor() {
}
ngOnInit() {
this.editable = this.me.login === this.currentProfile.user.login;
if (this.currentProfile.userInfo.birthDate) {
const dme = this.dme(this.currentProfile.userInfo.birthDate);
this.selectedDate.year = dme[0];
this.selectedDate.month = dme[1];
this.selectedDate.day = dme[2];
}
}
close() {
this.unloadedAvatar.path = null;
this.closeProfile.emit();
}
edit() {
this.currentProfile.userInfo.maritalStatus = this.currentProfile.userInfo.maritalStatus !== 'null' ?
this.currentProfile.userInfo.maritalStatus : null;
if (this.selectedDate.day && this.selectedDate.month && this.selectedDate.year) {
this.currentProfile.userInfo.birthDate = moment([
parseInt(this.selectedDate.year, 10),
// TODO: investigate month number shifting
parseInt(this.monthNumber(this.selectedDate.month), 10) - 2,
parseInt(this.selectedDate.day, 10)
]).format('YYYY-MM-DD');
} else {
this.currentProfile.userInfo.birthDate = null;
}
if (this.fileInput.nativeElement.files[0]) {
this.currentProfile.userInfo.newAvatar = this.fileInput.nativeElement.files[0];
}
this.editProfile.emit(this.currentProfile.userInfo);
this.editView = false;
}
monthName(n: number) {
return moment().month(n - 1).format('MMMM');
}
monthNumber(monthName: string) {
return moment().month(monthName).format('M');
}
dme(date) {
const d = moment(date).toArray().slice(0, 3);
d[1] = d[1] + 1;
return d;
}
selectAvatar() {
this.fileInput.nativeElement.click();
}
onAvatarSelect() {
const reader = new FileReader();
reader.onload = (e: any) => {
this.unloadedAvatar.path = e.target.result;
};
reader.readAsDataURL(this.fileInput.nativeElement.files[0]);
}
}
<file_sep>import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {NewImage} from '../dto/NewImage';
import {API_URL} from '../../../globals';
import {HttpClient} from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DocumentService {
constructor(private http: HttpClient) {
}
upload(token: string, file): Observable<NewImage> {
const formData = new FormData();
formData.append('document', file);
return this.http.post<NewImage>(API_URL + 'document/upload', formData, {
headers: {
'Auth-Token': token
}
});
}
}
<file_sep>export class NewChat {
name: string;
memberIds: number[];
}
<file_sep>export enum ImageCompressionMode {
FULL = 'f',
MEDIUM = 'm',
SMALL = 's'
}
<file_sep>package com.gmail.ivanjermakov1.messenger.test.unit;
import com.gmail.ivanjermakov1.messenger.dto.TestingUser;
import com.gmail.ivanjermakov1.messenger.dto.UserInfoDto;
import com.gmail.ivanjermakov1.messenger.exception.AuthenticationException;
import com.gmail.ivanjermakov1.messenger.exception.NoSuchEntityException;
import com.gmail.ivanjermakov1.messenger.exception.RegistrationException;
import com.gmail.ivanjermakov1.messenger.repository.UserInfoRepository;
import com.gmail.ivanjermakov1.messenger.service.TestingService;
import com.gmail.ivanjermakov1.messenger.service.UserInfoService;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;
import static org.mockito.Mockito.any;
import static org.mockito.Mockito.when;
@SpringBootTest
@RunWith(SpringRunner.class)
@Transactional
public class UserInfoUnitTest {
@InjectMocks
private UserInfoService userInfoService;
@Autowired
private TestingService testingService;
@Mock
private UserInfoRepository userInfoRepository;
private TestingUser user;
@Before
public void before() throws RegistrationException, AuthenticationException {
user = testingService.registerUser("Jack");
}
@Test(expected = NoSuchEntityException.class)
public void shouldThrowException_WhenNoSuchUserInfo() {
when(userInfoRepository.findByUser(any()))
.thenReturn(Optional.empty());
userInfoService.edit(
user.user,
new UserInfoDto(
user.userDto,
"Jack",
"Jack"
)
);
}
}
| fe224b9abf237a9f211ff37dc16a2da5abd16d94 | [
"SQL",
"HTML",
"Markdown",
"Gradle",
"Java",
"TypeScript"
] | 119 | TypeScript | ivanjermakov/messenger | 755b8428585dfe57f114cb20332316f617d8de9d | aa6e944a939e2be79d35cd1abe79d7dcd1ec8ee4 | |
HEAD | <file_sep>
/**
* Some of them should be written as function, such as the option
* of http request. In general, it also means that you can change
* not only properties' value but also their NAMEs. Of course you
* can change all properties' names if nessesary.
*/
exports.default = {
// Request option for login
loginOpt: () => {
return {
url: 'http://acm.hdu.edu.cn/userloginex.php?action=login',
formData: {
// User infomation
username: 'username',
userpass: '<PASSWORD>',
login: 'Sign In'
}
}
},
// Request option for submit
submitOpt: (problemID, code, cookie) => {
return {
url: 'http://acm.hdu.edu.cn/submit.php?action=submit',
headers: {
cookie: cookie
},
formData: {
check: 0,
problemid: problemID,
language: 0,
usercode: code
}
}
},
// Problem ID, 1000-???
problemStart: 1000,
problemEnd: 1010,
// Max async limit when submit codes
asyncLimit: 1,
// Submit interval(:ms)
interval: 20000,
// What's the format of code names
fileNameFormat: (problemID) => `${problemID}.cpp`,
// where are the codes
path: './cpp/'
}<file_sep># autoAC
万能AC机,刷OJ专用。理论上支持所有OJ,只要网站没有验证码之类的提交限制
## 用法
安装依赖
``` bash
npm install
```
将要提交的代码存入程序目录下一个文件夹里(如'cpp')
将config.example.js改名为config.js
按文件中的说明修改配置信息
比如第一个配置项
``` javascript
// Request option for login
loginOpt: () => {
return {
url: 'http://acm.hdu.edu.cn/userloginex.php?action=login',
formData: {
// User infomation
username: 'username',
userpass: '<PASSWORD>',
login: 'Sign In'
}
}
}
```
样例给的是杭电OJ的登录示例
为了灵活把整个登录请求的信息都放在了配置文件里,方便修改。
必须动态返回的配置项写成了函数的形式,比如
``` javascript
// What's the format of code names
fileNameFormat: (problemID) => `${problemID}.cpp`
```
用模板字符串给出一个题号到文件名的映射,找到题号对应的代码文件
启动程序
``` bash
➜ npm run post
```<file_sep>const Acmachine = require('./Acmachine.js').default
const config = require('./config.js').default
new Acmachine(config).run() | 4d66ab3083dc798a6ef4bbb1477cc48bfd49d02d | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | luob5/autoAC | ce9c5ac40915d06b18532e252e2259af4d6e4616 | ca303bf1072fe7455da40b0fc462caa87edee211 | |
refs/heads/master | <repo_name>cp38510/scripts<file_sep>/init_server_with_gpu_mailru/install_all.sh
#!/bin/bash
# This script for install Nvidia drivers and CUDA 10.1 on Centos 7.6, relevant 12.07.2019
sudo -i
yum -y update
yum -y install pciutils
lspci | grep -i nvidia
yum -y install kernel-devel
yum -y group install "Development Tools"
yum -y install kernel-devel-$(uname -r) kernel-headers-$(uname -r)
yum -y install epel-release
yum -y install dkms
yum -y install wget
wget http://us.download.nvidia.com/tesla/418.67/NVIDIA-Linux-x86_64-418.67.run
sh NVIDIA-Linux-x86_64-418.67.run
wget https://developer.nvidia.com/compute/cuda/10.1/Prod/local_installers/cuda-repo-rhel7-10-1-local-10.1.168-418.67-1.0-1.x86_64.rpm
sudo rpm -i cuda-repo-rhel7-10-1-local-10.1.168-418.67-1.0-1.x86_64.rpm
sudo yum -y clean all
sudo yum -y install cuda
echo "export PATH=/usr/local/cuda/bin:$PATH" >> ~/.bashrc
echo "export LD_LIBRARY_PATH=/usr/local/cuda/lib64:$LD_LIBRARY_PATH" >> ~/.bashrc
source ~/.bashrc
echo "Execute: nvidia-smi"
echo "Execute: nvcc --version"
echo "Execute: shutdown -r now"
<file_sep>/tomcat_getting_start.sh
#!/bin/bash
#dz2_tomcat_version 0.1
#
SCRIPT_LOG_PATH="/tmp/deploy_process.log"
GIT_PATH="https://github.com/mnryerasi/java_Test.git"
DIRECTORY_FOR_CLONE_GIT="/tmp/git"
REMOTE_SERVER_USER="root"
REMOTE_SERVER_IP="8.8.8.8"
REMOTE_FILE_SERVER_PATH="/var/lib/tomcat8/webapps/"
#
echo "$(date '+%Y-%m-%d %H:%M:%S') - Start deploy project ${GIT_PATH}" >> ${SCRIPT_LOG_PATH}
#Remove old directory, if it exist
rm -rf ${DIRECTORY_FOR_CLONE_GIT}
#Clone git repository
git clone ${GIT_PATH} ${DIRECTORY_FOR_CLONE_GIT}
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, project don't clone from git" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#Collect application
mvn package -f ${DIRECTORY_FOR_CLONE_GIT}
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, project don't collect in Maven" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#Remove old directory, if it exist
TMP_VAR=$(ls ${DIRECTORY_FOR_CLONE_GIT}/target/*.war |cut -d \/ -f 5 |cut -d \. -f 1)
ssh -o StrictHostKeychecking=no ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP} "rm -rf ${REMOTE_FILE_SERVER_PATH}/${TMP_VAR}*"
#Copy file to remote server
rsync --verbose --archive --compress-level=9 --stats ${DIRECTORY_FOR_CLONE_GIT}/target/*.war ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP}:${REMOTE_FILE_SERVER_PATH}
#Restart tomcat on remote server
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, *.war don't copy to remote server" >> ${SCRIPT_LOG_PATH} && exit 0; fi
ssh -o StrictHostKeychecking=no ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP} "systemctl restart tomcat8"
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, tomcat don't restart on remote server ${REMOTE_SERVER_IP}" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#Test http code project
wget -O /dev/null -a ${DIRECTORY_FOR_CLONE_GIT}/testwget http://${REMOTE_SERVER_IP}:8080/grants/ && grep -c '200 OK' ${DIRECTORY_FOR_CLONE_GIT}/testwget
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, project don't start correct" >> ${SCRIPT_LOG_PATH} && exit 0; fi
echo "$(date '+%Y-%m-%d %H:%M:%S') - Success finish deploy project ${GIT_PATH}" >> ${SCRIPT_LOG_PATH}
<file_sep>/search_ip_addresses_owned_by_AS.sh
#!/bin/bash
#script to search all domain IP-addresses
#
function show_usage {
echo -e "Usage: $0 domain_name\nExample: $0 vk.com\n"
exit 1
}
#
if [ $# -ne 1 ]; then
show_usage
else
#remove temporary files, if they exist
rm -rf /tmp/tmpvartmp777
rm -rf /tmp/tmpvartmp778
#find domain IP-addresses
dig $1 +short > /tmp/tmpvartmp777
#start search all AS(Autonomous System) owned by IP-addresses
while read ipaddr;
do
whois $ipaddr | grep origin | awk {'print $2'} > /tmp/tmpvartmp778
done < /tmp/tmpvartmp777
#sort unique AS(Autonomous System)
ASUNIQ="$(cat /tmp/tmpvartmp778 |sort -u)"
#find all IP-addresses owned by AS(Autonomous System)
whois -h whois.ripe.net -i origin $ASUNIQ | grep route | awk '{print $2}' | grep -ivE "vk|:" |egrep -v '[a-z]|[A-Z]'
#remove temporary files
rm -rf /tmp/tmpvartmp777
rm -rf /tmp/tmpvartmp778
echo "Done!"
fi
<file_sep>/backup/test_backup1.sh
#!/bin/bash
#scrypt #1_version 0.1
#
BACKUPLOG="/tmp/create_file_process.log"
FILE_SERVER_PATH="/tmp/test_backup.log"
#
echo "$(date '+%Y-%m-%d %H:%M:%S') - Start create file ${FILE_SERVER_PATH}" >> ${BACKUPLOG}
head -c 100000000 < /dev/urandom > ${FILE_SERVER_PATH}
if [ $? -ne 0 ];
then
echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR create file ${FILE_SERVER_PATH}" >> ${BACKUPLOG}
else
echo "$(date '+%Y-%m-%d %H:%M:%S') - Success finish create file ${FILE_SERVER_PATH}" >> ${BACKUPLOG}
fi
<file_sep>/backup/backup_site_20180321.sh
#!/bin/bash
#script_backup_some_web_site
#
BACKUPLOG="./backup.log"
SERVER_USER="user"
SERVER_IP="8.8.8.8"
FILE_SERVER_PATH="/var/www/"
FILE_SAVE_PATH="/home/user/backup/site-$(date +%Y%m%d)"
#
DATABASE_NAME="dbname"
DATABASE_USER="dbname"
DATABASE_PASS="<PASSWORD>"
#
#
#Create directory for safe files
mkdir ${FILE_SAVE_PATH}
#Dump database web site on remote server
sshpass -p $1 ssh -o StrictHostKeychecking=no ${SERVER_USER}@${SERVER_IP} "mysqldump -u'${DATABASE_USER}' ${DATABASE_NAME} -p'${DATABASE_PASS}' > dump.sql"
#Copy files web site to local server
sshpass -p $1 rsync --verbose --archive --compress-level=9 --stats ${SERVER_USER}@${SERVER_IP}:${FILE_SERVER_PATH} ${FILE_SAVE_PATH}
#Copy database to local server
sshpass -p $1 rsync --verbose --archive --compress-level=9 --stats ${SERVER_USER}@${SERVER_IP}:/home/${SERVER_USER}/dump.sql ${FILE_SAVE_PATH}
#Remove database frome remote server
sshpass -p $1 ssh -o StrictHostKeychecking=no ${SERVER_USER}@${SERVER_IP} "rm dump.sql"
#Compress web site files
tar -cvzf ${FILE_SAVE_PATH}.tar.gz ${FILE_SAVE_PATH}
#Move to another directory
mv ${FILE_SAVE_PATH}.tar.gz ./site
#Remove files
rm -rf ${FILE_SAVE_PATH}
echo "Done!"
<file_sep>/zimbra/zimbra_remove_messages_v1.sh
#!/bin/bash
#version 0.1
#
ZIMBRA_BIN=/opt/zimbra/bin
MAIL_DOMAIN=mail.ru
#
echo "Enter the mailbox name, use format: <EMAIL>:"
read THEACCOUNT
# Checking the existence of an account
$ZIMBRA_BIN/zmprov -l gaa $MAIL_DOMAIN |grep -xc $THEACCOUNT > /dev/null 2>&1
if [ $? -ne 0 ]; then "echo ERROR, account $THEACCOUNT not found" && exit 0; fi
#
echo "Enter the start date for the message deletion period, in mm/dd/yyyy format. Example: 04/1/2018"
read THEDATE1
if [ -z "$THEDATE1" ]; then echo "ERROR, variable not entered" && exit 0; fi
if [[ ! "$THEDATE1" =~ ^[0-9]{2}/[0-9]{2}/[0-9]{4}$ ]]; then echo "ERROR, invalid date format, use format: mm/dd/yyyy" && exit 0; fi
#
echo "Enter the end date for the message deletion period, in mm/dd/yyyy format. Example: 04/21/2018"
read THEDATE2
if [ -z "$THEDATE2" ]; then echo "ERROR, variable not entered" && exit 0; fi
if [[ ! "$THEDATE2" =~ ^[0-9]{2}/[0-9]{2}/[0-9]{4}$ ]]; then echo "ERROR, invalid date format, use format: mm/dd/yyyy" && exit 0; fi
#
echo "You will now be deleting ALL(Input and output) messages in $THEDATE1 - $THEDATE2 for $THEACCOUNT."
echo "Do you want to continue? (y/N): "
read ADD
#
themagic ()
{
rm -f /tmp/deleteOldMessagesList.txt; touch /tmp/deleteOldMessagesList.txt
rm -f /tmp/process.log; touch /tmp/process.log
for i in `$ZIMBRA_BIN/zmmailbox -z -m $THEACCOUNT search -l 1000 "after:$THEDATE1 before:$THEDATE2" |awk '{print $2}'| sed 1,4d`
do
if [[ $i =~ [-]{1} ]]
then
MESSAGEID=${i#-}
echo "deleteMessage $MESSAGEID" >> /tmp/deleteOldMessagesList.txt
else
echo "deleteConversation $i" >> /tmp/deleteOldMessagesList.txt
fi
done
#
while [ -s /tmp/deleteOldMessagesList.txt ]
do
$ZIMBRA_BIN/zmmailbox -z -m $THEACCOUNT < /tmp/deleteOldMessagesList.txt >> /tmp/process.log
rm -f /tmp/deleteOldMessagesList.txt; touch /tmp/deleteOldMessagesList.txt
for i in `$ZIMBRA_BIN/zmmailbox -z -m $THEACCOUNT search -l 1000 "after:$THEDATE1 before:$THEDATE2" |awk '{print $2}'| sed 1,4d`
do
if [[ $i =~ [-]{1} ]]
then
MESSAGEID=${i#-}
echo "deleteMessage $MESSAGEID" >> /tmp/deleteOldMessagesList.txt
else
echo "deleteConversation $i" >> /tmp/deleteOldMessagesList.txt
fi
done
done
read -p "Completed. Run again for other user (y/n)? " REPLY
if [[ $REPLY =~ ^[Yy]$ ]]; then exec $0; else ADD=n; fi
}
#
while expr "$ADD" : ' *[Yy].*' > /dev/null
do themagic
done
<file_sep>/backup/test_backup2.sh
#!/bin/bash
#scrypt #2_version 0.1
#
BACKUPLOG="/tmp/backup_process.log"
REMOTE_SERVER_USER="root"
REMOTE_SERVER_IP="8.8.8.8"
REMOTE_FILE_SERVER_PATH="/tmp/test_backup.log"
LOCAL_FILE_SAVE_PATH="/home/backup_log/"
LOCAL_FILE_SAVE_NAME="$(date +%d%m%y)-test_backup.log.tar.gz"
#
echo "$(date '+%Y-%m-%d %H:%M:%S') - Start backup file ${REMOTE_FILE_SERVER_PATH})" >> ${BACKUPLOG}
#Check exist file
remote_file=$(ssh -o StrictHostKeychecking=no ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP} test -f ${REMOTE_FILE_SERVER_PATH})
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, file not exist ${REMOTE_FILE_SERVER_PATH}" >> ${BACKUPLOG} && exit 0; fi
#If file exist, clean old files in local directory
find ${LOCAL_FILE_SAVE_PATH} -type f -mtime +7 -exec rm -rf {} \;
#Compression file on remote server
ssh -o StrictHostKeychecking=no ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP} "tar -cvzf ${REMOTE_FILE_SERVER_PATH}.tar.gz ${REMOTE_FILE_SERVER_PATH}"
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, file not compress ${REMOTE_FILE_SERVER_PATH}" >> ${BACKUPLOG} && exit 0; fi
#Copy file from remote server
rsync --verbose --archive --compress-level=9 --stats ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP}:${REMOTE_FILE_SERVER_PATH}.tar.gz ${LOCAL_FILE_SAVE_PATH}${LOCAL_FILE_SAVE_NAME}
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, file not copy ${REMOTE_FILE_SERVER_PATH}" >> ${BACKUPLOG} && exit 0; fi
#Clean remote file
ssh -o StrictHostKeychecking=no ${REMOTE_SERVER_USER}@${REMOTE_SERVER_IP} "truncate -s 0 ${REMOTE_FILE_SERVER_PATH} & rm -rf ${REMOTE_FILE_SERVER_PATH}.tar.gz"
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, file not cleared ${REMOTE_FILE_SERVER_PATH}" >> ${BACKUPLOG} && exit 0; fi
echo "$(date '+%Y-%m-%d %H:%M:%S') - Success finish backup file ${REMOTE_FILE_SERVER_PATH})" >> ${BACKUPLOG}
<file_sep>/deploy_app_to_docker_tomcat.sh
#!/bin/bash
#
#script deploy .war application from git_ver0.1
#
#For deploy we use 3 servers: SERVER_BUILD, SERVER_REGISTRY and SERVER_PROD.
#On server SERVER_BUILD install java and maven, download application from git,
#compile app in maven and build docker container with dockerfile, push to SERVER_REGISTRY.
#On SERVER_REGISTRY we start docker registry and keep container for transfer.
#On SERVER_PROD we only start container from SERVER_REGISTRY.
#
BUILD_IP=
REGISTRY_IP=
PROD_IP=
#
REGISTRY_USER="usertmp"
REGISTRY_PASS="<PASSWORD>"
CONTAINER_NAME="test1"
#
GIT_PATH="https://github.com/cp38510/java_Test.git"
DIRECTORY_FOR_CLONE_GIT="/tmp/git"
#
SCRIPT_LOG_PATH=/tmp/scriptdeploy.log
DATEFORM=$(date '+%Y-%m-%d %H:%M:%S')
#
#
function scriptdeploy {
#############################################################
#check enter servers IP's
if [ -z $BUILD_IP ] ; then echo "You don't set SERVER_BUILD IP" && exit 0; fi
if [ -z $REGISTRY_IP ] ; then echo "You don't set SERVER_REGISTRY IP" && exit 0; fi
if [ -z $PROD_IP ] ; then echo "You don't set SERVER_PROD IP" && exit 0; fi
#remove old RSA key's
ssh-keygen -R $BUILD_IP
ssh-keygen -R $REGISTRY_IP
ssh-keygen -R $PROD_IP
#############################################################
#SERVER_REGISTRY
SSHTMP1="ssh -o StrictHostKeychecking=no root@$REGISTRY_IP"
#update server
$SSHTMP1 "apt-get update > /dev/null"
#install docker
$SSHTMP1 "dpkg -s docker-ce > /dev/null 2>&1"
if [ $? -ne 0 ]; then $SSHTMP1 "curl https://get.docker.com/ | bash > /dev/null 2>&1"; fi
#check install docker
$SSHTMP1 "dpkg -s docker-ce > /dev/null 2>&1"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker didn't install on SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#create directories for docker
$SSHTMP1 "rm -rf /home/docker"
$SSHTMP1 "mkdir -p /home/docker/{data,auth}"
#create authentication docker registry file htpasswd
$SSHTMP1 "rm -rf /home/docker/auth/htpasswd"
$SSHTMP1 "docker run --entrypoint htpasswd registry -Bbn $REGISTRY_USER $REGISTRY_PASS > /home/docker/auth/htpasswd"
#check exist file htpasswd
$SSHTMP1 "test -f /home/docker/auth/htpasswd"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, file /home/docker/auth/htpasswd didn't create on SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#restart docker
$SSHTMP1 "systemctl restart docker"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker didn't restart on SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#stop and remove all runing container
TMPDOCKERLIST=$($SSHTMP1 "docker ps -a" |awk '{print $1}' |grep -vi container |tr '\n' ' ')
$SSHTMP1 "docker stop $TMPDOCKERLIST && docker rm $TMPDOCKERLIST"
#start docker registry container
$SSHTMP1 "docker run -d -p 5000:5000 --restart=always --name registry -v /home/docker/data:/var/lib/registry -v /home/docker/auth:/auth -e \"REGISTRY_AUTH=htpasswd\" -e \"REGISTRY_AUTH_HTPASSWD_REALM=Registry Realm\" -e REGISTRY_AUTH_HTPASSWD_PATH=/auth/htpasswd registry > /dev/null"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker registry container didn't start on SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
echo -e "\e[32m Deploy SERVER_REGISTRY Done \e[0m"
#############################################################
#SERVER_BUILD
SSHTMP2="ssh -o StrictHostKeychecking=no root@$BUILD_IP"
#update server
$SSHTMP2 "apt-get update > /dev/null"
#add java repository
$SSHTMP2 "add-apt-repository ppa:webupd8team/java -y > /dev/null"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, java repository didn't add on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#update server
$SSHTMP2 "apt-get update > /dev/null"
#install java
$SSHTMP2 "dpkg -s oracle-java8-installer > /dev/null 2>&1"
if [ $? -ne 0 ]; then
$SSHTMP2 "echo \"oracle-java8-installer shared/accepted-oracle-license-v1-1 select true\" | sudo debconf-set-selections > /dev/null 2>&1"
$SSHTMP2 "apt-get install -y oracle-java8-installer > /dev/null 2>&1"
fi
#export JAVA_HOME directory
$SSHTMP2 "export JAVA_HOME=/usr/lib/jvm/java-8-oracle/"
#check install java
$SSHTMP2 "dpkg -s oracle-java8-installer > /dev/null 2>&1"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, java didn't install on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#install maven
$SSHTMP2 "dpkg -s maven > /dev/null 2>&1"
if [ $? -ne 0 ]; then $SSHTMP2 "apt-get install maven -y > /dev/null 2>&1"; fi
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, maven didn't install on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#install git
$SSHTMP2 "dpkg -s git > /dev/null 2>&1"
if [ $? -ne 0 ]; then $SSHTMP2 "apt-get install git > /dev/null 2>&1"; fi
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, git didn't install on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#clone git repository
$SSHTMP2 "rm -rf /tmp/git"
$SSHTMP2 "git clone ${GIT_PATH} ${DIRECTORY_FOR_CLONE_GIT} > /dev/null"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, project don't clone from git on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#package application
$SSHTMP2 "mvn package -f /tmp/git > /dev/null"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, application didn't package on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#install docker
$SSHTMP2 "dpkg -s docker-ce > /dev/null 2>&1"
if [ $? -ne 0 ]; then $SSHTMP2 "curl https://get.docker.com/ | bash > /dev/null 2>&1"; fi
#check install docker
$SSHTMP2 "dpkg -s docker-ce > /dev/null 2>&1"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker didn't install on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#create dockerfile
$SSHTMP2 "NAMEWAR=$(find /tmp/git/ -name \"*.war\" -exec basename \{} \;)"
$SSHTMP2 "echo -e \"FROM tomcat:8\nADD ./$NAMEWAR /usr/local/tomcat/webapps/\nEXPOSE 8080\nCMD [\042catalina.sh\042, \042run\042]\" > /tmp/dockerfile"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, dockerfile didn't create on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#docker build container
$SSHTMP2 "cd $DIRECTORY_FOR_CLONE_GIT/target/ && docker build -t $REGISTRY_IP:5000/$CONTAINER_NAME:latest -f /tmp/dockerfile ."
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker container didn't build on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#create file for enable http connect to repository
$SSHTMP2 "echo -e \"{ '\042'insecure-registries'\042':['\042'$REGISTRY_IP:5000'\042'] }\" |tr -d '\047' > /etc/docker/daemon.json"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, file /etc/docker/daemon.json didn't create on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#restart docker
$SSHTMP2 "systemctl restart docker"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker didn't restart on SERVER_BUILD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#login in remote docker registry
$SSHTMP2 "docker login --username=$REGISTRY_USER --password=$REGISTRY_PASS $REGISTRY_IP:5000"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker on SERVER_BUILD didn't login on remote SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#push docker container to remote docker registry
$SSHTMP2 "docker push $REGISTRY_IP:5000/$CONTAINER_NAME:latest"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker container didn't push to remote SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
echo -e "\e[32m Deploy SERVER_BUILD Done \e[0m"
#############################################################
#SERVER_PROD
SSHTMP3="ssh -o StrictHostKeychecking=no root@$PROD_IP"
#update server
$SSHTMP3 "apt-get update > /dev/null"
#install docker
$SSHTMP3 "dpkg -s docker-ce > /dev/null 2>&1"
if [ $? -ne 0 ]; then $SSHTMP3 "curl https://get.docker.com/ | bash > /dev/null 2>&1"; fi
#check install docker
$SSHTMP3 "dpkg -s docker-ce > /dev/null 2>&1"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker didn't install on SERVER_PROD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#create file for enable http connect to repository
$SSHTMP3 "echo -e \"{ '\042'insecure-registries'\042':['\042'$REGISTRY_IP:5000'\042'] }\" |tr -d '\047' > /etc/docker/daemon.json"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, file /etc/docker/daemon.json didn't create on SERVER_PROD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#restart docker
$SSHTMP3 "systemctl restart docker"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker didn't restart on SERVER_PROD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#login in remote docker registry
$SSHTMP3 "docker login --username=$REGISTRY_USER --password=$REGISTRY_PASS $REGISTRY_IP:5000"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker on SERVER_PROD didn't login on remote SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#pull docker container from remote docker registry
$SSHTMP3 "docker pull $REGISTRY_IP:5000/$CONTAINER_NAME:latest"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker container didn't pull from remote SERVER_REGISTRY" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#add tag to container
$SSHTMP3 "docker tag $REGISTRY_IP:5000/$CONTAINER_NAME:latest tomcat/$CONTAINER_NAME:latest"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, tag didn't add to cantainer on SERVER_PROD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#run docker container
$SSHTMP3 "docker run -d -p 8080:8080 --restart=always tomcat/$CONTAINER_NAME:latest"
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, docker container didn't run on SERVER_PROD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
#wait start container, before test
sleep 15s
#Test http code project
rm -rf /tmp/testwget
wget -O /dev/null -a /tmp/testwget http://$PROD_IP:8080/grants/ && grep -c ' 200 ' /tmp/testwget
if [ $? -ne 0 ]; then echo "$DATEFORM - ERROR, project didn't start correct on SERVER_PROD" >> ${SCRIPT_LOG_PATH} && exit 0; fi
rm -rf /tmp/testwget
echo -e "\e[32m Deploy SERVER_PROD Done \e[0m"
echo -e "\e[32m All task's well done! Go http://$PROD_IP:8080/grants/ \e[0m"
}
scriptdeploy
if [ $? -ne 0 ]; then echo "script execution ERROR! Look details ${SCRIPT_LOG_PATH}"; fi
<file_sep>/zimbra/zimbra_remove_messages_v2.sh
#!/bin/bash
#version 0.2
#
ZIMBRA_BIN=/opt/zimbra/bin
MAIL_DOMAIN=mail.ru
USER_LIST=/tmp/userlist.txt
#Enter the start date for the message deletion period, in mm/dd/yyyy format. Example: 04/1/2018
THEDATE1=05/20/2013
#Enter the end date for the message deletion period, in mm/dd/yyyy format. Example: 04/21/2018
THEDATE2=01/01/2017
#
cat $USER_LIST | while read line
do
#
rm -f /tmp/deleteOldMessagesList.txt
touch /tmp/deleteOldMessagesList.txt
rm -f /tmp/process.log
touch /tmp/process.log
for i in `$ZIMBRA_BIN/zmmailbox -z -m $line search -l 1000 "after:$THEDATE1 before:$THEDATE2" |awk '{print $2}'| sed 1,4d`
do
if [[ $i =~ [-]{1} ]]
then
MESSAGEID=${i#-}
echo "deleteMessage $MESSAGEID" >> /tmp/deleteOldMessagesList.txt
else
echo "deleteConversation $i" >> /tmp/deleteOldMessagesList.txt
fi
done
#
while [ -s /tmp/deleteOldMessagesList.txt ]
do
$ZIMBRA_BIN/zmmailbox -z -m $line < /tmp/deleteOldMessagesList.txt >> /tmp/process.log
rm -f /tmp/deleteOldMessagesList.txt
touch /tmp/deleteOldMessagesList.txt
for i in `$ZIMBRA_BIN/zmmailbox -z -m $line search -l 1000 "after:$THEDATE1 before:$THEDATE2" |awk '{print $2}'| sed 1,4d`
do
if [[ $i =~ [-]{1} ]]
then
MESSAGEID=${i#-}
echo "deleteMessage $MESSAGEID" >> /tmp/deleteOldMessagesList.txt
else
echo "deleteConversation $i" >> /tmp/deleteOldMessagesList.txt
fi
done
done
#
echo "Messages in $line delete" >> /tmp/deleteProcess.txt
echo "Done!"
done
<file_sep>/send_notify_abuse_script.sh
#!/bin/bash
#
#script_for_notify_the_owner_IP_about_abuse_v0.1
#
#file with ip - e-mail from WHOIS; example: 8.8.8.8 <EMAIL>
SPAMIPLIST=/tmp/spamiplist.txt
#file with log's abuse
SPAMLOGS=/tmp/logsmailserver.txt
#file for logging this script
SENDMAILLOG=/tmp/sendmail.log
#your text for subject mail
SUBJECTMAIL="SSH brute-force from your server"
#
#create list with uniq email's
cat $SPAMIPLIST |cut -d ' ' -f2|sort -u >/tmp/testtest111
UNIQLIST=/tmp/testtest111
#
while read MAILTO;
do
#create list IPs from mail
MAILIP="$(cat $SPAMIPLIST|grep $MAILTO|cut -d ' ' -f1)"
#change list IPs for search
IPFORGREP="$(echo $MAILIP|tr ' ' '\|')"
#grep logs for message
LOGS="$(cat $SPAMLOGS|egrep "$IPFORGREP")"
#create masseges for mail
MAILTEXT="Hello!\n\nAn attempt to brute-force account passwords(on our server mail.domain.com IP: 8.8.8.8) over SSH/FTP by a machine in your domain or in your network has been detected. Attached are the host who attacks and time / date of activity.\n\nPlease take the necessary action(s) to stop this activity immediately.\nIf you have any questions please reply to this email.\n\nHost attacker IP:\n$MAILIP\n\nLogs attack(time UTC+4):\n$LOGS\n\nSincerely,\nSystem administrator\nSurname Name\ndomain.com"
echo -e "${MAILTEXT}" |mail -aFrom:Surname_Name\<<EMAIL>\> -s "${SUBJECTMAIL}" "${MAILTO}"
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, mail did'n sent to $MAILTO" >> ${SENDMAILLOG}; fi
#
done <"${UNIQLIST}"
<file_sep>/google_cloud_test_settings2.sh
#!/bin/bash
#
#script for setup test server Ubuntu_16 on Google Cloud_version01
#
SCRIPTLOG="/tmp/startscriptlog"
#
timedatectl set-timezone Europe/Moscow
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, timezone don't set Europe/Moscow" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog"; fi
apt-get update -y
#yum update -y
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, system don't update" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog"; fi
apt-get install git less nano nmap -y
yum install git less nano -y
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, applications don't install" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog"; fi
sed -i -e 's/#PermitRootLogin prohibit-password/PermitRootLogin yes/g' -e 's/PermitRootLogin no/PermitRootLogin yes/g' -e 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
#egrep 'PermitRootLogin yes' /etc/ssh/sshd_config && grep 'PasswordAuthentication yes' /etc/ssh/sshd_config
#if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, settings in /etc/ssh/sshd_config don't change" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog"; fi
systemctl restart ssh
systemctl restart sshd
#if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, ssh.service don't restart" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog"; fi
#sed -i '/root/s/\:\*/\:$1$jYePn7UP$1Q6SYWeihp9IWcB3taOeq\//g' /etc/shadow
#grep root /etc/shadow |grep ':$1$jYePn7UP$1Q6SYWeihp9IWcB3taOeq/:'
#if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, root passwd don't change in /etc/shadow" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog"; fi
mkdir -p /root/.ssh
chmod 700 /root/.ssh
echo "ssh-rsa <KEY>2<KEY>EuCzFOhJ9pYBJ<KEY>Mu+d8X97zVk<KEY>jv<KEY>Za<KEY>stm+9VdUREe1PMdb8IAigi<KEY>Im<KEY>mc<KEY>dwMQiXwbBvOfzBDqtQ+Y9N24LHSZYLTAxhAqEyZ60/cJF root" >> /root/.ssh/authorized_keys
chmod 600 /root/.ssh/authorized_keys
echo "Well done!"
<file_sep>/google_cloud_test_settings3.sh
#!/bin/bash
#
#script for setup test server Ubuntu_16 on Google Cloud_version01
#
SCRIPTLOG="/tmp/startscriptlog"
#
timedatectl set-timezone Europe/Moscow
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, timezone don't set Europe/Moscow" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog" && exit 0; fi
apt-get update
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, system don't update" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog" && exit 0; fi
apt-get install git less nano nmap -y
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, applications don't install" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog" && exit 0; fi
sed -i -e 's/PermitRootLogin prohibit-password/PermitRootLogin yes/g' -e 's/PermitRootLogin no/PermitRootLogin yes/g' -e 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
egrep 'PermitRootLogin yes' /etc/ssh/sshd_config && grep 'PasswordAuthentication yes' /etc/ssh/sshd_config
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, settings in /etc/ssh/sshd_config don't change" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog" && exit 0; fi
systemctl restart ssh
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, ssh.service don't restart" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog" && exit 0; fi
sed -i '/root/s/\:\*/\:$1$jYePn7UP$1Q6SYWeihp9IWcB3taOeq\//g' /etc/shadow
grep root /etc/shadow |grep ':$1$jYePn7UP$1Q6SYWeihp9IWcB3taOeq/:'
if [ $? -ne 0 ]; then echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR, root passwd don't change in /etc/shadow" >> ${SCRIPTLOG} && echo "look /tmp/startscriptlog" && exit 0; fi
echo "ssh-rsa <KEY> root" >> /root/.ssh/authorized_keys
echo "Well done!"
| fb2f6799e5bb03a6cd81b61bdb619813b5479b51 | [
"Shell"
] | 12 | Shell | cp38510/scripts | 757bcf16bd39a81f8e996e4948f84c544142f808 | b1b364e6ff0a6e0d7cf374a6eb873d6dd6b2e2de | |
refs/heads/master | <repo_name>ogrisel/manylinux-builds<file_sep>/common_vars.sh
# Useful defines common across builds
IO_PATH="${IO_PATH:-/io}"
# BLAS_SOURCE can be "atlas" or "openblas"
BLAS_SOURCE="${BLAS_SOURCE:-atlas}"
PYTHON_VERSIONS="${PYTHON_VERSIONS:-2.6 2.7 3.3 3.4 3.5}"
OPENBLAS_VERSION="${OPENBLAS_VERSION:-0.2.16}"
# Probably don't want to change the stuff below this line
MANYLINUX_URL=https://nipy.bic.berkeley.edu/manylinux
export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH
export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
function lex_ver {
# Echoes dot-separated version string padded with zeros
# Thus:
# 3.2.1 -> 003002001
# 3 -> 003000000
echo $1 | awk -F "." '{printf "%03d%03d%03d", $1, $2, $3}'
}
function strip_dots {
# Strip "." characters from string
echo $1 | sed "s/\.//g"
}
function build_archive {
local pkg_root=$1
local url=$2
curl -LO $url/${pkg_root}.tar.gz
tar zxf ${pkg_root}.tar.gz
(cd $pkg_root && ./configure && make && make install)
rm -rf $pkg_root
}
function cpython_path {
# Return path to cpython given
# * version (of form "2.7")
# * u_suff ("" or "u" default "u")
local py_ver="${1:-2.7}"
local u_suff="${2:-u}"
# For Python >= 3.3, "u" suffix not meaningful
if [ $(lex_ver $py_ver) -ge $(lex_ver 3.3) ]; then
u_suff=""
fi
local no_dots=$(strip_dots $py_ver)
echo "/opt/python/cp${no_dots}-cp${no_dots}m${u_suff}"
}
function add_manylinux_repo {
cat << EOF > /etc/yum.repos.d/manylinux.repo
[manylinux1-x86_64]
name=wheels for manylinux 64-bit image
baseurl=https://nipy.bic.berkeley.edu/manylinux/rpms
gpgcheck=0
EOF
}
function get_openblas {
# Install openblas
tar xf $LIBRARIES/openblas_${OPENBLAS_VERSION}.tgz
}
function get_atlas {
add_manylinux_repo
yum install -y atlas-devel
}
function get_blas {
if [ "$BLAS_SOURCE" == "atlas" ]; then
get_atlas
elif [ "$BLAS_SOURCE" == "openblas" ]; then
get_openblas
fi
}
function install_auditwheel {
$(cpython_path 3.5)/bin/pip3 install auditwheel
ln -s $(cpython_path 3.5)/bin/auditwheel /usr/local/bin
}
WHEELHOUSE=$IO_PATH/wheelhouse
LIBRARIES=$IO_PATH/libraries
mkdir -p $WHEELHOUSE
mkdir -p $LIBRARIES
install_auditwheel
| 6a8c5a936414747805c2a760de26756323c2cbc0 | [
"Shell"
] | 1 | Shell | ogrisel/manylinux-builds | 92f91a9e1365dc53c3458f156ff2774c3f2ca68b | cae8096b328a1f85b9f16c71fc212c5a30b636d8 | |
refs/heads/master | <file_sep>/*
*
*
Copyright (c) 2007 <NAME>, <NAME>, <NAME>
Software Architecture Group, Hasso Plattner Institute, Potsdam, Germany
http://www.hpi.uni-potsdam.de/swa/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include "VMFrame.h"
#include "VMMethod.h"
#include "VMObject.h"
#include "VMInteger.h"
#include "VMClass.h"
#include "VMSymbol.h"
#include "../vm/Universe.h"
//when doesNotUnderstand or UnknownGlobal is sent, additional stack slots might
//be necessary, as these cases are not taken into account when the stack
//depth is calculated. In that case this method is called.
pVMFrame VMFrame::EmergencyFrameFrom( pVMFrame from, int extraLength ) {
int length = from->GetNumberOfIndexableFields() + extraLength;
int additionalBytes = length * sizeof(pVMObject);
pVMFrame result = new (_HEAP, additionalBytes) VMFrame(length);
result->SetClass(from->GetClass());
//copy arguments, locals and the stack
from->CopyIndexableFieldsTo(result);
//set Frame members
result->SetPreviousFrame(from->GetPreviousFrame());
result->SetMethod(from->GetMethod());
result->SetContext(from->GetContext());
result->stackPointer = from->GetStackPointer();
result->bytecodeIndex = from->bytecodeIndex;
result->localOffset = from->localOffset;
return result;
}
const int VMFrame::VMFrameNumberOfFields = 6;
VMFrame::VMFrame(int size, int nof) : VMArray(size,
nof + VMFrameNumberOfFields) {
_HEAP->StartUninterruptableAllocation();
this->localOffset = _UNIVERSE->NewInteger(0);
this->bytecodeIndex = _UNIVERSE->NewInteger(0);
this->stackPointer = _UNIVERSE->NewInteger(0);
_HEAP->EndUninterruptableAllocation();
}
pVMMethod VMFrame::GetMethod() const {
return this->method;
}
void VMFrame::SetMethod(pVMMethod method) {
this->method = method;
}
bool VMFrame::HasPreviousFrame() const {
return this->previousFrame != nilObject;
}
bool VMFrame::HasContext() const {
return this->context != nilObject;
}
pVMFrame VMFrame::GetContextLevel(int lvl) {
pVMFrame current = this;
while (lvl > 0) {
current = current->GetContext();
--lvl;
}
return current;
}
pVMFrame VMFrame::GetOuterContext() {
pVMFrame current = this;
while (current->HasContext()) {
current = current->GetContext();
}
return current;
}
int VMFrame::RemainingStackSize() const {
// - 1 because the stack pointer points at the top entry,
// so the next entry would be put at stackPointer+1
return this->GetNumberOfIndexableFields() -
stackPointer->GetEmbeddedInteger() - 1;
}
pVMObject VMFrame::Pop() {
int32_t sp = this->stackPointer->GetEmbeddedInteger();
this->stackPointer->SetEmbeddedInteger(sp-1);
return (*this)[sp];
}
void VMFrame::Push(pVMObject obj) {
int32_t sp = this->stackPointer->GetEmbeddedInteger() + 1;
this->stackPointer->SetEmbeddedInteger(sp);
(*this)[sp] = obj;
}
void VMFrame::PrintStack() const {
cout << "SP: " << this->stackPointer->GetEmbeddedInteger() << endl;
for (int i = 0; i < this->GetNumberOfIndexableFields()+1; ++i) {
pVMObject vmo = (*this)[i];
cout << i << ": ";
if (vmo == NULL)
cout << "NULL" << endl;
if (vmo == nilObject)
cout << "NIL_OBJECT" << endl;
if (vmo->GetClass() == NULL)
cout << "VMObject with Class == NULL" << endl;
if (vmo->GetClass() == nilObject)
cout << "VMObject with Class == NIL_OBJECT" << endl;
else
cout << "index: " << i << " object:"
<< vmo->GetClass()->GetName()->GetChars() << endl;
}
}
void VMFrame::ResetStackPointer() {
// arguments are stored in front of local variables
pVMMethod meth = this->GetMethod();
size_t lo = meth->GetNumberOfArguments();
this->localOffset->SetEmbeddedInteger(lo);
// Set the stack pointer to its initial value thereby clearing the stack
size_t numLocals = meth->GetNumberOfLocals();
this->stackPointer->SetEmbeddedInteger(lo + numLocals - 1);
}
int VMFrame::GetBytecodeIndex() const {
return this->bytecodeIndex->GetEmbeddedInteger();
}
void VMFrame::SetBytecodeIndex(int index) {
this->bytecodeIndex->SetEmbeddedInteger(index);
}
pVMObject VMFrame::GetStackElement(int index) const {
int sp = this->stackPointer->GetEmbeddedInteger();
return (*this)[sp-index];
}
void VMFrame::SetStackElement(int index, pVMObject obj) {
int sp = this->stackPointer->GetEmbeddedInteger();
(*this)[sp-index] = obj;
}
pVMObject VMFrame::GetLocal(int index, int contextLevel) {
pVMFrame context = this->GetContextLevel(contextLevel);
int32_t lo = context->localOffset->GetEmbeddedInteger();
return (*context)[lo+index];
}
void VMFrame::SetLocal(int index, int contextLevel, pVMObject value) {
pVMFrame context = this->GetContextLevel(contextLevel);
size_t lo = context->localOffset->GetEmbeddedInteger();
(*context)[lo+index] = value;
}
pVMObject VMFrame::GetArgument(int index, int contextLevel) {
// get the context
pVMFrame context = this->GetContextLevel(contextLevel);
return (*context)[index];
}
void VMFrame::SetArgument(int index, int contextLevel, pVMObject value) {
pVMFrame context = this->GetContextLevel(contextLevel);
(*context)[index] = value;
}
void VMFrame::PrintStackTrace() const {
//TODO
}
int VMFrame::ArgumentStackIndex(int index) const {
pVMMethod meth = this->GetMethod();
return meth->GetNumberOfArguments() - index - 1;
}
void VMFrame::CopyArgumentsFrom(pVMFrame frame) {
// copy arguments from frame:
// - arguments are at the top of the stack of frame.
// - copy them into the argument area of the current frame
pVMMethod meth = this->GetMethod();
int num_args = meth->GetNumberOfArguments();
for(int i=0; i < num_args; ++i) {
pVMObject stackElem = frame->GetStackElement(num_args - 1 - i);
(*this)[i] = stackElem;
}
}
void VMFrame::MarkReferences() {
if (gcfield) return;
VMArray::MarkReferences();
}
<file_sep># SOM++
This project is for SOM++ project on Mac. The target of this project is to enable the 64bit mode works on mac.
Base code is coming from http://www.hpi.uni-potsdam.de/hirschfeld/projects/som/
<file_sep>/*
*
*
Copyright (c) 2007 <NAME>, <NAME>, <NAME>
Software Architecture Group, Hasso Plattner Institute, Potsdam, Germany
http://www.hpi.uni-potsdam.de/swa/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include "Heap.h"
#include "../vmobjects/VMObject.h"
#include "../vmobjects/VMFreeObject.h"
#include "../vm/Universe.h"
/*
* macro for padding - only word-aligned memory must be allocated
*/
#define PAD_BYTES(N) ((sizeof(void*) - ((N) % sizeof(void*))) % sizeof(void*))
Heap* Heap::theHeap = NULL;
Heap* Heap::GetHeap() {
if (!theHeap) {
_UNIVERSE->ErrorExit("Trying to access uninitialized Heap");
}
return theHeap;
}
void Heap::InitializeHeap( int objectSpaceSize ) {
if (theHeap) {
cout << "Warning, reinitializing already initialized Heap, "
<< "all data will be lost!" << endl;
delete theHeap;
}
theHeap = new Heap(objectSpaceSize);
}
void Heap::DestroyHeap() {
if (theHeap) delete theHeap;
}
Heap::Heap(int objectSpaceSize) {
objectSpace = malloc(objectSpaceSize);
if (!objectSpace) {
std::cout << "Failed to allocate the initial "<< objectSpaceSize
<< " bytes for the Heap. Panic.\n" << std::endl;
exit(1);
}
memset(objectSpace, 0, objectSpaceSize);
sizeOfFreeHeap = objectSpaceSize;
this->objectSpaceSize = objectSpaceSize;
this->buffersizeForUninterruptable = (int) (objectSpaceSize * 0.1);
uninterruptableCounter = 0;
numAlloc = 0;
spcAlloc = 0;
numAllocTotal = 0;
freeListStart = (VMFreeObject*) objectSpace;
freeListStart->SetObjectSize(objectSpaceSize);
freeListStart->SetNext(NULL);
freeListStart->SetPrevious(NULL);
freeListStart->SetGCField(-1);
/*freeListStart = (FreeListEntry*) objectSpace;
freeListStart->size = objectSpaceSize;
freeListStart->next = NULL;*/
gc = new GarbageCollector(this);
}
Heap::~Heap() {
if (gcVerbosity > 0) {
cout << "-- Heap statistics --" << endl;
cout << "Total number of allocations: " << numAllocTotal << endl;
cout << "Number of allocations since last collection: "
<< numAlloc << endl;
std::streamsize p = cout.precision();
cout.precision(3);
cout << "Used memory: " << spcAlloc << "/"
<< this->objectSpaceSize << " ("
<< ((double)spcAlloc/(double)this->objectSpaceSize)*100 << "%)" << endl;
cout.precision(p);
gc->PrintGCStat();
}
free(objectSpace);
}
VMObject* Heap::AllocateObject(size_t size) {
//add padding, so objects are word aligned
size_t paddedSize = size + PAD_BYTES(size);
VMObject* vmo = (VMObject*) Allocate(paddedSize);
++numAlloc;
++numAllocTotal;
spcAlloc += paddedSize;
return vmo;
}
void* Heap::Allocate(size_t size) {
if (size == 0) return NULL;
if (size < sizeof(VMObject)) {
//this will never happen, as all allocation is done for VMObjects
return internalAllocate(size);
}
#ifdef HEAPDEBUG
std::cout << "allocating: " << (int)size << "bytes" << std::endl;
#endif
//if there is not enough free heap size and we are not inside an uninterruptable
//section of allocation, start garbage collection
if (sizeOfFreeHeap <= buffersizeForUninterruptable &&
uninterruptableCounter <= 0) {
#ifdef HEAPDEBUG
cout << "Not enough free memory, only: " << sizeOfFreeHeap
<< " bytes left." << endl
<< "Starting Garbage Collection" << endl;
#endif
gc->Collect();
//
//reset allocation stats
//
numAlloc = 0;
spcAlloc = 0;
}
VMObject* result = NULL;
VMFreeObject* cur = freeListStart;
VMFreeObject* last = NULL;
while(cur->GetObjectSize() != size &&
cur->GetObjectSize() < size+sizeof(VMObject) &&
cur->GetNext() != NULL) {
last = cur;
cur = cur->GetNext();
}
if (cur->GetObjectSize() == size) {
//perfect fit
if (cur == freeListStart) {
freeListStart = cur->GetNext();
freeListStart->SetPrevious(NULL);
} else {
last->SetNext(cur->GetNext());
cur->GetNext()->SetPrevious(last);
}
result = cur;
} else if (cur->GetObjectSize() >= size + sizeof(VMFreeObject)) {
//found an entry that is big enough
int oldSize = cur->GetObjectSize();
VMFreeObject* oldNext = cur->GetNext();
result = cur;
VMFreeObject* replaceEntry = (VMFreeObject*) ((uintptr_t)cur + size);
replaceEntry->SetObjectSize(oldSize - size);
replaceEntry->SetGCField(-1);
replaceEntry->SetNext(oldNext);
if (cur == freeListStart) {
freeListStart = replaceEntry;
freeListStart->SetPrevious(NULL);
} else {
last->SetNext(replaceEntry);
replaceEntry->SetPrevious(last);
}
} else {
//problem... might lose data here
cout << "Not enough heap, data loss is possible" << endl;
gc->Collect();
this->numAlloc = 0;
this->spcAlloc = 0;
result = (VMObject*)this->Allocate(size);
}
if (result == NULL) {
cout << "alloc failed" << endl;
PrintFreeList();
_UNIVERSE->ErrorExit("Failed to allocate");
}
memset((void *)result, 0, size);
result->SetObjectSize(size);
this->sizeOfFreeHeap -= size;
return result;
}
void Heap::PrintFreeList() {
VMFreeObject* curEntry = freeListStart;
int i =0;
while (curEntry != NULL) {
cout << "i: " << curEntry->GetObjectSize() << endl;
++i;
curEntry = curEntry->GetNext();
}
}
void Heap::FullGC() {
gc->Collect();
}
void Heap::Free(void* ptr) {
if ( ((uintptr_t)ptr < (uintptr_t) this->objectSpace) &&
((uintptr_t)ptr > (uintptr_t) this->objectSpace + this->objectSpaceSize)) {
internalFree(ptr);
}
}
void Heap::Destroy(VMObject* _object) {
int freedBytes = _object->GetObjectSize();
memset((void *)_object, 0, freedBytes);
VMFreeObject* object = (VMFreeObject*) _object;
//see if there's an adjoining unused object behind this object
VMFreeObject* next = (VMFreeObject*)((uintptr_t)object + (int)freedBytes);
if (next->GetGCField() == -1) {
//yes, there is, so we can join them
object->SetObjectSize(next->GetObjectSize() + freedBytes);
object->SetNext(next->GetNext());
next->GetNext()->SetPrevious(object);
VMFreeObject* previous = next->GetPrevious();
object->SetPrevious(previous);
memset((void *)next, 0, next->GetObjectSize());
} else {
//no, there is not, so we just put the new unused object as the new freeListStart
object->SetObjectSize(freedBytes);
object->SetNext(freeListStart);
freeListStart->SetPrevious(object);
freeListStart = object;
}
//TODO: find a way to merge unused objects that are before this object
}
void Heap::internalFree(void* ptr) {
free(ptr);
}
void* Heap::internalAllocate(size_t size) {
if (size == 0) return NULL;
void* result = malloc(size);
if(!result) {
cout << "Failed to allocate " << size << " Bytes." << endl;
_UNIVERSE->Quit(-1);
}
memset(result, 0, size);
return result;
}
| 3016f68254a8309c4b671e571e063d11087c4b70 | [
"Markdown",
"C++"
] | 3 | C++ | zheddie/SOMpp64 | 3518d7c756ff14ec8806ae50a4922eaaecfeacc8 | e5e984e2a62b05fe21e2b72459021c3f13bc688a | |
refs/heads/master | <repo_name>ismailhozza/fullstackopen-part1<file_sep>/src/index_osa1.js
import React from 'react';
import ReactDOM from 'react-dom';
const Header = () => <h1>Anna palautetta</h1>
const Button = ({handleClick, text}) => <button onClick={handleClick}>{text}</button>
const Statistic = ({label, value, children}) => <tr><td>{label}</td><td>{value} {children}</td></tr>
const Statistics = ({hyva, neutraali, huono, keskiarvo, positiivisia}) => {
if(hyva+neutraali+huono===0) {
return (
<div>
<br/>
<em>ei yhtään palautetta annettu</em>
</div>
)
}
return (
<div>
<h1>statistiikka</h1>
<table>
<tbody>
<Statistic label="hyvä" value={hyva}/>
<Statistic label="neutraali" value={neutraali}/>
<Statistic label="huono" value={huono}/>
<Statistic label="keskiarvo" value={keskiarvo}/>
<Statistic label="positiivisia" value={positiivisia}>%</Statistic>
</tbody>
</table>
</div>
)
}
class App extends React.Component {
constructor() {
super();
this.state = {
hyva: 0,
neutraali: 0,
huono: 0
}
}
hyva = () => {
this.setState({ hyva: this.state.hyva + 1 })
}
neutraali = () => {
this.setState({ neutraali: this.state.neutraali + 1 })
}
huono = () => {
this.setState({ huono: this.state.huono + 1 })
}
asetaPalaute = (kentta) => {
return () => {
let state = {};
state[kentta] = this.state[kentta] + 1;
this.setState(state)
}
}
positiivisia = () => {
let val = this.state.hyva/(
this.state.hyva
+this.state.neutraali
+this.state.huono);
val = val || 0;
return Math.round(val * 10000) / 100;
}
keskiarvo = () => {
let val = (this.state.hyva-this.state.huono)/(
this.state.hyva
+this.state.neutraali
+this.state.huono);
val = val || 0;
return Math.round(val * 10) / 10;
}
render() {
return (
<div>
<Header />
<Button handleClick={this.asetaPalaute('hyva')} text="hyvä"/>
<Button handleClick={this.asetaPalaute('neutraali')} text="neutraali"/>
<Button handleClick={this.asetaPalaute('huono')} text="huono"/>
<Statistics
hyva={this.state.hyva}
neutraali={this.state.neutraali}
huono={this.state.huono}
keskiarvo={this.keskiarvo()}
positiivisia={this.positiivisia()}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'));
| fc7a82fec60e0a07bffaa5c4dd427034b2480e3b | [
"JavaScript"
] | 1 | JavaScript | ismailhozza/fullstackopen-part1 | 5f70d9e24efe3214a4b8ddfd8dcaccf97e4704c7 | 494f39f4560f46c7f39cfa116e0431585f8f3596 | |
refs/heads/master | <repo_name>alskflsjoon/c_programing_power_upgrade<file_sep>/c_programing_power_upgrade/sec01.c
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
void question1(){
printf("[문자, 정수, 실수, 문자열]의 폼으로 입력: ");
char a;
int b;
float c;
char d[10];
scanf("%c, %d, %f, %s", &a, &b, &c, d);
printf("입력된 데이터 출력 %c, %d, %f, %s", a, b, c, d);
}
void question2() {
char string[100];
puts("hello", stdout);
printf("문자열 입력: ");
gets(string);
printf("입력된 문자열: %s", string);
}
void question3() {
int a = 0;
int b = 0;
fputs("두 수를 16진수로 입력: ", stdout);
scanf("%x %x", &a, &b);
//scanf("%x, %x", a, b);
printf("연산 결과 8진수: %o\n", a + b);
printf("연산 결과 10진수: %d\n", a + b);
printf("연산 결과 16진수: %x\n", a + b);
}
void question4() {
char c;
int count = 0;
while (1) {
fputs("Data input (Ctrl+Z to exit): ",stdout);
c = getchar();
if (c == EOF) {
break;
}
count++;
if (getchar() == '\n')
continue;
}
printf("\n입력된 문자의 수: %d", count);
}
void question4_2() {
char input = 0;;
int a = 1;
int result = 0;
while (1) {
fputs("Data input (Ctrl+Z to exit): ", stdout);
a = scanf("%d", &input);
if (feof(stdin)) {
printf("a: %d, input: %d\n", a, input);
break;
}
printf("a: %d, input: %d\n", a, input);
result += input;
}
printf("총 합: %d", result);
}
int main(void) {
//int a=0;
//printf("%d", scanf("%d", &a));
question4_2();
} | ef9299b2e65da38da14f19c4c83f7668a3476586 | [
"C"
] | 1 | C | alskflsjoon/c_programing_power_upgrade | 30d73b9dbf3f70ce77921de31da43907487a93c2 | 706d94aebb1bd0a742ad08f9abddab3b5df0202b | |
refs/heads/master | <repo_name>by-ui/by-ui<file_sep>/src/components/dropdown-menu/index.ts
import DropdownMenu from '../dropdown/src/dropdown-menu.vue'
Object.defineProperty(DropdownMenu, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-dropdown-menu', DropdownMenu);
}
})
export default DropdownMenu;
<file_sep>/build/config/env.ts
// 分环境打包配置
const remain = JSON.parse(process.env.npm_config_argv || '').remain;
const host = remain.length ? remain[0].replace(/^--/, '') : 'default';
const domain = process.env.DOMAIN;
const customize = process.env.CUSTOMIZE || false;
export default {
host,
domain,
customize
}
<file_sep>/src/components/menu-sub/index.ts
import MenuSub from '../menu/src/menu-sub.vue'
Object.defineProperty(MenuSub, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-menu-sub', MenuSub);
}
})
export default MenuSub
<file_sep>/src/components/notification/model.ts
export class notificationOption {
title: string;
content: string;
duration: number;
type: string;
show: boolean;
constructor(title: string, content: string, duration: number = 4000, type: string = '', show: boolean = true) {
this.title = title;
this.content = content;
this.duration = duration;
this.type = type;
this.show = show;
}
}
<file_sep>/src/components/tag/index.ts
import Tag from './src/tag.vue'
Object.defineProperty(Tag, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-tag', Tag);
}
})
export default Tag
<file_sep>/src/index.ts
/********** 基础组件 **********/
import Button from './components/button';
import ButtonGroup from './components/button-group';
import Tag from './components/tag';
import Icon from './components/icon';
/********** 表单组件 **********/
import Checkbox from './components/checkbox';
import CheckboxGroup from './components/checkbox-group';
import Textarea from './components/textarea';
import InputNumber from './components/input-number';
import Rate from './components/rate';
import Input from './components/input';
import Switch from './components/switch';
import Slider from './components/slider'
import Radio from './components/radio';
import RadioGroup from './components/radio-group';
import RadioButton from './components/radio-button';
import Form from './components/form';
import FormItem from './components/form-item';
import Select from './components/select'
import Option from './components/select-option'
import OptionGroup from './components/select-option-group'
/********** 视图组件 **********/
import Badge from './components/badge';
import Alert from './components/alert';
import Collapse from './components/collapse';
import CollapseItem from './components/collapse-Item';
import Message from './components/message';
import LoadingBar from './components/loading-bar';
import Notification from './components/notification';
import Progress from './components/progress';
import TimeLine from './components/timeline';
import TimeLineItem from './components/timeline-item';
import Step from './components/step';
import StepItem from './components/step-item';
import Table from './components/table';
import Dropdown from './components/dropdown';
import DropdownMenu from './components/dropdown-menu';
import DropdownItem from './components/dropdown-item';
import Drawer from './components/drawer';
import Tooltip from './components/tooltip';
import Popover from './components/popover';
import Modal from './components/modal';
import Card from './components/card';
/********** 导航组件 **********/
import Breadcrumb from './components/breadcrumb';
import BreadcrumbItem from './components/breadcrumb-item';
import Pagination from './components/pagination';
import Tabs from './components/tabs';
import TabPane from './components/tab-pane';
import Menu from './components/menu';
import MenuItem from './components/menu-item';
import MenuItemGroup from './components/menu-item-group';
import Submenu from './components/menu-sub';
function install(Vue: any, opts = {}) {
Vue.component('by-button', Button);
Vue.component('by-button-group', ButtonGroup);
Vue.component('by-tag', Tag);
Vue.component('by-icon', Icon);
Vue.component('by-checkbox', Checkbox);
Vue.component('by-checkbox-group', CheckboxGroup);
Vue.component('by-textarea', Textarea);
Vue.component('by-input-number', InputNumber);
Vue.component('by-rate', Rate);
Vue.component('by-switch', Switch);
Vue.component('by-select', Select)
Vue.component('by-option', Option)
Vue.component('by-option-group', OptionGroup)
Vue.component('by-input', Input);
Vue.component('by-radio', Radio);
Vue.component('by-radio-group', RadioGroup);
Vue.component('by-radio-button', RadioButton);
Vue.component('by-slider', Slider);
Vue.component('by-form', Form);
Vue.component('by-form-item', FormItem);
Vue.component('by-badge', Badge);
Vue.component('by-alert', Alert);
Vue.component('by-collapse', Collapse);
Vue.component('by-collapse-item', CollapseItem);
Vue.component('by-progress', Progress);
Vue.component('by-breadcrumb', Breadcrumb);
Vue.component('by-breadcrumb-item', BreadcrumbItem)
Vue.component('by-time-line', TimeLine);
Vue.component('by-timeline-item', TimeLineItem);
Vue.component('by-pagination', Pagination);
Vue.component('by-step', Step);
Vue.component('by-step-item', StepItem);
Vue.component('by-table', Table);
Vue.component('by-dropdown', Dropdown);
Vue.component('by-dropdown-menu', DropdownMenu);
Vue.component('by-dropdown-item', DropdownItem);
Vue.component('by-drawer', Drawer);
Vue.component('by-tabs', Tabs);
Vue.component('by-tab-pane', TabPane);
Vue.component('by-menu', Menu);
Vue.component('by-menu-item', MenuItem);
Vue.component('by-menu-item-group', MenuItemGroup);
Vue.component('by-menu-sub', Submenu);
Vue.component('by-tooltip', Tooltip);
Vue.component('by-popover', Popover);
Vue.component('by-modal', Modal);
Vue.component('by-card', Card);
Vue.prototype.$message = Message;
Vue.prototype.$loadingBar = LoadingBar;
Vue.prototype.$notify = Notification;
Vue.prototype.$modal = Modal;
}
/**
* Global Install
*/
if (typeof window !== 'undefined' && window.Vue) {
install(window.Vue)
}
const verion = 'v.0.0.3'
export { verion, install, Message, Button, Modal }
// export default { verion, install, Message, Button }
<file_sep>/src/components/drawer/index.ts
import Drawer from './src/drawer.vue'
Object.defineProperty(Drawer, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-drawer', Drawer);
}
})
export default Drawer;
<file_sep>/docs/packages/i18n/index.ts
import Vue from 'vue';
import VueI18n from 'vue-i18n';
import messages from '@/locale';
Vue.use(VueI18n);
export const i18n = new VueI18n({
locale: 'cn', // set locale
fallbackLocale: 'cn', // 默认语言设置,当其他语言没有的情况下,使用en作为默认语言
messages // set locale messages
});
<file_sep>/src/components/loading-bar/model.ts
export class LoadingBarOption {
width: number | string;
color: string;
percent: number;
status: string;
show: boolean;
constructor(width: number | string = '', color: string = '', percent: number = 100, status: string = '', show: boolean = true) {
this.width = width;
this.color = color;
this.percent = percent;
this.status = status;
this.show = show;
}
}
<file_sep>/src/components/card/index.ts
import Card from './src/card.vue'
Object.defineProperty(Card, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-card', Card);
}
})
export default Card
<file_sep>/src/utils/utils.ts
const SPECIAL_CHARS_REGEXP = /([:\-_]+(.))/g
const MOZ_HACK_REGEXP = /^moz([A-Z])/
export function camelCase(name: string) {
return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter
}).replace(MOZ_HACK_REGEXP, 'Moz$1')
}
export function getStyle (element:any, styleName:string) {
if (!element || !styleName) return null
styleName = camelCase(styleName)
if (styleName === 'float') {
styleName = 'cssFloat'
}
try {
const computed = (document as any).defaultView.getComputedStyle(element, '')
return element.style[styleName] || computed ? computed[styleName] : null
} catch (e) {
return element.style[styleName]
}
}<file_sep>/src/components/notification/vue.d.ts
import Vue from 'vue';
import { notificationOption } from './model';
declare module 'vue/types/vue' {
interface Vue {
$notify: {
(): void;
success(option: notificationOption): void;
error(option: notificationOption): void;
warning(option: notificationOption): void;
info(option: notificationOption): void;
};
}
}
<file_sep>/src/locale/index.ts
import cn from './lang/zh-CN'
import en from './lang/en-US'
export default {
cn,
en
}
<file_sep>/docs/utils/collapse-transition.ts
/**
* https://github.com/ElemeFE/element/blob/dev/src/transitions/collapse-transition.js
*/
import { addClass, removeClass } from './util'
const Transition = {
beforeEnter(el) {
addClass(el, 'collapse-transition')
if (!el.dataset) el.dataset = {}
// // el.dataset.oldPaddingTop = el.style.paddingTop
// // el.dataset.oldPaddingBottom = el.style.paddingBottom
el.style.height = '0'
// el.style.paddingTop = 0
// el.style.paddingBottom = 0
},
enter(el) {
el.dataset.oldOverflow = el.style.overflow
if (el.scrollHeight !== 0) {
el.style.height = `${el.scrollHeight}px`
// // el.style.paddingTop = el.dataset.oldPaddingTop
// // el.style.paddingBottom = el.dataset.oldPaddingBottom
} else {
el.style.height = ''
// // el.style.paddingTop = el.dataset.oldPaddingTop
// // el.style.paddingBottom = el.dataset.oldPaddingBottom
}
el.style.overflow = 'hidden'
},
afterEnter(el) {
// for safari: remove class then reset height is necessary
removeClass(el, 'collapse-transition')
el.style.height = ''
el.style.overflow = el.dataset.oldOverflow
},
beforeLeave(el) {
if (!el.dataset) el.dataset = {}
// // el.dataset.oldPaddingTop = el.style.paddingTop
// // el.dataset.oldPaddingBottom = el.style.paddingBottom
el.dataset.oldOverflow = el.style.overflow
el.style.height = `${el.scrollHeight}px`
el.style.overflow = 'hidden'
},
leave(el) {
if (el.scrollHeight !== 0) {
// for safari: add class after set height, or it will jump to zero height suddenly, weired
addClass(el, 'collapse-transition')
el.style.height = 0
// el.style.paddingTop = 0
// el.style.paddingBottom = 0
}
},
afterLeave(el) {
removeClass(el, 'collapse-transition')
el.style.height = ''
el.style.overflow = el.dataset.oldOverflow
// // el.style.paddingTop = el.dataset.oldPaddingTop
// // el.style.paddingBottom = el.dataset.oldPaddingBottom
}
}
export default {
name: 'CollapseTransition',
functional: true,
render(h, { children }) {
const data = {
on: Transition
}
return h('transition', data, children)
}
}
<file_sep>/src/components/progress/index.ts
import Progress from './src/progress.vue'
Object.defineProperty(Progress, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-progress', Progress);
}
})
export default Progress
<file_sep>/src/components/radio-group/index.ts
import RadioGroup from '../radio/src/radio-group.vue'
Object.defineProperty(RadioGroup, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-radio-group', RadioGroup);
}
})
export default RadioGroup
<file_sep>/src/components/button/index.ts
import Button from './src/button.vue'
Object.defineProperty(Button, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-button', Button);
}
})
export default Button
<file_sep>/src/components/select-option-group/index.ts
import OptionGroup from '../select/src/option-group.vue'
Object.defineProperty(OptionGroup, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-option-group', OptionGroup);
}
})
export default OptionGroup
<file_sep>/build/webpack/webpack.dev.config.ts
import * as webpack from 'webpack';
import * as merge from 'webpack-merge';
import * as HtmlPlugin from 'html-webpack-plugin';
import * as path from 'path';
const CleanWebpackPlugin = require('clean-webpack-plugin');
const FriendlyErrorsWebpackPlugin = require('friendly-errors-webpack-plugin');
const baseConfig = require('./webpack.base.config.ts');
const os = require("os");
const networkInterfaces = os.networkInterfaces();
import byui from '../config/by-ui';
let ip = "";
const port = '11111';
for (var key in networkInterfaces) {
networkInterfaces[key].forEach(item => {
if (!item.internal && item.family === "IPv4") {
ip = item.address;
}
});
}
module.exports = merge(baseConfig, {
entry: {
index: [path.resolve("docs/index.ts")]
},
output: {
publicPath: "/",
},
devServer: {
host: ip,
port: port,
hot: true,
open: true,
quiet: true,
historyApiFallback: true
},
plugins: [
new CleanWebpackPlugin(),
new webpack.HotModuleReplacementPlugin(),
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: [
...byui,
],
notes: [
`start at: http://${ip}:${port}`,
],
}
}),
new HtmlPlugin({
filename: "index.html",
title: "By-ui",
template: path.resolve("docs/index.html"),
showErrors: true,
}),
],
})
<file_sep>/src/components/loading-bar/src/loading-bar.ts
import Vue from 'vue';
import LoadingBarVue from './loading-bar.vue';
import { LoadingBarOption } from '../model';
let instance: any;
const LoadingBarConstructor = Vue.extend(LoadingBarVue);
class LoadingBar {
constructor(options: LoadingBarOption) {
options = options || {}
instance = new LoadingBarConstructor({
data: options
})
instance.vm = instance.$mount()
document.body.appendChild(instance.vm.$el)
}
update(newOptions: LoadingBarOption) {
newOptions.width && (instance.width = newOptions.width);
newOptions.color && (instance.color = newOptions.color);
newOptions.percent && (instance.percent = newOptions.percent);
newOptions.status && (instance.status = newOptions.status);
newOptions.show && (instance.show = newOptions.show);
}
destroy() {
document.body.removeChild(instance.vm.$el)
}
}
export default LoadingBar;
<file_sep>/docs/markdown/slider.md
# Slider 滑动输入条
---
滑动输入条,用于控制用户在规定的数值区间内进行选择
## 基础用法
基本滑动条,通过 `v-model` 绑定数据,默认取值范围为 `0~100`
:::demo
```html
<by-slider v-model="value"></by-slider>
```
:::
## 不可用状态
设置属性 `disabled` 禁用滑动条
:::demo
```html
<by-slider v-model="value2" disabled="true"></by-slider>
```
:::
## 自定义取值范围
通过属性 `min`, `max` 分别设置最小和最大可取值
:::demo
```html
<by-slider v-model="value3" :min="20" :max="80"></by-slider>
```
:::
## 离散值
可通过属性 `step` 控制每次滑动的间隔,默认间隔为 `1`
:::demo
```html
<by-slider v-model="value4" :step="10"></by-slider>
```
:::
## Slider 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| -------- | ------------------------------- | ------- | ------ | ------ |
| value | 当前的值,可通过 `v-model` 绑定 | Number | - | - |
| step | 步长 | Number | - | 1 |
| min | 最小值 | Number | - | 0 |
| max | 最大值 | Number | - | 100 |
| disabled | 是否禁用 | Boolean | - | false |
## Slider 事件
| 事件名称 | 说明 | 返回值 |
| -------- | -------------------- | ---------- |
| change | 绑定的值有变化时触发 | 改变后的值 |
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class BySliderMd extends Vue {
value = 0
value2 = 20
value3 = 30
value4 = 50
}
</script>
<file_sep>/docs/markdown/button.md
# Button 按钮
-----
## 带颜色倾向的按钮
带有色彩倾向的按钮能给用户带来操作提示
:::demo
```html
<div class="row">
<by-button>默认按钮</by-button>
<by-button type="primary">主要按钮</by-button>
<by-button type="success">成功按钮</by-button>
<by-button type="error">危险按钮</by-button>
<by-button type="warning">警告按钮</by-button>
<by-button type="info">信息按钮</by-button>
</div>
<div class="row">
<by-button plain>默认按钮</by-button>
<by-button type="primary" plain>主要按钮</by-button>
<by-button type="success" plain>成功按钮</by-button>
<by-button type="error" plain>危险按钮</by-button>
<by-button type="warning" plain>警告按钮</by-button>
<by-button type="info" plain>信息按钮</by-button>
</div>
<div class="row">
<by-button round>默认按钮</by-button>
<by-button type="primary" round>主要按钮</by-button>
<by-button type="success" round>成功按钮</by-button>
<by-button type="error" round>危险按钮</by-button>
<by-button type="warning" round>警告按钮</by-button>
<by-button type="info" round>信息按钮</by-button>
</div>
```
:::
## 不可用状态按钮
添加属性 `disabled` 禁用按钮
:::demo
```html
<div class="row">
<by-button type="primary" disabled>主要按钮</by-button>
<by-button hollow disabled>次要按钮</by-button>
<by-button type="text" disabled>文字按钮</by-button>
</div>
```
:::
## 图标按钮
添加属性 `icon` 渲染图标按钮
:::demo
```html
<div class="row">
<by-button icon="icon-edit" circle></by-button>
<by-button type="primary" icon="icon-edit" circle></by-button>
<by-button type="success" icon="icon-edit" circle></by-button>
<by-button type="error" icon="icon-edit" circle></by-button>
<by-button type="warning" icon="icon-edit" circle></by-button>
<by-button type="info" icon="icon-edit" circle></by-button>
</div>
```
:::
`loading` 按钮
:::demo
```html
<by-button loading circle></by-button>
<by-button loading >加载中</by-button>
```
:::
### 不同尺寸
Button 组件提供除了默认值以外的三种尺寸,可以在不同场景下选择合适的按钮尺寸。
:::demo
```html
<div>
<by-button type="primary" size="large">变大按钮</by-button>
<by-button type="primary">正常按钮</by-button>
<by-button type="primary" size="small">变小按钮</by-button>
<by-button type="primary" size="smaller">超小按钮</by-button>
</div>
<div style="margin-top: 20px;">
<by-button icon="icon-edit" circle size="large"></by-button>
<by-button icon="icon-edit" circle></by-button>
<by-button icon="icon-edit" circle size="small"></by-button>
<by-button icon="icon-edit" circle size="smaller"></by-button>
</div>
```
:::
## Button 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| type | 按钮的类型 | String | `default` `primary` `success` `error` `warning` `info` `text` | - |
| nativeType | 原生按钮的类型 | String | - | `button` |
| size | 按钮的大小 | String | `large`, `small`, `smaller` | - |
| hollow | 是否为空心按钮 | Boolean | - | false |
| icon | 按钮的图标类名,填入图标的 `classname` | String | 见文档 `Icon 图标` | - |
| loading | 设置按钮的载入状态 | Boolean | - | false |
| circle | 设置圆形图标按钮 | Boolean | - | false |
<style lang="scss" scoped>
.row {
.by-btn + .by-btn {
margin-left: 8px;
}
& + .row {
margin-top: 20px;
}
.by-btn-group .by-btn {
margin-left: 0;
}
}
.by-btn-group {
margin-left: 8px;
margin-top: 16px;
}
</style>
<file_sep>/src/components/icon/index.ts
import Icon from './src/icon.vue'
Object.defineProperty(Icon, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-icon', Icon);
}
})
export default Icon
<file_sep>/src/locale/lang/pt-BR.ts
export default {
by: {
select: {
placeholder: 'Selecione',
notFoundText: 'Nenhum dado correspondente'
},
modal: {
okText: 'OK',
cancelText: 'Cancelar'
},
pagination: {
prevText: 'Página anterior',
nextText: 'Próxima página',
total: 'Total',
item: 'item',
items: 'itens',
pageSize: '/ página',
goto: 'Ir para',
pageText: '',
prev5Text: '5 Páginas anteriores',
next5Text: 'Próximas 5 Páginas'
},
table: {
emptyText: 'Sem dados'
}
}
}
<file_sep>/src/components/menu-item/index.ts
import MenuItem from '../menu/src/menu-item.vue'
Object.defineProperty(MenuItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-menu-item', MenuItem);
}
})
export default MenuItem
<file_sep>/src/components/loading-bar/index.ts
import LoadingBar from './src/loading-bar';
import { LoadingBarOption } from './model';
let loadingBarInstance: any;
let option: LoadingBarOption = new LoadingBarOption();
let timer: any;
function getLoadingBarInstance(option: LoadingBarOption) {
loadingBarInstance = loadingBarInstance || new LoadingBar(option);
return loadingBarInstance;
}
function update(options: LoadingBarOption) {
const instance = getLoadingBarInstance(options);
instance.update(options);
}
function hide() {
setTimeout(() => {
update(new LoadingBarOption(undefined, undefined, 0, undefined, false));
destroy()
}, 800)
}
function destroy() {
const instance = getLoadingBarInstance(new LoadingBarOption())
clearTimer()
loadingBarInstance = null
instance.destroy()
}
function clearTimer() {
if (timer) {
clearInterval(timer)
timer = null
}
}
export default {
start() {
if (timer) return;
let percent = 0;
update(option);
timer = setInterval(() => {
percent += Math.floor((Math.random() * 3) + 5);
if (percent > 90) {
clearTimer()
}
update(new LoadingBarOption(undefined, undefined, percent, 'success', true));
}, 200);
},
update(percent: number) {
clearTimer();
option.status = 'success';
option.percent = percent;
console.log(option);
update(option);
},
finish() {
clearTimer();
option.status = 'success';
option.percent = 100;
hide()
},
error() {
clearTimer();
option.status = 'error';
option.percent = 100;
option.color = '';
update(option);
hide();
},
config(options: LoadingBarOption) {
option = options
}
}
<file_sep>/docs/markdown/badge.md
# Badge 徽标
----
## 独立使用
不包裹任何元素,类似 `Tag` 标签
:::demo
```html
<by-badge value="3" ></by-badge>
<by-badge value="23"></by-badge>
<by-badge value="199"></by-badge>
<by-badge value="2019"></by-badge>
```
:::
## 文本内容
徽标既可以数字,也可以是文本内容
:::demo
```html
<by-badge value="new"></by-badge>
<by-badge value="hot"></by-badge>
```
:::
## 不同状态
设置属性 `status` 指定不同的状态徽标
:::demo
```html
<by-badge value="123"></by-badge>
<by-badge value="123" status="success"></by-badge>
<by-badge value="123" status="warning"></by-badge>
<by-badge value="123" status="info"></by-badge>
```
:::
## 设定最大值
设置属性 `max-num` 可自定义徽标的最大值,超过最大值则显示 `+`
:::demo
```html
<by-badge :value="value" :max-num="maxNum"></by-badge>
```
:::
## 组合用法
与其他组件组合使用,用于展示消息数量等
:::demo
```html
<by-badge value="3">
<by-button>回复</by-button>
</by-badge><br /><br />
<by-badge :value="value" :max-num="maxNum">
<by-button>回复</by-button>
</by-badge><br /><br />
<by-badge value="new">
<by-button>回复</by-button>
</by-badge>
```
:::
## 小红点
设置属性 `dot` 不显示具体的数字
:::demo
```html
<by-badge :value="12" dot></by-badge>
<by-badge :value="12" dot>
<by-button>回复</by-button>
</by-badge>
<by-badge :value="12" dot>
<i class="icon icon-inbox"></i>
</by-badge>
<by-badge :value="12" dot>
<span>消息</span>
</by-badge>
```
:::
## 动态展示
动态展示变化的效果
:::demo
```html
<by-badge :value="num" :max-num="60">
<span class="badge-example"></span>
</by-badge>
<by-badge :value="num" :show="show" dot>
<span class="badge-example"></span>
</by-badge>
<br>
<by-button @click="num -= 1">-</by-button>
<by-button @click="num += 1">+</by-button>
<by-button size="small" @click="toggleDot">{{show ? '隐藏' : '显示'}}小红点</by-button>
```
:::
## Badge 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value | 绑定的值 | String / Number | - | - |
| maxNum | 允许的最大值,超出则用 `+` 号显示 | Number | - | 99 |
| dot | 是否显示为小红点 | Boolean | - | false |
| status | 徽标的类型 | String | `success` `warning` `info` | - |
| show | 是否显示徽标 | Boolean | - | true |
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class ByBadgeMd extends Vue {
maxNum = 99;
value = 123;
num = 50;
show = true;
toggleDot() {
this.show = !this.show;
}
}
</script>
<style lang="scss" scoped>
.badge-example{
display: inline-block;
width: 32px;
height: 32px;
border-radius: 6px;
background: #EEE;
cursor: pointer;
}
.by-badge + .by-badge {
margin-left: 24px;
}
</style>
<file_sep>/src/locale/lang/zh-CN.ts
export default {
by: {
index: {
h4: '通过模块化UI组件库,专注于更好的用户体验',
button: '开始使用',
btnGroup: [
{
title: '指南',
content: '了解设计指南,利用统一的规范进行设计帮助产品设计师、前端工程师快速搭建'
},{
title: '组件',
content: '通过组件的Demo体验交互细节,开发即可单独引用,也可使用全局方式引入组件'
},{
title: '资源',
content: '产品可直接用sketch工具快速搭建高保真产品原型,减少沟通成本'
}
]
},
header: {
adminSystem: '管理后台',
component: '组件',
guide: '指南'
},
color: {
themeColor: '主色',
themeColorDesc: '用于标识品牌颜色',
colorTitle: 'Color 颜色',
colorDesc: '统一的色彩搭配可以提高品牌的识别度,色彩的运用除了需要考虑品牌的统一性之外,还需要达到信息传递,交互反馈等目的。BY-UI 是BY实验室出品,品牌颜色为【BY蓝】,因此 BY-UI 的整体配色风格也是基于【BY蓝】展开的。',
},
nav: {
color: '色彩',
font: '字体',
brand: '品牌',
introduce: '介绍',
component: '组件',
summarize: '综述',
baseComponent: '基础组件',
formComponent: '表单组件',
viewComponent: '视图组件',
navComponent: '导航组件',
button: 'Button 按钮',
layout: 'Layout 布局',
tag: 'Tag 标签',
icon: 'Icon 图标',
checkbox: 'Checkbox 多选框',
input: 'Input 输入框',
inputnumber: 'InputNumber 数字输入框',
radio: 'Radio 单选框',
rate: 'Rate 评分',
select: 'Select 选择器',
switch: 'Switch 开关',
form: 'Form 表单',
slider: 'Slider 滑动输入条',
textarea: 'Textarea 文本域',
alert: 'Alert 警告提示',
badge: 'Badge 徽标',
card: 'Card 卡片',
collapse: 'Collapse 折叠面板',
loadingBar: 'LoadingBar 加载进度条',
modal: 'Modal 模态框',
message: 'Message 全局提示',
notification: 'Notification 通知提醒',
popover: 'Popover 弹出框',
progress: 'Progress 进度条',
timeline: 'Timeline 时间轴',
tooltip: 'Tooltips 文字提示',
table: 'Table 表格',
drawer: 'Drawer 抽屉',
breadcrumb: 'Breadcrumb 面包屑',
dropdown: 'Dropdown 下拉菜单',
menu: 'Menu 导航菜单',
pagination: 'Pagination 分页',
steps: 'Steps 步骤条',
tabs: 'Tabs 标签页',
},
select: {
placeholder: '请选择',
notFoundText: '无匹配数据'
},
modal: {
okText: '确定',
cancelText: '取消'
},
pagination: {
prevText: '上一页',
nextText: '下一页',
total: '共',
item: '条',
items: '条',
pageSize: '条/页',
goto: '前往',
pageText: '页',
prev5Text: '向前5页',
next5Text: '向后5页'
},
table: {
emptyText: '暂无数据'
}
}
}
<file_sep>/docs/markdown/loadingbar.md
# LoadingBar 加载进度条
----
全局创建了一个用于显示页面加载、异步请求的加载进度条。
因为可复用性的关系,`LoadingBar` 只会全局创建一个实例,而且在 `Vue.prototype` 中添加了全局对象 `$loadingBar`,可以直接通过 `this.$loadingBar` 操作实例
## 基础用法
通过调用 `$loadingBar` 提供的三种方法来控制全局的加载进度条 `start()`、`finish()`、`error()`
:::demo
```html
<by-button @click="start">Start</by-button>
<by-button @click="finish">Finish</by-button>
<by-button @click="error">Error</by-button>
<by-button @click="update">Update</by-button>
<script>
export default {
methods: {
start () {
this.$loadingBar.start()
},
finish () {
this.$loadingBar.finish()
},
error () {
this.$loadingBar.error()
},
update () {
this.$loadingBar.update(60)
}
}
}
</script>
```
:::
## LoadingBar 函数方法
| 函数名 | 说明 | 参数 |
|---------- |-------------- |---------- |
| start | 开始从 0 显示加载进度条,并自动加载 | - |
| finish | 完成进度条 | - |
| error | 显示错误类型的进度条 | - |
| update | 指定进度的百分比,更新进度条 | percent,指定进度的百分比 |
## LoadingBar 配置
提供 `LoadingBar` 的全局配置,使用方法如下:
```js
this.$loadingBar.config(new LoadingBarOption(
10, // 高度
'linear-gradient(to right, #30fcfc, #fff5ee)', // 背景色,支持渐变
1, // 百分比进度
'success', // 状态
true // 显示隐藏
));
```
:::demo
```html
<by-button @click="startLinear">设置渐变及高度</by-button>
<script>
export default {
methods: {
startLinear(){
this.$loadingBar.config(new LoadingBarOption(
10, 'linear-gradient(to right, #30fcfc, #fff5ee)', 1, 'success', true
));
this.$loadingBar.start()
},
}
}
</script>
```
:::
## LoadingBar 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| height | 进度条的线宽 | Number | - | 4 |
| color | 进度条的背景色 | String | - | - |
| percent | 进度条的百分比 | Number | - | - |
| status | 进度条的状态 | String | `success` `error` | success |
| show | 进度条的显隐 | Boolean | `true` `false` | true |
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { LoadingBarOption } from '../../src/components/loading-bar/model.ts';
@Component
export default class LoadingBar extends Vue {
start () {
this.$loadingBar.start();
}
startLinear(){
this.$loadingBar.config(new LoadingBarOption(
10, 'linear-gradient(to right, #30fcfc, #fff5ee)', 1, 'success', true
));
this.$loadingBar.start();
}
finish () {
this.$loadingBar.finish();
}
error () {
this.$loadingBar.error();
}
update () {
this.$loadingBar.update(60)
}
}
</script>
<file_sep>/docs/markdown/modal.md
# Modal 模态框
----
模态对话框,当需要询问用户处理事务,又不希望跳转页面时,可以使用模态框 `Modal` 在当前页面打开一个浮层并承载相应的操作。
当需要弹出一个简洁的确认框时,也可以使用默认的精简版模态框。`BY-UI` 在 `Vue.prototype` 中添加了全局对象 `$modal`,可以直接通过 `this.$modal` 对象操作实例方法
## Modal 实例方法
通过调用 `this.$modal` 的方法来使用:
- `this.$modal.alert(config)`
- `this.$modal.confirm(config)`
- `this.$modal.prompt(config)`
- `this.$modal.info(config)`
- `this.$modal.success(config)`
- `this.$modal.warning(config)`
- `this.$modal.error(config)`
## 消息提醒
弹出会中断用户的对话框,直到用户知晓该信息之后才可以关闭,属于交互比较重的操作。(类似于 `window.alert`)
可以用 `Promise` 的方式捕获操作反馈,也可以用传入 `callback` 参数的方式
:::demo
```html
<p class="demo-desc">this.$modal.alert()</p>
<by-button @click="modalAlert">Alert</by-button>
<script>
export default {
methods: {
modalAlert () {
this.$modal.alert({
title: '这里是标题名称',
content: '这里是文本内容',
callback: function (action) {
this.$message(action)
}
})
}
}
}
</script>
```
:::
## 确认消息
对用户操作的一个反馈,用于确定是否需要继续操作。(类似于 `window.confirm`)
:::demo
```html
<p class="demo-desc">this.$modal.confirm()</p>
<by-button @click="modalConfirm">Confirm</by-button>
<script>
export default {
methods: {
modalConfirm () {
this.$modal.confirm({
title: '提示',
content: '此操作需要非常谨慎,您确定要这么做吗?'
}).then(() => {
this.$message('点击了「确认」按钮')
}).catch(() => {
this.$message('点击了「取消」按钮')
})
}
}
}
</script>
```
:::
## 提交信息
弹出输入对话框,提醒用户输入相应内容。(类似于 `window.prompt`)
:::demo
```html
<p class="demo-desc">this.$modal.prompt({ title: '提示', content: '请输入邮件地址:' })</p>
<by-button @click="modalPrompt">Prompt</by-button>
<script>
export default {
methods: {
modalPrompt () {
this.$modal.prompt({
title: '提示',
content: '请输入邮件地址:'
}).then((data) => {
this.$message(`点击了「确认」按钮,输入框的值为 ${data.value}`)
}).catch(() => {
this.$message('点击了「取消」按钮')
})
}
}
}
</script>
```
:::
## 消息类的对话框
除了上述的类 `window` 对话框,`by-UI` 还提供了四种消息类的对话框,主要用来展示一些重要信息。该类的对话框仅允许点击「确定」按钮关闭,不支持其他关闭方式
:::demo
```html
<p class="demo-desc">this.$modal.success()</p>
<by-button @click="handleClick('success')">成功</by-button>
<by-button @click="handleClick('error')">错误</by-button>
<by-button @click="handleClick('warning')">警告</by-button>
<by-button @click="handleClick('info')">消息</by-button>
<script>
export default {
methods: {
handleClick (type) {
if (type === 'info') {
this.$modal.info({
content: '这里是提示的消息'
})
} else if (type === 'success') {
this.$modal.success({
content: '这里是成功的消息'
})
} else if (type === 'warning') {
this.$modal.warning({
content: '这里是警告的消息'
})
} else if (type === 'error') {
this.$modal.error({
content: '这里是错误的消息'
})
}
}
}
}
</script>
```
:::
## 组件化方式调用
前面提到的是通过 `this.$modal` 的方法来使用,如果要自定义对话框,可使用组件化的方式
:::demo
```html
<by-button @click="modal1=true">显示自定义模态框</by-button>
<by-modal v-model="modal1" title="这里是标题" @on-confirm="handleConfirm" @on-cancel="handleCancel">
<p>这里是模态框的文本内容!</p>
<p>这里是模态框的文本内容!</p>
</by-modal>
<script>
export default {
methods: {
handleConfirm () {
this.$message('Confirm')
},
handleCancel () {
this.$message('Cancel')
}
}
}
</script>
```
:::
## 自定义样式
`Modal` 组件提供了自定义页头、页脚的 `slot`,可灵活的控制对话框的样式结构。通过与其他组件的交互,可实现复杂的功能需求。
:::demo
```html
<by-button @click="modal2=true">自定义页头和页脚</by-button>
<by-button @click="modal3=true">不带标题</by-button>
<by-modal v-model="modal2">
<div slot="header" style="text-align:center;">
<span>这里是标题</span>
</div>
<div style="text-align:center;">
<p>能看到这里的内容吗?</p>
</div>
<div slot="footer">
<by-button style="width:100%;" type="error" @click="closeModal2">这里是按钮</by-button>
</div>
</by-modal>
<by-modal v-model="modal3">
<p>这里是模态框的文本内容!</p>
</by-modal>
<script>
export default {
methods: {
closeModal2 () {
this.modal2 = false
}
}
}
</script>
```
:::
## 禁用关闭
- 设置属性 `show-close` 为 `false` 可取消右上角的关闭按钮以及键盘的 `ESC` 键;
- 设置属性 `mask-closable` 为 `false` 可取消遮罩层的点击关闭事件;
:::demo
```html
<by-button @click="modal4=true">禁用右上角关闭按钮(含 ESC)</by-button>
<by-button @click="modal5=true">取消遮罩层关闭</by-button>
<by-modal v-model="modal4" title="标题" :show-close="false">这里是文本</by-modal>
<by-modal v-model="modal5" title="标题" :show-close="false" :mask-closable="false">这里是文本</by-modal>
```
:::
## 自定义窗口位置
通过属性 `styles` 传入 `CSS Style Object`,可更改弹框的样式
:::demo
```html
<by-button @click="modal6=true">仅改变距离顶部的位置</by-button>
<by-modal v-model="modal6" title="标题" :styles="{top: '20px'}">这里是文本内容</by-modal>
```
:::
## Modal 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value | 是否显示模态框,可通过 `v-model` 绑定 | Boolean | - | false |
| title | 模态框的标题 | String | - | - |
| content | 模态框的内容 | String | - | - |
| cancelText | 取消按钮的文本 | String | - | 取消 |
| okText | 确定按钮的文本 | String | - | 确定 |
| maskClosable | 点击遮罩层是否可以关闭模态框 | Boolean | - | true |
| showHead | 是否显示标题 | Boolean | - | true |
| showClose | 是否显示关闭按钮 | Boolean | - | true |
| showFooter | 是否显示底部按钮 | Boolean | - | true |
| showInput | 是否显示输入框 | Boolean | - | false |
| width | 模态框的宽度 | Number / String | - | `520` |
| closeOnPressEsc | 点击 `ESC` 是否可以关闭模态框 | Boolean | - | true |
| styles | 模态框的自定义样式 | Object | - | - |
## Modal 事件
| 事件名称 | 说明 | 返回参数 |
|---------- |-------------- |---------- |
| on-cancel | 点击取消的回调事件 | - |
| on-confirm | 点击确定的回调事件 | - |
## Modal Slots
| 名称 | 说明 |
|-------- |------------------- |
| header | 自定义模态框的头部 |
| footer | 自定义模态框的底部,即底部按钮部分 |
| - | 自定义模态框的主体内容 |
<script>
export default {
data () {
return {
modal1: false,
modal2: false,
modal3: false,
modal4: false,
modal5: false,
modal6: false
}
},
methods: {
handleClick (type) {
if (type === 'info') {
this.$modal.info({
content: '这里是提示的消息'
})
} else if (type === 'success') {
this.$modal.success({
content: '这里是成功的消息'
})
} else if (type === 'warning') {
this.$modal.warning({
content: '这里是警告的消息'
})
} else if (type === 'error') {
this.$modal.error({
content: '这里是错误的消息'
})
}
},
modalAlert () {
this.$modal.alert({
title: '这里是标题名称',
content: '这里是文本内容',
callback: action => {
this.$message(action)
}
})
},
modalConfirm () {
this.$modal.confirm({
title: '提示',
content: '此操作需要非常谨慎,您确定要这么做吗?'
}).then(() => {
this.$message('点击了「确认」按钮')
}).catch(() => {
this.$message('点击了「取消」按钮')
})
},
modalPrompt () {
this.$modal.prompt({
title: '提示',
content: '请输入邮件地址:'
}).then((data) => {
this.$message(`点击了「确认」按钮,输入框的值为 ${data.value}`)
}).catch(() => {
this.$message('点击了「取消」按钮')
})
},
handleConfirm () {
this.$message('Confirm')
},
handleCancel () {
this.$message('Cancel')
},
closeModal2 () {
this.modal2 = false
}
}
}
</script>
<file_sep>/build/webpack/webpack.prod.config.ts
import * as path from 'path';
import * as merge from 'webpack-merge';
import * as HtmlPlugin from 'html-webpack-plugin';
import * as UglifyJsPlugin from 'uglifyjs-webpack-plugin';
import * as OptimizeCSSAssetsPlugin from 'optimize-css-assets-webpack-plugin';
import * as FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin';
import CleanWebpackPlugin from 'clean-webpack-plugin';
import * as baseConfig from './webpack.base.config';
import byui from '../config/by-ui';
let notes = [
`Compile Successful!`
];
module.exports = merge(baseConfig, {
mode: 'production',
entry: {
index: [path.resolve("docs/index.ts")]
},
output: {
path: path.resolve('dist'),
filename: `[name].[contenthash].js`,
chunkFilename: `[name].[contenthash].js`,
publicPath: './',
},
devtool: false,
stats: false,
plugins: [
new CleanWebpackPlugin(),
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: [
...byui
],
notes: [
...notes
],
},
}),
new HtmlPlugin({
filename: "index.html",
title: "By-ui",
template: path.resolve("docs/index.html"),
showErrors: true,
favicon: './favicon.ico'
}),
],
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: false
}),
new OptimizeCSSAssetsPlugin({
cssProcessorOptions: {
safe: true,
},
}),
]
}
})
<file_sep>/src/components/form-item/index.ts
import FormItem from '../form/src/form-item.vue'
Object.defineProperty(FormItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-form-item', FormItem);
}
})
export default FormItem;
<file_sep>/src/locale/lang/ko-KR.ts
export default {
by: {
select: {
placeholder: '선택',
notFoundText: '찾는 데이터가 없습니다'
},
modal: {
okText: '확인',
cancelText: '취소'
},
pagination: {
prevText: '이전 페이지',
nextText: '다음 페이지',
total: '전체',
item: '항목',
items: '항목',
pageSize: '/ 페이지',
goto: '이동',
pageText: '',
prev5Text: '이전 5 페이지',
next5Text: '다음 5 페이지'
},
table: {
emptyText: '데이터가 없습니다'
}
}
}
<file_sep>/src/components/message/src/message.ts
import Vue from 'vue';
import MessageVue from './message.vue';
const MessageConstructor = Vue.extend(MessageVue);
const messageType = ['info', 'success', 'warning', 'error', 'loading'];
const instances: any = [];
let seed = 1;
let zindexSeed = 1010;
const Message = (options: any) => {
if (Vue.prototype.$isServer) return;
options = options || {};
if (typeof options === 'string') {
options = {
message: options
};
}
const customCloseFunc = options.onClose;
const id: string = `message_${seed++}`;
options.onClose = () => {
Message.close(id, customCloseFunc);
};
const instance = new MessageConstructor({
data: options
});
instance.id = id;
instance.vm = instance.$mount();
document.body.appendChild(instance.vm.$el);
instance.vm.visible = true;
instance.dom = instance.vm.$el;
instance.dom.style.zIndex = zindexSeed++;
const offset = 0;
const len = instances.length;
let topDist = offset;
for (let i = 0; i < len; i++) {
topDist += instances[i].$el.offsetHeight + 8;
}
topDist += 8;
instance.top = topDist;
instances.push(instance);
// 返回关闭方法,用于手动消除
return function() {
instance.vm.close(id);
};
}
Message.close = (id: string, customCloseFunc: any) => {
const len = instances.length;
let index: number = 0,
removedHeight;
for (let i: number = 0; i < len; i++) {
if (id === instances[i].id) {
if (typeof customCloseFunc === 'function') {
customCloseFunc(instances[i]);
}
index = i;
removedHeight = instances[i].dom.offsetHeight;
instances.splice(i, 1);
break;
}
}
if (len > 1) {
for (let i: number = index; i < len - 1; i++) {
instances[i].dom.style.top = `${parseInt(
instances[i].dom.style.top
) -
removedHeight -
8}px`;
}
}
}
Message.closeAll = () => {
instances.forEach((elem: any, idx: any) => {
elem.close();
});
}
Message.info = (options:any) => newMessage(options, 'info')
Message.success = (options:any) => newMessage(options, 'success')
Message.warning = (options:any) => newMessage(options, 'warning')
Message.error = (options:any) => newMessage(options, 'error')
Message.loading = (options:any) => newMessage(options, 'loading')
function newMessage(options:any , type: string){
if (typeof options === 'string') {
options = {
message: options
};
}
options.type = type;
options.icon = options.icon;
return Message(options);
}
export default Message;
<file_sep>/src/components/step/index.ts
import Step from './src/step.vue'
Object.defineProperty(Step, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-step', Step);
}
})
export default Step
<file_sep>/src/components/menu-item-group/index.ts
import MenuItemGroup from '../menu/src/menu-item-group.vue'
Object.defineProperty(MenuItemGroup, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-menu-item-group', MenuItemGroup);
}
})
export default MenuItemGroup
<file_sep>/src/components/form/index.ts
import Form from './src/form.vue'
Object.defineProperty(Form, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-form', Form);
}
})
export default Form;
<file_sep>/src/components/select-option/index.ts
import Option from '../select/src/option.vue'
Object.defineProperty(Option, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-option', Option);
}
})
export default Option<file_sep>/docs/resources/directives/index.ts
import Vue from 'vue';
import VueClipboard from './clipboard/clipboard';
Vue.use(VueClipboard);
<file_sep>/docs/utils/util.ts
/**
* 常用方法
*/
const SPECIAL_CHARS_REGEXP = /([:\-_]+(.))/g
const MOZ_HACK_REGEXP = /^moz([A-Z])/
const trim = function (string) {
return (string || '').replace(/^[\s\uFEFF]+|[\s\uFEFF]+$/g, '')
}
/**
* [camelCaseToHyphen 将驼峰命名转换为连字符]
* @param {[string]} str [驼峰命名的字符串]
* @return {[string]} [连字符的字符串]
*/
export function camelCaseToHyphen(str) {
return str.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase()
}
export function camelCase(name) {
return name.replace(SPECIAL_CHARS_REGEXP, function (_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter
}).replace(MOZ_HACK_REGEXP, 'Moz$1')
}
export function getStyle(element, styleName) {
if (!element || !styleName) return null
styleName = camelCase(styleName)
if (styleName === 'float') {
styleName = 'cssFloat'
}
try {
const computed = document.defaultView.getComputedStyle(element, '')
return element.style[styleName] || computed ? computed[styleName] : null
} catch (e) {
return element.style[styleName]
}
}
function typeOf(obj) {
const map = {
'[object Boolean]': 'boolean',
'[object Number]': 'number',
'[object String]': 'string',
'[object Function]': 'function',
'[object Array]': 'array',
'[object Date]': 'date',
'[object RegExp]': 'regExp',
'[object Undefined]': 'undefined',
'[object Null]': 'null',
'[object Object]': 'object',
}
return map[Object.prototype.toString.call(obj)]
}
export function deepCopy(data) {
const type = typeOf(data)
let obj
if (type === 'array') {
obj = []
} else if (type === 'object') {
obj = {}
} else {
return data
}
if (type === 'array') {
for (let i = 0; i < data.length; i++) {
obj.push(deepCopy(data[i]))
}
} else if (type === 'object') {
for (const i in data) {
obj[i] = deepCopy(data[i])
}
}
return obj
}
export function hasClass(el, cls) {
if (!el || !cls) return false
if (cls.indexOf(' ') !== -1) throw new Error('className should not contain space.')
if (el.classList) {
return el.classList.contains(cls)
}
return (` ${el.className} `).indexOf(` ${cls} `) > -1
}
export function addClass(el, cls) {
if (!el) return
const classes = (cls || '').split(' ')
let curClass = el.className
for (let i = 0, j = classes.length; i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
el.classList.add(clsName)
} else if (!hasClass(el, clsName)) {
curClass += ` ${clsName}`
}
}
if (!el.classList) {
el.className = curClass
}
}
export function removeClass(el, cls) {
if (!el || !cls) return
const classes = cls.split(' ')
let curClass = ` ${el.className} `
for (let i = 0, j = classes.length; i < j; i++) {
const clsName = classes[i]
if (!clsName) continue
if (el.classList) {
el.classList.remove(clsName)
} else if (hasClass(el, clsName)) {
curClass = curClass.replace(` ${clsName} `, ' ')
}
}
if (!el.classList) {
el.className = trim(curClass)
}
}
export function findComponentUpward(context: any, componentName: any, componentNames?: any) {
if (typeof componentName === 'string') {
componentNames = [componentName]
} else {
componentNames = componentName
}
let parent = context.$parent
let name = parent.$options.name
while (parent && (!name || componentNames.indexOf(name) < 0)) {
parent = parent.$parent
if (parent) name = parent.$options.name
}
return parent
}
export function findComponentsUpward(context, componentName, components = []) {
let parent = context.$parent
let name = parent.$options.name
while (parent && name) {
if (componentName === name) {
components.push(parent)
}
parent = parent.$parent
if (parent) {
name = parent.$options.name
}
}
return components
}
export function findComponentDownward(context, componentName) {
const childrens = context.$children
let children
if (childrens.length) {
childrens.forEach(child => {
if (child.$options.name === componentName) {
children = child
}
})
for (let i = 0, len = childrens.length; i < len; i++) {
const child = childrens[i]
const name = child.$options.name
if (name === componentName) {
children = child
break
} else {
children = findComponentDownward(child, componentName)
if (children) break
}
}
}
return children
}
export function findComponentsDownward(context, componentName, components = []) {
const childrens = context.$children
if (childrens.length) {
childrens.forEach(child => {
const subChildren = child.$children
const name = child.$options.name
if (name === componentName) {
components.push(child)
}
if (subChildren.length) {
const findChildren = findComponentsDownward(child, componentName, components)
if (findChildren) {
components.concat(findChildren)
}
}
})
}
return components
}
<file_sep>/docs/vue-router/index.ts
import Vue from 'vue';
import VueRouter, { RouterOptions } from 'vue-router';
import routes from './routes';
Vue.use(VueRouter);
const options: RouterOptions = {
routes,
};
const router = new VueRouter(options);
router.beforeEach((to, from, next) => {
next();
(window as any).scrollbar && (window as any).scrollbar.scrollTo(0, 0, 200)
})
export default router;
<file_sep>/src/components/message/index.ts
import Message from './src/message'
export default Message;
<file_sep>/src/components/menu/index.ts
import Menu from './src/menu.vue'
Object.defineProperty(Menu, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-menu', Menu);
}
})
export default Menu
<file_sep>/src/components/popover/index.ts
import Popover from './src/popover.vue'
Object.defineProperty(Popover, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-popover', Popover);
}
})
export default Popover
<file_sep>/src/mixins/popup/index.ts
import { Vue, Component, Prop, Watch } from 'vue-property-decorator';
import merge from '../merge';
import PopupManager from './popup-manager';
import getScrollBarWidth from '../scrollbar-width';
import { getStyle, addClass, removeClass, hasClass } from '../dom';
let idSeed = 1;
let scrollBarWidth;
@Component
export default class Popup extends Vue {
@Prop({
default: false
})
visible?: boolean;
@Prop()
openDelay?: {};
@Prop()
closeDelay?: {};
@Prop()
zIndex?: {};
@Prop({
default: false
})
modal?: boolean;
@Prop({
default: true
})
modalFade?: boolean;
@Prop()
modalClass?: {};
@Prop({
default: false
})
modalAppendToBody?: boolean;
@Prop({
default: true
})
lockScroll?: boolean;
@Prop({
default: false
})
closeOnPressEscape?: boolean;
@Prop({
default: false
})
closeOnClickModal?: boolean;
opened = false;
bodyPaddingRight = null;
computedBodyPaddingRight = 0;
withoutHiddenClass = true;
rendered = false;
open(options?:any) {
console.log('open');
if (!this.rendered) {
this.rendered = true;
}
const props = merge({}, this.$props || this, options);
if (this._closeTimer) {
clearTimeout(this._closeTimer);
this._closeTimer = null;
}
clearTimeout(this._openTimer);
const openDelay = Number(props.openDelay);
if (openDelay > 0) {
this._openTimer = setTimeout(() => {
this._openTimer = null;
this.doOpen(props);
}, openDelay);
} else {
this.doOpen(props);
}
}
doOpen(props:any) {
if (this.$isServer) return;
if (this.willOpen && !this.willOpen()) return;
if (this.opened) return;
this._opening = true;
const dom = this.$el;
const modal = props.modal;
const zIndex = props.zIndex;
if (zIndex) {
PopupManager.zIndex = zIndex;
}
if (modal) {
if (this._closing) {
PopupManager.closeModal(this._popupId);
this._closing = false;
}
PopupManager.openModal(this._popupId, PopupManager.nextZIndex(), this.modalAppendToBody ? undefined : dom, props.modalClass, props.modalFade);
if (props.lockScroll) {
this.withoutHiddenClass = !hasClass(document.body, 'by-popup-parent--hidden');
if (this.withoutHiddenClass) {
this.bodyPaddingRight = document.body.style.paddingRight;
this.computedBodyPaddingRight = parseInt(getStyle(document.body, 'paddingRight'), 10);
}
scrollBarWidth = getScrollBarWidth();
let bodyHasOverflow = document.documentElement.clientHeight < document.body.scrollHeight;
let bodyOverflowY = getStyle(document.body, 'overflowY');
if (scrollBarWidth > 0 && (bodyHasOverflow || bodyOverflowY === 'scroll') && this.withoutHiddenClass) {
document.body.style.paddingRight = this.computedBodyPaddingRight + scrollBarWidth + 'px';
}
addClass(document.body, 'by-popup-parent--hidden');
}
}
if (getComputedStyle(dom).position === 'static') {
dom.style.position = 'absolute';
}
dom.style.zIndex = PopupManager.nextZIndex();
this.opened = true;
this.onOpen && this.onOpen();
this.doAfterOpen();
}
doAfterOpen() {
this._opening = false;
}
close() {
if (this.willClose && !this.willClose()) return;
if (this._openTimer !== null) {
clearTimeout(this._openTimer);
this._openTimer = null;
}
clearTimeout(this._closeTimer);
const closeDelay = Number(this.closeDelay);
if (closeDelay > 0) {
this._closeTimer = setTimeout(() => {
this._closeTimer = null;
this.doClose();
}, closeDelay);
} else {
this.doClose();
}
}
doClose() {
this._closing = true;
this.onClose && this.onClose();
if (this.lockScroll) {
setTimeout(this.restoreBodyStyle, 200);
}
this.opened = false;
this.doAfterClose();
}
doAfterClose() {
PopupManager.closeModal(this._popupId);
this._closing = false;
}
restoreBodyStyle() {
if (this.modal && this.withoutHiddenClass) {
document.body.style.paddingRight = this.bodyPaddingRight;
removeClass(document.body, 'by-popup-parent--hidden');
}
this.withoutHiddenClass = true;
}
beforeMount() {
this._popupId = 'popup-' + idSeed++;
PopupManager.register(this._popupId, this);
}
beforeDestroy() {
PopupManager.deregister(this._popupId);
PopupManager.closeModal(this._popupId);
this.restoreBodyStyle();
}
@Watch('visible')
onVisibleChange(val:boolean) {
console.log({val});
if (val) {
if (this._opening) return;
if (!this.rendered) {
this.rendered = true;
Vue.nextTick(() => {
this.open();
});
} else {
this.open();
}
} else {
this.close();
}
}
}
// props: {
// visible: {
// type: Boolean,
// default: false
// },
// openDelay: { },
// closeDelay: { },
// zIndex: { },
// modal: {
// type: Boolean,
// default: false
// },
// modalFade: {
// type: Boolean,
// default: true
// },
// modalClass: { },
// modalAppendToBody: {
// type: Boolean,
// default: false
// },
// lockScroll: {
// type: Boolean,
// default: true
// },
// closeOnPressEscape: {
// type: Boolean,
// default: false
// },
// closeOnClickModal: {
// type: Boolean,
// default: false
// }
// },
// export {
// PopupManager
// };
<file_sep>/docs/markdown/typography.md
# Typography 字体
----
统一字体规范,力求在各个操作系统上都有最佳的展示效果 1231233213221332132
## 字体家族
css 代码如下:
```css
font-family: -apple-system, BlinkMacSystemFont, "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
```
## 中文字体
<div class="row">
<div class="by-component__container col-sm-24 col-md-8">
<div class="by-component-typo typo-pingfang">
<div class="by-component-typo__show">新仁类实验室</div>
<div class="by-component-typo__detail">
<p>苹方 / PingFang SC</p>
<p class="note">MacOS, IOS 优选字体</p>
</div>
</div>
</div>
<div class="by-component__container col-sm-24 col-md-8">
<div class="by-component-typo typo-dongqing">
<div class="by-component-typo__show">新仁类实验室</div>
<div class="by-component-typo__detail">
<p>冬青黑体 / Hiragino Sans GB</p>
<p class="note">MacOS 备选字体</p>
</div>
</div>
</div>
<div class="by-component__container col-sm-24 col-md-8">
<div class="by-component-typo typo-yahei">
<div class="by-component-typo__show">新仁类实验室</div>
<div class="by-component-typo__detail">
<p>微软雅黑 / Microsoft YaHei</p>
<p class="note">次级备选字体</p>
</div>
</div>
</div>
</div>
<div class="type-demo-container">
<div class="row flex-middle typo-pingfang">
<div class="col-md-5 type">苹方 / PingFang SC</div>
<div class=" content">新仁类实验室(xrl.io 英文简称XRL) 始建于2015年10月,是一个年轻基情的技术团队</div>
</div>
<div class="row flex-middle typo-dongqing">
<div class="col-md-5 type">冬青黑体 / Hiragino Sans GB</div>
<div class=" content">新仁类实验室(xrl.io 英文简称XRL) 始建于2015年10月,是一个年轻基情的技术团队</div>
</div>
<div class="row flex-middle typo-yahei">
<div class="col-md-5 type">微软雅黑 / Microsoft YaHei</div>
<div class=" content">新仁类实验室(xrl.io 英文简称XRL) 始建于2015年10月,是一个年轻基情的技术团队</div>
</div>
</div>
<style lang="scss" scoped>
.type-demo-container {
.row {
margin-top: 8px;
margin-bottom: 8px;
}
.type {
color: #7E95A7;
font-size: 13px;
text-align: right;
}
.content {
font-size: 15px;
padding-left: 24px;
word-break: break-all;
}
}
</style>
<file_sep>/src/components/button-group/index.ts
import ButtonGroup from '../button/src/button-group.vue'
Object.defineProperty(ButtonGroup, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-button-group', ButtonGroup);
}
})
export default ButtonGroup
<file_sep>/src/components/checkbox/index.ts
import CheckBox from './src/checkbox.vue'
Object.defineProperty(CheckBox, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-checkbox', CheckBox);
}
})
export default CheckBox
<file_sep>/docs/vue-router/routes.ts
import { RouteConfig } from 'vue-router';
import NavConfig from './nav.config.yml';
class Route {
name: string;
component: any;
path: string;
children?: Route[] = new Array();
redirect?: any;
constructor(name: string, component: any, path: string, children?: Route[], redirect?: any) {
this.name = name;
this.component = component;
this.path = path;
children && (this.children = children);
redirect && (this.redirect = redirect);
}
}
const routes: any = [];
let currentIndex: number;
Object.keys(NavConfig).forEach((parent: string, index: number) => {
// 制定父级路由
const _name = parent.toLowerCase();
currentIndex = index;
routes.push(
new Route(
parent,
() => import(/* webpackChunkName: "modules/[request]" */ `../views/${_name}/${_name}.vue`),
`/${_name}`,
undefined,
// 重定向到第一个子路由
{ name: NavConfig[parent][0].items[0].name.toLowerCase() }
)
);
// 遍历子路由
NavConfig[parent].forEach((item: any) => {
const _itemName = item.name.toLowerCase();
// 有组的情况
if (item.groups) {
item.groups.forEach(group => {
group.items.forEach(item => {
const _name = item.name.toLowerCase();
routes[currentIndex].children.push(
new Route(
_name,
() => import(/* webpackChunkName: "modules/[request]" */ `../markdown/${_name}.md`),
`${_name}/`
)
)
})
})
} else {
item.items.forEach(group => {
const _name = group.name.toLowerCase();
routes[currentIndex].children.push(
new Route(
_name,
() => import(/* webpackChunkName: "modules/[request]" */ `../markdown/${_name}.md`),
`${_name}/`
)
)
})
}
})
})
routes.push({
path: '/',
name: 'home',
component: () => import(/* webpackChunkName: "modules/home" */ `../views/index/index.vue`)
})
export default routes
<file_sep>/docs/markdown/form.md
# From 表单
----
## 简单的表单
:::demo
```html
<by-form :model="formData1" :rules="ruleLogin1" ref="formLogin1">
<by-form-item prop="username">
<by-input v-model="formData1.username" placeholder="用户名">
<template slot="prepend">
<i class="icon icon-user"></i>
</template>
</by-input>
</by-form-item>
<by-form-item prop="password">
<by-input v-model="formData1.password" placeholder="密码">
<template slot="prepend">
<i class="icon icon-lock"></i>
</template>
</by-input>
</by-form-item>
<by-form-item label="记住密码">
<by-switch v-model="formData1.remember"></by-switch>
</by-form-item>
<by-form-item>
<by-button type="primary" size="small" @click.prevent="handleSubmit('formLogin1')">登录</by-button>
</at-form-item>
</by-form>
```
:::
## 设置label内容及宽度
:::demo
```html
<div style="width: 450px;">
<by-form :model="formData2" :rules="ruleLogin2" ref="formLogin2" :label-width="80">
<by-form-item prop="name" label="活动名称">
<by-input v-model="formData2.name"></by-input>
</by-form-item>
<!-- <by-form-item prop="password" label="活动区域">
<by-select v-model="formData2.area"></by-select>
</by-form-item> -->
<by-form-item prop="password" label="即时配送">
<by-switch v-model="formData2.delivery"></by-switch>
</by-form-item>
</el-form-item>
<by-form-item prop="type" label="活动性质">
<by-checkbox-group v-model="formData2.type">
<by-checkbox label="美食/餐厅线上活动" name="type">美食/餐厅线上活动</by-checkbox>
<by-checkbox label="地推活动" name="type">地推活动</by-checkbox>
<by-checkbox label="线下主题活动" name="type">线下主题活动</by-checkbox>
<by-checkbox label="单纯品牌曝光" name="type">单纯品牌曝光</by-checkbox>
</by-checkbox-group>
</by-form-item>
<by-form-item prop="resource" label="特殊资源">
<by-radio-group v-model="formData2.resource">
<by-radio label="线上品牌商赞助">线上品牌商赞助</by-radio>
<by-radio label="线下场地免费">线下场地免费</by-radio>
</by-radio-group>
</by-form-item>
<by-form-item prop="desc" label="活动形式">
<by-input type="textarea" v-model="formData2.desc"></by-input>
</by-form-item>
<by-form-item>
<by-button type="primary" size="small" @click.prevent="handleSubmit('formLogin2')">登录</by-button>
</at-form-item>
</by-form>
</div>
```
:::
## 设置label-postion
:::demo
```html
<by-radio-group v-model="labelPosition" size="small">
<by-radio-button label="left">左对齐</by-radio-button>
<by-radio-button label="right">右对齐</by-radio-button>
<by-radio-button label="top">顶部对齐</by-radio-button>
</by-radio-group>
<div style="width: 400px; margin-top: 20px;">
<by-form :model="formData3" :rules="ruleLogin3" ref="formLogin3" :label-width="80" :label-position="labelPosition">
<by-form-item prop="name" label="活动名称">
<by-input v-model="formData3.name"></by-input>
</by-form-item>
<by-form-item label="活动形式">
<by-input type="textarea" v-model="formData3.desc"></by-input>
</by-form-item>
<by-form-item>
<by-button type="primary" size="small" @click.prevent="handleSubmit('formLogin3')">登录</by-button>
</at-form-item>
</by-form>
</div>
```
:::
## API
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|-------------|---------------------------------------------------------------------------------------|---------|--------|--------|
| model | 表单数据对象 | object | — | — |
| rules | 表单验证规则 | object | — | — |
| inline | 行内表单模式 | Boolean | — | false |
| label | 表单域标签的内容 | string | — | — |
| label-width | 表单域标签的宽度,例如 '50'。作为 Form 直接子元素的 form-item 会继承该值。支持 auto。 | number | — | — |
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class ByFormMd extends Vue {
labelPosition = 'right';
formData1 = {
username: '',
password: '',
remember: true
}
formData2 = {
name: '',
area: '',
delivery: false,
type: [],
resource: '',
desc: '',
}
formData3 = {}
ruleLogin1 = {
username: [{
required: true,
message: '请输入用户名',
trigger: 'blur'
}],
password: [{
required: true,
message: '请输入密码',
trigger: 'blur'
}, {
type: 'string',
min: 6,
message: '密码长度不能小于6',
trigger: 'blur'
}]
}
ruleLogin2 = {
name: [{
required: true,
message: '请输入活动名称',
trigger: 'blur'
}],
// area: [{
// required: true,
// message: '请输入密码',
// trigger: 'blur'
// }, {
// type: 'string',
// min: 6,
// message: '密码长度不能小于6',
// trigger: 'blur'
// }],
type: [{
type: 'array',
required: true,
message: '请至少选择一个活动性质',
trigger: 'change'
}],
resource: [{
required: true,
message: '请选择特殊资源',
trigger: 'blur'
}],
desc: [{
required: true,
message: '请输入活动形式',
trigger: 'blur'
}],
}
ruleLogin3 = {}
handleSubmit (name) {
this.$refs[name].validate(valid => {
if (valid) {
this.$notify({
type: 'success',
message: '提交成功'
})
} else {
this.$notify({
type: 'error',
message: '校验失败'
})
}
})
}
}
</script>
<style lang="sass" scoped>
.by-checkbox-group{
width: 320px;
margin: 0;
padding: 0;
list-style: none;
.by-checkbox {
float: left;
width: 160px;
margin: 0;
padding: 0;
}
}
</style>
<file_sep>/src/components/notification/index.ts
import Notification from './src/notification';
export default Notification;
<file_sep>/src/mixins/popover.ts
import { Vue, Component, Prop, Model } from 'vue-property-decorator';
let $: any;
if (typeof window !== 'undefined') {
$ = require('../utils/NodeList.js').default
}
@Component
export default class PopoverMixin extends Vue {
@Prop()
trigger?: string;
@Prop()
title?: string;
@Prop({
default: ''
})
content?: string;
@Prop({
default: true
})
header?: boolean;
@Prop({
default: 'top'
})
placement?: string;
@Prop({
default: false
})
value?: boolean;
show = this.value;
position = {
top: 0,
left: 0
};
_trigger: any = null;
_timer: any = null;
toggle() {
this.show = !this.show
this.$emit('toggle', this.show)
if (!this.show) return
this.setPopoverPosition()
}
showPopover() {
this.show = true
this.setPopoverPosition()
}
hidePopover() {
this.show = false
}
handleMouseEnter() {
this.showPopover()
clearTimeout(this._timer)
}
handleMouseLeave() {
this._timer = setTimeout(() => {
this.hidePopover()
}, 200)
}
setPopoverPosition() {
this.$nextTick(() => {
const popover:any = this.$refs.popover;
const trigger:any = this.$refs.trigger;
switch (this.placement) {
case 'top':
this.position.left = trigger.offsetLeft - (popover.offsetWidth / 2) + (trigger.offsetWidth / 2)
this.position.top = trigger.offsetTop - popover.offsetHeight
break
case 'top-left':
this.position.left = trigger.offsetLeft
this.position.top = trigger.offsetTop - popover.offsetHeight
break
case 'top-right':
this.position.left = trigger.offsetLeft + trigger.offsetWidth - popover.offsetWidth
this.position.top = trigger.offsetTop - popover.offsetHeight
break
case 'left':
this.position.left = trigger.offsetLeft - popover.offsetWidth
this.position.top = trigger.offsetTop + (trigger.offsetHeight / 2) - (popover.offsetHeight / 2)
break
case 'left-top':
this.position.left = trigger.offsetLeft - popover.offsetWidth
this.position.top = trigger.offsetTop
break
case 'left-bottom':
this.position.left = trigger.offsetLeft - popover.offsetWidth
this.position.top = trigger.offsetTop + trigger.offsetHeight - popover.offsetHeight
break
case 'right':
this.position.left = trigger.offsetLeft + trigger.offsetWidth
this.position.top = trigger.offsetTop + (trigger.offsetHeight / 2) - (popover.offsetHeight / 2)
break
case 'right-top':
this.position.left = trigger.offsetLeft + trigger.offsetWidth
this.position.top = trigger.offsetTop
break
case 'right-bottom':
this.position.left = trigger.offsetLeft + trigger.offsetWidth
this.position.top = trigger.offsetTop + trigger.offsetHeight - popover.offsetHeight
break
case 'bottom':
this.position.left = trigger.offsetLeft - (popover.offsetWidth / 2) + (trigger.offsetWidth / 2)
this.position.top = trigger.offsetTop + trigger.offsetHeight
break
case 'bottom-left':
this.position.left = trigger.offsetLeft
this.position.top = trigger.offsetTop + trigger.offsetHeight
break
case 'bottom-right':
this.position.left = trigger.offsetLeft + trigger.offsetWidth - popover.offsetWidth
this.position.top = trigger.offsetTop + trigger.offsetHeight
break
default:
// if user set wrong placement, then use default 'top'
this.position.left = trigger.offsetLeft - (popover.offsetWidth / 2) + (trigger.offsetWidth / 2)
this.position.top = trigger.offsetTop - popover.offsetHeight
break
}
popover.style.top = `${this.position.top}px`
popover.style.left = `${this.position.left}px`
})
}
doDestory() {
if (this._trigger) {
$(this._trigger).off()
}
}
mounted() {
const trigger = this.$refs.trigger;
// const parent = this.$refs.parent
// const events = {
// hover: 'mouseenter mouseleave',
// focus: 'focus blur'
// }
// let showEvent = events[this.trigger] || 'click'
if (!trigger) {
return console.error('Could not find trigger ref in your component that uses popovermixin')
}
this._trigger = trigger;
if (this.trigger === 'click') {
$(trigger).on('click', this.toggle)
} else if (this.trigger === 'hover') {
$(trigger).on('mouseenter', this.handleMouseEnter)
$(trigger).on('mouseleave', this.handleMouseLeave)
} else if (this.trigger === 'focus') {
$(trigger).on('focus', this.showPopover)
$(trigger).on('blur', this.hidePopover)
}
}
}
<file_sep>/build/webpack/webpack.base.config.ts
import * as path from 'path';
import * as webpack from 'webpack';
import * as VueLoaderPlugin from 'vue-loader/lib/plugin';
import * as MarkdownItContainer from 'markdown-it-container';
import * as markdownItAnchor from 'markdown-it-anchor';
const slugify = require('transliteration').slugify;
import * as MiniCssExtractPlugin from 'mini-css-extract-plugin';
import env from '../config/env';
const striptags = require('./tools/strip-tags');
const utils = require('./tools/utils');
const mode = process.env.ENV;
const isProduction = (mode === "production");
module.exports = {
output: {
path: path.resolve('dist'),
},
resolve: {
alias: {
"@": path.resolve("src"),
"@docs": path.resolve("docs"),
"mixins": path.resolve("src/mixins"),
"By-UI": path.resolve("src")
},
extensions: ['.ts', '.tsx', '.js']
},
module: {
rules: [
{
test: /\.vue$/,
exclude: /node_modules/,
loader: "vue-loader",
options: {
parallel: false
}
},
{
test: /\.md$/,
use: [
{
loader: 'vue-loader'
},
{
loader: 'vue-markdown-loader/lib/markdown-compiler',
options: {
raw: true,
preprocess: (MarkdownIt, source) => {
MarkdownIt.renderer.rules.table_open = function () {
return '<table class="table">'
}
// 对于代码块去除v-pre,添加高亮样式
MarkdownIt.renderer.rules.fence = utils.wrapCustomClass(MarkdownIt.renderer.rules.fence)
return source
},
use: [
[markdownItAnchor, {
level: 2, // 添加超链接锚点的最小标题级别, 如: #标题 不会添加锚点
slugify: slugify, // 自定义slugify, 我们使用的是将中文转为汉语拼音,最终生成为标题id属性
permalinkClass: 'anchor',
permalink: true, // 开启标题锚点功能
permalinkBefore: true, // 在标题前创建锚点
permalinkHref: (slug, state) => `javascript:toAnchor('${slug}')`,
}],
[MarkdownItContainer, 'demo', {
validate: params => params.trim().match(/^demo\s*(.*)$/),
render: (tokens, idx) => {
if (tokens[idx].nesting === 1) {
const html = utils.convertHtml(striptags(tokens[idx + 1].content, 'script'))
return `<demo-box>
<div slot="demo">${html}</div>
<div slot="source-code">`
}
// closing tag
return '</div></demo-box>'
}
}]
]
}
},
],
},
{
test: /\.js$/,
use: [{
loader: "babel-loader",
}],
exclude: /node_modules/,
},
{
test: /\.yml$/,
loader: 'json-loader!yaml-loader'
},
{
test: /\.tsx?$/,
exclude: /node_modules/,
use: [
{
loader: "babel-loader",
options: {
cacheDirectory: true
}
},
{
loader: "ts-loader",
options: {
appendTsxSuffixTo: [/\.vue$/],
transpileOnly: true
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
hmr: !isProduction,
// publicPath: '../'
},
},
{
loader: "css-loader",
options: {
sourceMap: !isProduction
}
},
{
loader: "sass-loader",
options: {
sourceMap: !isProduction
}
},
]
}, {
test: /\.(png|jpe?g|gif|svg)$/,
include: /image/,
loader: "url-loader",
query: {
limit: 1,
name: "asset/images/[hash:16].[ext]"
}
},
{
test: /\.(ttf|woff2?|eot|svg)$/,
include: /font/,
loader: "url-loader",
query: {
limit: 1,
name: "asset/fonts/[name].[hash:7].[ext]"
}
}
]
},
optimization: {
splitChunks: {
chunks: "all",
maxInitialRequests: 30,
maxAsyncRequests: 30,
minSize: 2048,
cacheGroups: {
default: {
priority: -20,
reuseExistingChunk: true,
minChunks: 20,
},
'vendors/library': {
name: 'vendors/library',
test: /[\\/]node_modules[\\/]/,
priority: -10,
},
'vendors/vue-bucket': {
name: 'vendors/vue-bucket',
test: /[\\/]node_modules[\\/](vue|vue-router|vuex|vue-class-component)[\\/]/,
priority: -1
},
}
},
runtimeChunk: {
name: 'vendors/manifest',
}
},
performance: {
hints: false
},
plugins: [
new VueLoaderPlugin(),
new MiniCssExtractPlugin({
filename: isProduction ? '[name].[contenthash].css' : '[name].css',
chunkFilename: isProduction ? '[name].[contenthash].css' : '[name].css'
}),
new webpack.DefinePlugin({
'process.env': {
domain: JSON.stringify(env.domain),
host: JSON.stringify(env.host),
customize: JSON.stringify(env.customize),
},
}),
],
}
<file_sep>/src/components/notification/src/notification.ts
import Vue from 'vue';
import NotificationVue from './notification.vue';
const NotificationConstructor = Vue.extend(NotificationVue);
const noticeType = ['success', 'error', 'warning', 'info'];
const instances: any[] = [];
let instance;
let seed = 1;
let zindexSeed = 1010;
const Notification = (options: any) => {
if (Vue.prototype.$isServer) return;
options = options || {};
const onClose = options.onClose;
const id = `notification_${seed++}`;
options.onClose = function () {
Notification.close(id, onClose)
};
instance = new NotificationConstructor({
data: options
});
instance.id = id;
instance.vm = instance.$mount();
document.body.appendChild(instance.vm.$el);
instance.vm.isShow = true;
instance.dom = instance.vm.$el;
instance.dom.style.zIndex = (zindexSeed++);
const offset = 0;
let topDist = offset;
for (let i = 0, len = instances.length; i < len; i++) {
topDist += instances[i].$el.offsetHeight + 16
}
topDist += 16
instance.top = topDist;
instances.push(instance);
return instance.vm;
}
Notification.close = function (id: number | string, onClose: any) {
const len = instances.length;
let index:any;
let removedHeight;
let i = 0;
for (i = 0; i < len; i++) {
if (id === instances[i].id) {
if (typeof onClose === 'function') {
onClose(instances[i])
}
index = i
removedHeight = instances[i].dom.offsetHeight
instances.splice(i, 1)
break
}
}
if (len > 1) {
for (i = index; i < len - 1; i++) {
instances[i].dom.style.top = `${parseInt(instances[i].dom.style.top) - removedHeight - 16}px`
}
}
}
noticeType.forEach(type => {
Notification[type] = (options: any) => {
if (typeof options === 'string') {
options = {
message: options
}
}
options.type = type
return Notification(options)
}
})
export default Notification;
<file_sep>/src/components/input-number/index.ts
import InputNumber from './src/input-number.vue'
Object.defineProperty(InputNumber, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-input-number', InputNumber);
}
})
export default InputNumber
<file_sep>/src/locale/lang/de.ts
export default {
by: {
select: {
placeholder: 'Auswählen',
notFoundText: 'keine Übereinstimmung'
},
modal: {
okText: 'Bestätigen',
cancelText: 'Abbrechen'
},
pagination: {
prevText: 'Vorherige Seite',
nextText: 'Nächste Seite',
total: 'Gesamt',
item: 'Inhalt',
items: 'Inhalte',
pageSize: '/ Seite',
goto: 'Gehe zu',
pageText: '',
prev5Text: 'Vorherige 5 Seiten',
next5Text: 'Nächste 5 Seiten'
},
table: {
emptyText: 'Keine Daten'
}
}
}
<file_sep>/build/webpack/webpack.components.config.ts
import * as webpack from 'webpack';
import * as merge from 'webpack-merge';
import * as FriendlyErrorsWebpackPlugin from 'friendly-errors-webpack-plugin';
import * as baseConfig from './webpack.base.config';
import byui from '../config/by-ui';
let notes = [
`Compile Building Components Successful!`
];
module.exports = merge(baseConfig, {
mode: 'production',
entry: {
main: './src/index.ts'
},
output: {
filename: 'by.js',
library: 'by',
libraryTarget: 'umd'
},
externals: {
vue: {
root: 'Vue',
commonjs: 'vue',
commonjs2: 'vue',
amd: 'vue'
}
},
optimization: {
splitChunks: false,
runtimeChunk: false
},
plugins: [
new webpack.BannerPlugin({
banner: `/*! BY-UI v${require('../../package.json').version} | MIT License */`,
raw: true,
entryOnly: true
}),
new FriendlyErrorsWebpackPlugin({
compilationSuccessInfo: {
messages: [
...byui
],
notes: [
...notes
],
},
}),
]
})
<file_sep>/src/components/alert/index.ts
import Alert from './src/alert.vue'
Object.defineProperty(Alert, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-alert', Alert);
}
})
export default Alert
<file_sep>/src/components/timeline-item/index.ts
import TimeLineItem from '../timeline/src/timeline-item.vue';
Object.defineProperty(TimeLineItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-time-line-item', TimeLineItem);
}
})
export default TimeLineItem
<file_sep>/src/components/select/index.ts
import Select from './src/select.vue'
Object.defineProperty(Select, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-select', Select);
}
})
export default Select
<file_sep>/src/components/input/index.ts
import Input from './src/input.vue'
Object.defineProperty(Input, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-input', Input);
}
})
export default Input
<file_sep>/src/components/radio-button/index.ts
import RadioButton from '../radio/src/radio-button.vue'
Object.defineProperty(RadioButton, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-radio-button', RadioButton);
}
})
export default RadioButton
<file_sep>/docs/resources/directives/clipboard/clipboard.ts
/**
* vue clipboard base on clipboard.js
* https://github.com/zhuowenli/vue-clipboards/blob/master/src/vue-clipboards.js
*/
const Clipboard = require('clipboard')
if (!Clipboard) {
throw new Error('[vue-clipboard] Cannot locate clipboard.js')
}
function isDom(obj: any) {
return typeof (window as any).HTMLElement === 'object'
? obj instanceof (window as any).HTMLElement
: obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string'
}
export default function (Vue: any) {
const clipboard = {}
const DEFAULTKEY = 'DEFAULT'
Vue.directive('clipboard', {
bind(el: any, binding: any, vnode: any) {
const option: any = {}
const key = (vnode.key || vnode.key === 0) ? vnode.key : DEFAULTKEY
let text = binding.value
let $parent = null
if (text) {
if (typeof text === 'function') {
text = text()
}
if (/(string|number)/.test(typeof text)) {
option.text = () => text
} else {
throw new Error('[vue-clipboard] Invalid value.')
}
}
if (vnode.data.attrs && vnode.data.attrs.model) {
$parent = isDom(vnode.data.attrs.model) ? vnode.data.attrs.model : document.querySelector(vnode.data.attrs.model)
}
if (vnode.elm.offsetParent) {
option.container = vnode.elm.offsetParent
} else if (isDom($parent)) {
option.container = $parent
} else {
option.container = el.parentElement || document.body
}
clipboard[key] = new Clipboard(el, option)
const { comoponentOptions, data } = vnode
const listeners = comoponentOptions ? comoponentOptions.listeners : null
const on = data ? data.on : null
const events = listeners || on
if (events && typeof events === 'object' && Object.keys(events).length) {
Object.keys(events).map(
cb => clipboard[key].on(cb, events[cb].fn || events[cb].fns)
)
}
return clipboard[key]
},
unbind(vnode: any) {
const key = (vnode.key || vnode.key === 0) ? vnode.key : DEFAULTKEY
if (clipboard[key] && clipboard[key].destroy) {
clipboard[key].destroy()
clipboard[key] = null
}
},
update(el: any, binding: any, vnode: any) {
binding.def.unbind(vnode)
binding.def.bind(el, binding, vnode)
}
})
}
<file_sep>/src/components/switch/index.ts
import Switch from './src/switch.vue'
Object.defineProperty(Switch, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-switch', Switch);
}
})
export default Switch
<file_sep>/docs/markdown/message.md
# Message 全局提示
----
相比 `Notification`,`Message` 更轻量,居中显示在页面顶部,用于展示全局消息,例如操作的反馈信息
- 提供消息、成功、错误、警告等反馈提示
- 在顶部居中显示,并自动消失,是一种不打断用户操作的轻量级提示
我们在 `Vue.prototype` 中添加了全局对象 `$message`,我们可以直接通过 `this.$message` 操作实例
- `this.$message(config)`
- `this.$message.info(config)`
- `this.$message.success(config)`
- `this.$message.warning(config)`
- `this.$message.error(config)`
- `this.$message.loading(config)`
## 基础用法
四种类型的消息提示
:::demo
```html
<by-button @click="handleClick('info')">Info</by-button>
<by-button @click="handleClick('success')">Success</by-button>
<by-button @click="handleClick('warning')">Warning</by-button>
<by-button @click="handleClick('error')">Error</by-button>
<script>
export default {
methods: {
handleClick (type) {
if (type === 'info') {
this.$message.info('这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息')
} else if (type === 'success') {
this.$message.success('这是一条成功信息')
} else if (type === 'warning') {
this.$message.warning('这是一条警告信息')
} else if (type === 'error') {
this.$message.error('这是一条错误信息')
}
}
}
}
</script>
```
:::
## 修改延时
提示默认的显示时长为 `3s`,可传递 `duration` 来自定义时长
:::demo
```html
<by-button @click="changeDuration">修改延时</by-button>
<script>
export default {
methods: {
changeDuration () {
this.$message.info({
message: '这是一条提示信息,10s 后自动关闭',
duration: 10000
})
}
}
}
</script>
```
:::
## 加载中
`this.$message.loading` 返回关闭方法,可用于手动关闭提示框
:::demo
```html
<by-button @click="showLoading">显示加载中...</by-button>
<script>
export default {
methods: {
showLoading () {
const loading = this.$message.loading({
message: '加载中...',
duration: 0
})
setTimeout(loading, 3000)
}
}
}
</script>
```
:::
## 单独引用
通过 `import` 方式引用
:::demo
```html
<by-button @click="handleImportClick('info')">Info</by-button>
<by-button @click="handleImportClick('success')">Success</by-button>
<by-button @click="handleImportClick('warning')">Warning</by-button>
<by-button @click="handleImportClick('error')">Error</by-button>
<script>
export default {
methods: {
handleImportClick (type) {
if (type === 'info') {
Message.info('这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息')
} else if (type === 'success') {
Message.success('这是一条成功信息')
} else if (type === 'warning') {
Message.warning('这是一条警告信息')
} else if (type === 'error') {
Message.error('这是一条错误信息')
}
}
}
}
</script>
```
:::
## Message 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| type | 全局提示的类别 | String | `success`, `error`, `warning`, `info` | `info` |
| message | 提示的内容 | String | - | - |
| duration | 自动关闭的延时,默认为 `3000` 毫秒 | Number | - | 3000 |
| icon | 自定义类别ICON | String | - | `info` |
| onClose | 关闭提示框时的回调函数 | Function | - | - |
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
import { Message } from 'By-UI'
@Component
export default class MyComponent extends Vue {
handleClick (type) {
if (type === 'info') {
this.$message.info('这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息')
} else if (type === 'success') {
this.$message.success('这是一条成功信息')
} else if (type === 'warning') {
this.$message.warning('这是一条警告信息')
} else if (type === 'error') {
this.$message.error('这是一条错误信息')
}
}
handleImportClick (type) {
if (type === 'info') {
Message.info('这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息这是一条提示信息')
} else if (type === 'success') {
Message.success('这是一条成功信息')
} else if (type === 'warning') {
Message.warning('这是一条警告信息')
} else if (type === 'error') {
Message.error('这是一条错误信息')
}
}
changeDuration () {
this.$message.info({
message: '这是一条提示信息,10s 后自动关闭',
duration: 10000
})
}
showLoading () {
const loading = this.$message.loading({
message: '加载中...',
duration: 0
})
setTimeout(loading, 3000)
}
mounted(){
console.log(Message);
}
}
</script>
<file_sep>/src/components/breadcrumb/index.ts
import Breadcrumb from './src/breadcrumb.vue'
Object.defineProperty(Breadcrumb, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-breadcrumb', Breadcrumb);
}
})
export default Breadcrumb
<file_sep>/build/inquirer/index.ts
const shell = require('shelljs');
const inquirer = require('inquirer');
const chalk = require('chalk');
const question = [
{
type: 'list',
name: 'compile',
message: 'What do you want to compile?',
choices: ['docs - 文档', 'components - 组件', 'all - 全部']
}
];
/**
* 编译源码
* answers 用户所选答案
*/
async function compile(answers) {
// 编译什么项目
let command = '';
switch (answers.compile) {
case 'docs - 文档':
command = 'npm run build:docs'
break;
case 'components - 组件':
command = 'npm run build:components'
break;
case 'all - 全部':
command = 'npm run build:docs'
break;
default:
break;
}
console.log(`${chalk.blue('Start compiling...')}`);
shell.exec(command, {
silent: true, // true 不会回显控制台
}, (code, stdout, stderr) => {
console.log(stdout);
})
}
inquirer.prompt(question)
.then((answers) => {
for (let item of question)
console.log(`${chalk.green(item.message)}:${chalk.red(answers[item.name])}`);
compile(answers);
});
<file_sep>/docs/markdown/select.md
# Select 选择器
---
## 基础用法
基本用法,可添加 `disabled` 属性禁用选择器
:::demo
```html
<by-select v-model="model1" style="width:100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州广州广州广州广州广州广州广州广州广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
</by-select>
<by-select v-model="model2" style="width:100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
</by-select>
<by-select v-model="model2" disabled style="width:100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
</by-select>
```
:::
## 不同尺寸
可设置 `size` 属性控制选择器大小,提供三种尺寸:`large`,`normal`,`small`
:::demo
```html
<by-select v-model="model3" size="small" style="width: 100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
</by-select>
<by-select v-model="model3" size="normal" style="width: 100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
</by-select>
<by-select v-model="model3" size="large" style="width: 100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
</by-select>
```
:::
## 可清空选择
设置 `clearable` 属性可清空已选项,仅适用于单选选择器
:::demo
```html
<by-select v-model="model4" clearable size="large" style="width: 100px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
</by-select>
```
:::
## 分组选项
选项可通过使用 `AtOptionGroup` 组件进行分组,分组的名称可使用属性 `label` 设置
:::demo
```html
<by-select v-model="model5" style="width: 100px">
<by-option-group label="广东省">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">珠海</by-option>
</by-option-group>
<by-option-group label="其他">
<by-option value="4">上海</by-option>
<by-option value="5">北京</by-option>
<by-option value="6" disabled>成都</by-option>
<by-option value="7">昆明</by-option>
<by-option value="8">杭州</by-option>
</by-option-group>
</by-select>
```
:::
## 自定义模板
可自定义 `AtOption` 显示的内容,但是请给 `AtOption` 添加 `label` 属性,这可以让选择器优先显示选项的 `label` 值,而不是内容本身
:::demo
```html
<by-select v-model="model6" style="width: 140px">
<by-option value="1" label="深圳"
><span>深圳</span
><span style="float: right;opacity: .6;font-size: 0.8em;"
>Shenzhen</span
></by-option
>
<by-option value="2" label="广州"
><span>广州</span
><span style="float: right;opacity: .6;font-size: 0.8em;"
>Guangzhou</span
></by-option
>
<by-option value="3" label="上海"
><span>上海</span
><span style="float: right;opacity: .6;font-size: 0.8em;"
>Shanghai</span
></by-option
>
<by-option value="4" label="北京"
><span>北京</span
><span style="float: right;opacity: .6;font-size: 0.8em;"
>Beijin</span
></by-option
>
<by-option value="5" label="成都"
><span>成都</span
><span style="float: right;opacity: .6;font-size: 0.8em;"
>Chengdu</span
></by-option
>
</by-select>
```
:::
## 多选列表
设置 `multiple` 属性可开启多项选择器,此时绑定的 `model` 将接受数组类型的数据
:::demo
```html
<by-select v-model="model7" multiple style="width: 240px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
</by-select>
```
:::
## 可搜索列表
添加 `filterable` 属性开启选择列表的可搜索功能
:::demo
```html
<by-select v-model="model8" filterable size="large" style="width: 240px">
<by-option value="1">深圳</by-option>
<by-option value="2">广州</by-option>
<by-option value="3">上海</by-option>
<by-option value="4">北京</by-option>
<by-option value="5">成都</by-option>
<by-option value="6">厦门</by-option>
<by-option value="7">昆明</by-option>
<by-option value="8">杭州</by-option>
</by-select>
```
:::
## Select 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
| :------------- | :--------------------------------------------- | :---------------------- | :------------------------- | :--------- |
| value | 指定当前组件的 value 值,可通过 `v-model` 绑定 | String / Number / Array | - | - |
| multiple | 是否支持多选 | Boolean | - | false |
| disabled | 是否禁用选择器 | Boolean | - | false |
| clearable | 是否支持清空功能 | Boolean | - | false |
| filterable | 是否支持搜索功能 | Boolean | - | false |
| placeholder | 选择器的占位文案 | String | - | 请选择 |
| size | 设置选择器的尺寸 | String | `large`, `normal`, `small` | normal |
| notFoundText | 搜索无结果的提示 | String | - | 无匹配数据 |
| placement | `dropdown` 出现的位置 | String | `top`, `bottom` | bottom |
| valueWithLabel | 是否将 `label` 值一并返回,默认只返回 `value` | Boolean | - | false |
## Select 事件
| 事件名称 | 说明 | 返回值 |
| --------- | ------------------ | ---------------------------------------------------- |
| on-change | 绑定的值变化时触发 | 选中的选项值,类型为 `String`,`Number` 或者 `Array` |
<script lang="ts">
import { Vue, Component, Prop, PropSync, Watch, Mixins, Provide } from "vue-property-decorator";
export default class Dropdown extends Vue {
model1=''
model2='2'
model3=''
model4=''
model5=''
model6=''
model7=new Array()
model8=''
}
// export default {
// data () {
// return {
// model1: '',
// model2: '2',
// model3: '',
// model4: '',
// model5: '',
// model6: '',
// model7: [],
// model8: '',
// }
// }
// }
</script>
<file_sep>/src/directives/clickoutside.ts
import { DirectiveOptions } from 'vue';
const clickoutsideContext = '@@clickoutsideContext';
const ClickOutside: DirectiveOptions = {
bind(el: any, binding, vnode: any) {
const documentHandler = function (e: any) {
if (!vnode.context || el.contains(e.target)) {
return false;
}
if (binding.expression) {
vnode.context[el[clickoutsideContext].methodName](e);
} else {
el[clickoutsideContext].bindingFn(e);
}
};
el[clickoutsideContext] = {
documentHandler,
methodName: binding.expression,
bindingFn: binding.value,
};
setTimeout(() => {
document.addEventListener('click', documentHandler);
}, 0);
},
update(el: any, binding) {
el[clickoutsideContext].methodName = binding.expression;
el[clickoutsideContext].bindingFn = binding.value;
},
unbind(el: any) {
document.removeEventListener('click', el[clickoutsideContext].documentHandler);
},
};
export default ClickOutside;
<file_sep>/docs/markdown/rate.md
# Rate 评分
---
评分组件
## 基础用法
最简单的用法。
:::demo
```html
<by-rate></by-rate>
```
:::
## 文案展现
给评分组件加上文案展示。
:::demo
```html
<by-rate :show-text="true" v-model="value2">
<span>{{ value2 }} 星</span>
</by-rate>
```
:::
## 其他图标
可以将星星替换为其他图标。
:::demo
```html
<by-rate icon="icon-heart-on"></by-rate>
```
:::
## 半星
支持选中半星。
:::demo
```html
<by-rate :allow-half="true"
:show-text="true"
:value="valueHalfStar"
@on-change="onStarChange"
@on-hover-change="onHoverChange">
</by-rate>
```
:::
## 只读
只读,无法进行鼠标交互。
:::demo
```html
<by-rate :allow-half="true"
:show-text="true"
:value="valueReadonly"
:disabled="true">
</by-rate>
```
:::
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class ByRateMd extends Vue {
value2 = 3;
value1 = 2.5;
valueHalfStar = 1;
valueReadonly = 3;
onStarChange(val:number){
console.log(val);
}
onHoverChange(val:number){
console.log(val);
}
}
</script>
## Rate 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|------------|--------------------|---------|--------|-------------|
| count | star 总数 | Number | - | 5 |
| value | 当前值 | String | - | 0 |
| allow-half | 是否允许选择半颗星 | Boolean | - | `false` |
| disabled | 只读,无法进行交互 | Boolean | - | `false` |
| icon | 指定图标 | String | - | `icon-star` |
| show-text | 实现显示辅助文案 | Boolean | - | `false` |
## Rate 事件
| 事件名称 | 说明 | 返回值 |
|-----------------|--------------------------------------|------------|
| on-change | star 数目改变时触发 | 改变后的值 |
| on-hover-change | 鼠标在 star 上移动导致数值变化时触发 | 改变后的值 |
## Rate slot
| 名称 | 说明 |
|------|----------------------|
| - | 自定义展示文案的内容 |
<file_sep>/src/components/radio/index.ts
import Radio from './src/radio.vue'
Object.defineProperty(Radio, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-radio', Radio);
}
})
export default Radio
<file_sep>/src/components/badge/index.ts
import Badge from './src/badge.vue'
Object.defineProperty(Badge, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-badge', Badge);
}
})
export default Badge
<file_sep>/docs/components/index.ts
import Vue, { PluginObject } from 'vue';
import ByHeader from './header/index.vue';
import ByFooter from './footer/index.vue';
import BySlider from './slidebar/index.vue';
import IconList from './icon-list/index.vue';
import DemoBox from './demobox/index.vue'; // md文件代码块
const Components: PluginObject<never> = {
install(Vue) {
Vue.component('by-header', ByHeader);
Vue.component('by-footer', ByFooter);
Vue.component('by-slider-bar', BySlider);
Vue.component('icon-list', IconList);
Vue.component('demo-box', DemoBox);
}
}
Vue.use(Components);
<file_sep>/docs/markdown/introduction.md
# 介绍
-----
By-UI 是一款基于 Vue.js 2.0 的前端 UI 组件库,主要用于快速开发 PC 网站中后台产品
<file_sep>/src/components/table/index.ts
import Table from './src/table.vue'
Object.defineProperty(Table, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-table', Table);
}
})
export default Table
<file_sep>/docs/index.ts
import Vue from 'vue'
import router from './vue-router';
import App from './app.vue';
/******** 公共包 ********/
import { i18n } from './packages/i18n';
/******** 文档全局组件 ********/
import './components'
/******** 公共UI及样式 ********/
// import '../_intermediate/iconfonts/by-icon.scss';
import '@/by-ui-style/src/index.scss';
import '@docs/assets/style/docs.scss';
/******** 公共directives ********/
import './directives'
/******** UI组件 ********/
import * as ByUI from 'By-UI/index';
Vue.use(ByUI)
new Vue({
el: '#by-ui',
i18n,
router,
render: h => h(App)
});
<file_sep>/src/components/timeline/index.ts
import TimeLine from './src/timeline.vue';
Object.defineProperty(TimeLine, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-time-line', TimeLine);
}
})
export default TimeLine
<file_sep>/src/components/collapse/index.ts
import Collapse from './src/collapse.vue'
Object.defineProperty(Collapse, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-collapse', Collapse);
}
})
export default Collapse
<file_sep>/tsconfig.json
{
"compileOnSave": false,
"include": ["@declaration", "src", "docs"],
"exclude": ["node_modules"],
"compilerOptions": {
"target": "es5",
"module": "esnext",
"moduleResolution": "node",
// 启用:
// --noImplicitAny:报告使用隐含any类型提高表达式和声明的错误
// --noImplicitThis:报告this使用隐含any类型时的错误
// --alwaysStrict:
// --strictNullChecks:在严格的空检查模式中,null和undefined值不在每种类型的域中,并且只能分配给它们any(undefined可以分配的一个例外void)
// --strictFunctionTypes:禁用功能类型的双变量参数检查
// --strictPropertyInitialization: 确保在构造函数中初始化非未定义的类属性
"strict": true,
"suppressImplicitAnyIndexErrors": true, // 抑制--noImplicitAny索引缺少索引签名的对象的错误。
// "noUnusedLocals": true, // 报告未使用的局部变量的错误
"forceConsistentCasingInFileNames": true, //禁止对同一文件的不一致引用
"allowSyntheticDefaultImports": true, // 允许从没有默认导出的模块进行默认导入
"experimentalDecorators": true, // 为ES6的装饰器启用实验支持
"downlevelIteration": true, // 提供迭代器全面支持
"allowJs": true,
"resolveJsonModule": true,
"lib": ["dom", "es5", "es6", "es7", "esnext", "es2015.promise"],
"jsx": "preserve",
"jsxFactory": "h",
"baseUrl": "./",
"paths": {
"@/*": ["./src/*"],
"@docs/*": ["./docs/*"],
"mixins/*": ["./src/mixins/*"],
"utils/*": ["./src/utils/*"],
"By-UI/*": ["./src/*"]
},
"sourceMap": true
},
}
<file_sep>/src/components/rate/index.ts
import Rate from './src/rate.vue'
Object.defineProperty(Rate, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-rate', Rate);
}
})
export default Rate
<file_sep>/src/components/loading-bar/vue.d.ts
import Vue from 'vue';
import { LoadingBarOption } from './model';
declare module 'vue/types/vue' {
interface Vue {
$loadingBar: {
(): void;
config(option: LoadingBarOption): void;
start(option: LoadingBarOption): void;
finish(option: LoadingBarOption): void;
error(option: LoadingBarOption): void;
update(option: LoadingBarOption): void;
};
}
}
<file_sep>/src/components/checkbox-group/index.ts
import CheckBoxGroup from '../checkbox/src/by-checkbox-group.vue'
Object.defineProperty(CheckBoxGroup, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-checkbox-group', CheckBoxGroup);
}
})
export default CheckBoxGroup
<file_sep>/@declaration/vue.plugins.d.ts
declare module 'Vivus';
declare module 'async-validator';
<file_sep>/src/locale/lang/fa-IR.ts
export default {
by: {
select: {
placeholder: 'انتخاب کنید',
notFoundText: 'موردی یافت نشد'
},
modal: {
okText: 'تایید',
cancelText: 'لغو'
},
pagination: {
prevText: 'صفحهی قبل',
nextText: 'صفحهی بعد',
total: 'تمام',
item: 'مورد',
items: 'مورد',
pageSize: '/ صفحه',
goto: 'برو به',
pageText: '',
prev5Text: 'پنج صفحهی قبلی',
next5Text: 'پنج صفحهی بعدی'
},
table: {
emptyText: 'بدون داده'
}
}
}
<file_sep>/docs/markdown/tooltip.md
# Tooltips 文字提示
----
文字提示框类似于 `HTML` 的 `title` 属性,当鼠标悬浮在元素上方时,会出现一个文字提示框
## 基本用法
鼠标悬停时,文字提示框默认显示在顶上的位置
:::demo
```html
<by-tooltip placement="top" content="提示信息">
<by-button>按钮</by-button>
</by-tooltip>
<by-tooltip content="提示信息"><span>一段文字</span></by-tooltip>
```
:::
## 自定义文字提示的内容
可通过 `slot="content"` 的方式设置文字提示的内容
:::demo
```html
<by-tooltip>
<span>文字提示</span>
<template slot="content">
<p>文字1</p>
<p>文字2</p>
</template>
</by-tooltip>
```
:::
## 不同的展示方向
`placement` 属性可设置文字提示框出现的位置,默认提供9种不同的方向
:::demo
```html
<div class="show-box">
<div class="top row col-md-16 flex-center">
<by-tooltip class="item" content="Top Left 提示文字" placement="top-left"><by-button>上左</by-button></by-tooltip>
<by-tooltip class="item" content="Top 提示文字" placement="top"><by-button>上边</by-button></by-tooltip>
<by-tooltip class="item" content="Top Right 提示文字" placement="top-right"><by-button>上右</by-button></by-tooltip>
</div>
<div class="center row col-md-16 flex-between">
<div class="left col-md-4">
<by-tooltip class="item" content="Left Top 提示文字" placement="left-top"><by-button>左上</by-button></by-tooltip>
<by-tooltip class="item" content="Left 提示文字" placement="left"><by-button>左边</by-button></by-tooltip>
<by-tooltip class="item" content="Left Bottom 提示文字" placement="left-bottom"><by-button>左下</by-button></by-tooltip>
</div>
<div class="right col-md-4">
<by-tooltip class="item" content="Right Top 提示文字" placement="right-top"><by-button>右上</by-button></by-tooltip>
<by-tooltip class="item" content="Right 提示文字" placement="right"><by-button>右边</by-button></by-tooltip>
<by-tooltip class="item" content="Right Bottom 提示文字" placement="right-bottom"><by-button>右下</by-button></by-tooltip>
</div>
</div>
<div class="bottom row col-md-16 flex-center">
<by-tooltip class="item" content="Bottom Left 提示文字" placement="bottom-left"><by-button>下左</by-button></by-tooltip>
<by-tooltip class="item" content="Bottom 提示文字" placement="bottom"><by-button>下边</by-button></by-tooltip>
<by-tooltip class="item" content="Bottom Right 提示文字" placement="bottom-right"><by-button>下右</by-button></by-tooltip>
</div>
</div>
```
:::
## Tooltip 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| content | 提示文字 | String | - | - |
| placement | 气泡框位置 | String | `top`, `top-left`, `top-right`, `left`, `left-top`, `left-bottom`, `right`, `right-top`, `right-bottom`, `bottom`, `bottom-left`, `bottom-right` | `top` |
<style lang="scss" scoped>
.by-tooltip {
& + .by-tooltip {
margin-left: 16px;
}
span {
font-size: 12px;
}
p {
color: #fff;
font-size: 12px;
}
}
.show-box {
max-width: 600px;
.by-tooltip + .by-tooltip {
margin: 0;
}
}
.top,
.bottom {
padding: 20px;
width: 100%;
.item + .item {
margin-left: 30px;
}
}
.center {
width: 100%;
.item + .item {
margin-top: 20px;
}
}
.left {
flex-direction: column;
}
.item > span {
display: inline-block;
width: 60px;
height: 32px;
line-height: 32px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 4px;
text-align: center;
cursor: pointer;
transition: all .3s;
&:hover {
color: #a0c1ff;
border-color: #a0c1ff;
}
}
</style>
<file_sep>/src/components/message/vue.d.ts
import Vue from 'vue';
declare module 'vue/types/vue' {
interface Vue {
$message: {
(option: any): void;
info(option: any): void;
success(option: any): void;
warning(option: any): void;
error(option: any): void;
loading(option: any): void;
};
}
}
<file_sep>/src/components/tabs/index.ts
import Tabs from './src/tabs.vue'
Object.defineProperty(Tabs, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-tabs', Tabs);
}
})
export default Tabs
<file_sep>/docs/markdown/popover.md
# Popover 弹出框
----
## 基本用法
默认显示在正中间,并且以 `click` 方式激活,使用方法跟 `Tooltip` 基本一样
:::demo
```html
<by-popover placement="top" title="Title" content="Top Placement">
<by-button size="small">点击</by-button>
</by-popover>
<by-popover content="Top Placement" title="Title">
一段文字
</by-popover>
```
:::
## 更改激活的方式
默认使用 `click` 方式激活,可设置 `trigger` 更换激活方式
:::demo
```html
<by-popover trigger="click" content="Top Placement">
<by-button size="small">Click</by-button>
</by-popover>
<by-popover trigger="hover" title="Title" content="Top Placement">
<by-button size="small">Hover</by-button>
</by-popover>
```
:::
## 弹出框的位置
设置属性 `placement` 可更改弹出框的位置,默认显示在顶部 `top`
:::demo
```html
<by-popover trigger="hover" content="Top Placement">
<by-button size="small">Top</by-button>
</by-popover>
<by-popover trigger="hover" content="Top Placement" placement="bottom">
<by-button size="small">Bottom</by-button>
</by-popover>
<by-popover trigger="hover" content="Top Placement" placement="left">
<by-button size="small">Left</by-button>
</by-popover>
<by-popover trigger="hover" content="Top Placement" placement="right">
<by-button size="small">Right</by-button>
</by-popover>
```
:::
## 嵌套内容
除了可以使用属性 `title` 和 `content` 设置弹出框的内容,还可以使用 `slot="title"` 和 `slot="content"` 的方式设置弹出框的嵌套内容
:::demo
```html
<by-popover placement="top" v-model="show" @toggle="toggleShow">
<by-button size="small">删除</by-button>
<template slot="content">
<p>这是一段内容,确定删除吗?</p>
<div style="text-align: right; margin-top: 8px;">
<by-button size="smaller" @click="show = false">取消</by-button>
<by-button type="primary" size="smaller" @click="show = false">确定</by-button>
</div>
</template>
</by-popover>
```
:::
## Popover 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| title | 标题文字 | String | - | - |
| content | 提示文字 | String | - | - |
| trigger | 触发的事件类型 | String | `hover`, `focus`, `click` | `click` |
| placement | 弹出框的位置 | String | `top`, `top-left`, `top-right`, `left`, `left-top`, `left-bottom`, `right`, `right-top`, `right-bottom`, `bottom`, `bottom-left`, `bottom-right` | `top` |
<style lang="scss" scoped>
.by-popover + .by-popover {
margin-left: 16px;
}
</style>
<script>
export default {
data() {
return {
show: false
}
},
methods: {
toggleShow(status) {
this.show = status
}
}
}
</script>
<file_sep>/src/components/tooltip/index.ts
import Tooltip from './src/tooltip.vue'
Object.defineProperty(Tooltip, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-tooltip', Tooltip);
}
})
export default Tooltip
<file_sep>/src/components/collapse-item/index.ts
import CollapseItem from '../collapse/src/collapse-item.vue'
Object.defineProperty(CollapseItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-collapse-item', CollapseItem);
}
})
export default CollapseItem
<file_sep>/src/components/pagination/index.ts
import Pagination from './src/pagination.vue'
Object.defineProperty(Pagination, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-pagination', Pagination);
}
})
export default Pagination
<file_sep>/src/components/dropdown/index.ts
import Dropdown from './src/dropdown.vue'
Object.defineProperty(Dropdown, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-dropdown', Dropdown);
}
})
export default Dropdown;
<file_sep>/src/mixins/two-way/index.ts
import { Vue, Component, Prop, Model } from 'vue-property-decorator';
/** Mixin:双向绑定 */
@Component
export default class TwoWay extends Vue {
@Prop()
@Model('valueChanged')
bindValue!: any;
/** 双向绑定数据 */
get currentValue() {
return this.bindValue;
}
set currentValue(value) {
this.$emit('valueChanged', value);
}
}
<file_sep>/src/locale/lang/en-US.ts
export default {
by: {
index:{
h4: 'Focus on a better user experience with a modular UI component library.',
button: 'GET STARTED',
btnGroup: [
{
title: 'Guide',
content: 'Understand design guidelines and design with uniform specifications to help product designers and front-end engineers build quickly.'
},{
title: 'Component',
content: 'Experience the interaction details through the demo of the component, the development can be referenced separately, or the component can be introduced globally.'
},{
title: 'Resource',
content: 'Products can quickly build high-fidelity prototypes with sketch tools, reducing communication costs.'
}
]
},
header: {
adminSystem: 'Admin',
component: 'Component',
guide: 'Guide'
},
color:{
themeColor:'Theme Color',
themeColorDesc:'Used to identify brand colors',
colorTitle:'Color',
colorDesc:'Uniform color matching can improve the recognition of the brand, the use of color in addition to need to consider the unity of the brand, but also need to achieve information transmission, interactive feedback and other purposes. BY-UI is made by BY Lab sand, branded in BY Blue, so the overall color matching style of BY-UI is also based on BY Blue.',
},
nav:{
color:'Color',
font:'Font',
brand:'Brand',
introduce:'Introduce',
button:'Button',
tag:'Tag',
component:'Component',
summarize:'Summarize',
baseComponent:'BaseComponent',
icon: 'Icon',
checkbox: 'Checkbox',
input: 'Input',
inputnumber: 'InputNumber',
radio: 'Radio',
rate: 'Rate',
},
select: {
placeholder: 'Select',
notFoundText: 'No matching data'
},
modal: {
okText: 'OK',
cancelText: 'Cancel'
},
pagination: {
prevText: 'Previous Page',
nextText: 'Next Page',
total: 'Total',
item: 'item',
items: 'items',
pageSize: '/ page',
goto: 'Goto',
pageText: '',
prev5Text: 'Previous 5 Pages',
next5Text: 'Next 5 Pages'
},
table: {
emptyText: 'No data'
}
}
}
<file_sep>/src/components/tab-pane/index.ts
import TabPane from '../tabs/src/tab-pane.vue'
Object.defineProperty(TabPane, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-tab-pane', TabPane);
}
})
export default TabPane
<file_sep>/src/components/textarea/index.ts
import Textarea from './src/textarea.vue'
Object.defineProperty(Textarea, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-textarea', Textarea);
}
})
export default Textarea
<file_sep>/src/components/step-item/index.ts
import StepItem from '../step/src/step-item.vue'
Object.defineProperty(StepItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-step-item', StepItem);
}
})
export default StepItem
<file_sep>/src/components/modal/index.ts
import Model from './src/modal.vue';
import Dialog from './src/dialog';
Object.defineProperty(Model, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-model', Model);
}
})
Object.assign(Model,Dialog)
export default Model
<file_sep>/docs/markdown/drawer.md
# Drawer 抽屉
有些时候, `Dialog` 组件并不满足我们的需求, 比如你的表单很长, 亦或是你需要临时展示一些文档, `Drawer` 拥有和 `Dialog` 几乎相同的 API, 在 UI 上带来不一样的体验.
### 基本用法
呼出一个临时的侧边栏, 可以从多个方向呼出
:::demo
```html
<by-radio-group v-model="direction">
<by-radio label="ltr">从左往右开</by-radio>
<by-radio label="rtl">从右往左开</by-radio>
<by-radio label="ttb">从上往下开</by-radio>
<by-radio label="btt">从下往上开</by-radio>
</by-radio-group>
<by-button @click="drawer = true" type="primary" style="margin-left: 16px;">
点我打开
</by-button>
<by-drawer
title="我是标题"
:visible.sync="drawer"
:direction="direction"
:before-close="handleClose"
@close="close"></by-drawer>
<script>
export default {
data() {
return {
drawer: false,
direction: 'rtl',
};
},
methods: {
handleClose(done) {
done();
},
close(){
console.log('close);
}
}
};
</script>
```
:::
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class drawerMd extends Vue {
drawer = false;
direction = 'rtl';
handleClose(done) {
// this.$confirm('确认关闭?').then(_ => {
// done();
// }).catch(_ => {});
done();
}
close(){
console.log('close');
}
}
</script>
<file_sep>/build/iconfont/iconfont-builder.js
const path = require('path');
const fs = require('fs');
const color = require('colors-cli');
const {
createSVG,
createTTF,
createEOT,
createWOFF,
createWOFF2,
copyTemplate
} = require("svgtofont/src/utils");
const options = {
src: path.resolve('docs/assets/icon-svgs'), // svg 图标目录路径
dist: path.resolve('_intermediate/iconfonts'), // 输出到指定目录中
fontName: 'by-icon', // 设置字体名称
fontSize: '16px',
clssaNamePrefix: 'icon',
svgicons2svgfont: {
fontHeight: 1000,
normalize: true
},
}
let cssString = [];
fs.exists("./_intermediate/iconfonts", exists => {
if (!exists) {
fs.mkdir('./_intermediate', error => {});
fs.mkdir('./_intermediate/iconfonts/', error => {})
}
createSVG(options) // SVG => SVG Font
.then(UnicodeObject => {
Object.keys(UnicodeObject).forEach(name => {
let _code = UnicodeObject[name];
cssString.push(`.${options.clssaNamePrefix}-${name}:before { content: "\\${_code.charCodeAt(0).toString(16)}"; }\n`);
});
})
.then(() => createTTF(options)) // SVG Font => TTF
.then(() => createWOFF(options)) // TTF => WOFF
.then(() => createWOFF2(options)) // TTF => WOFF2
.then(() => {
const font_temp = path.resolve(__dirname, "iconfont-builder-template");
return copyTemplate(font_temp, options.dist, {
fontname: options.fontName,
fontsize: options.fontSize || '16px',
cssString: cssString.join(""),
timestamp: new Date().getTime(),
prefix: options.clssaNamePrefix || options.fontName
});
}).then(() => {
console.log(`${color.green('✔')} Iconfont Build Success\n`)
})
})
<file_sep>/src/components/slider/index.ts
import Slider from './src/slider.vue'
Object.defineProperty(Slider, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-slider', Slider);
}
})
export default Slider
<file_sep>/docs/markdown/inputnumber.md
# InputNumber 数字输入框
----
## 基础用法
支持传入 `step` 精度,以及指定取值范围 `max` , `min`。默认 `step` 取整数 1
:::demo
```html
<p class="demo-desc">基本输入框,范围可以无递加或递减</p>
<div class="row no-gutter">
<div class="col-md-4">
<by-input-number v-model="num1"></by-input-number><br>
</div>
</div>
<p class="demo-desc">有精度输入框,step=5,step=0.5</p>
<div class="row no-gutter">
<div class="col-md-4">
<by-input-number :step="5" v-model="num2"></by-input-number>
</div>
<div class="col-md-4 col-md-offset-1">
<by-input-number :step="0.5" v-model="num3"></by-input-number>
</div>
</div>
<p class="demo-desc">有取值范围的输入框,min=0, max=20</p>
<div class="row no-gutter">
<div class="col-md-4">
<by-input-number :min="0" :max="20" v-model="num4"></by-input-number>
</div>
</div>
```
:::
## 不可用状态
设置属性 `disabled` 禁用输入框
:::demo
```html
<div class="row no-gutter">
<div class="col-md-4">
<by-input-number disabled v-model="num5"></by-input-number>
</div>
</div>
```
:::
## 不同尺寸
配置属性 `size`,可控制输入框的尺寸,默认支持三种尺寸:`large`,`normal`,`small`
:::demo
```html
<div class="row">
<div class="col-sm-12 col-md-4">
<by-input-number size="small" v-model="num6"></by-input-number>
</div>
<div class="col-sm-12 col-md-4">
<by-input-number v-model="num6"></by-input-number>
</div>
<div class="col-sm-12 col-md-4">
<by-input-number size="large" v-model="num6"></by-input-number>
</div>
</div>
```
:::
## InputNumber 参数
| 参数 | 说明 | 类型 | 可选值 | 默认值 |
|---------- |-------------- |---------- |-------------------------------- |-------- |
| value | 输入框的值,可通过 `v-model` 绑定 | Number | - | - |
| size | 输入框尺寸 | String | `small` `normal` `large` | normal |
| step | 每次递增或递减的数目 | Number | - | 1 |
| min | 最小值 | Number | - | -Infinity |
| max | 最大值 | Number | - | Infinity |
| disabled | 是否禁用输入框 | Boolean | - | false |
| readonly | 是否设置成只读 | Boolean | - | false |
| autofocus | 是否自动聚焦到输入框 | Boolean | - | false |
## InputNumber 事件
| 事件名称 | 说明 | 返回值 |
|---------- |-------------- |---------- |
| focus | 获得焦点时触发 | event |
| blur | 失去焦点时触发 | event |
| change | 绑定的值有变化时触发 | 输入框的值 |
<script lang="ts">
import { Vue, Component } from "vue-property-decorator";
@Component
export default class InputNumber extends Vue {
num1 = 0;
num2 = 0;
num3= 0;
num4 = 10;
num5 = 999.99;
num6 = 100;
}
</script>
<file_sep>/src/components/dropdown-item/index.ts
import DropdownItem from '../dropdown/src/dropdown-item.vue'
Object.defineProperty(DropdownItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-dropdown-item', DropdownItem);
}
})
export default DropdownItem
<file_sep>/README.md
# By-UI1
基于 Vue2.0 一款轻量级、模块化的高颜值前端UI组件库
使用webpack打包,typescript语法搭建的管理系统后台
说明:https://www.yuque.com/okr2gd/ng0vwv/egrrzu
```
git submodule update --init --recursive
git submodule foreach git pull https://github.com/by-ui/by-ui-style.git master
```
```
npm install
```
```
npm run icon
```
```
npm run dev
```
- vue-i18n 国际化
- vivus svg动画
- smooth-scrollbar 滚动条
<file_sep>/src/components/breadcrumb-item/index.ts
import BreadcrumbItem from '../breadcrumb/src/breadcrumb-item.vue'
Object.defineProperty(BreadcrumbItem, 'install', {
writable: false,
value: (Vue: any) => {
Vue.component('by-breadcrumb-item', BreadcrumbItem);
}
})
export default BreadcrumbItem
| 0d943fcab908fc1cc15aee658d8f98316e70b485 | [
"Markdown",
"TypeScript",
"JSON with Comments",
"JavaScript"
] | 105 | TypeScript | by-ui/by-ui | 1e0e7913f9f702e534a4923ff981b95dfad19a05 | dae97a5cd3afebfc49e99dca3ce0cc255d0d278c | |
refs/heads/master | <repo_name>mchernyavskaya/hack-days-aws-mobile-app<file_sep>/src/config/config.js
let API_GATEWAY_ROOT = 'https://fl9wpsxzkk.execute-api.eu-central-1.amazonaws.com/prod';
let config = {
apiGateway: {
processImageUrl: `${API_GATEWAY_ROOT}/v1/processimage`
},
uid: {
length: 20
},
awsmobile: {
publicBucket: "https://hackdaysawsmobileapp-userfiles-mobilehub-830251747.s3.eu-central-1.amazonaws.com/public/"
}
};
export default config; | ed87b685dd167ac3b96ef9f2cf03c1740d7cd099 | [
"JavaScript"
] | 1 | JavaScript | mchernyavskaya/hack-days-aws-mobile-app | 26b4b87dd88c853c7db94ad722da03e6ae29ab21 | d8117580e6faac0b10a7bc67817559fd825c3a06 | |
refs/heads/master | <repo_name>madwenoma/elasticsearch-demos<file_sep>/src/main/java/com/lee/learn/house/domain/House.java
package com.lee.learn.house.domain;
public class House {
private Long houseId;
private String title;
private String xiaoQu;
private Double price;
private Integer junJia;
private String jingJiRen;
private String huXing;
private String louCeng;
private Double jianZhuMianJi;
private String huXingJieGou;
private Double shiNeiMianJi;
private String jianZhuLeiXing;
private String chaoXiang;
private String jianZhuJieGou;
private String zhuangXiu;
private String tiHuBiLi;
private String gongNuanFangShi;
private String dianTi;
private String chanQuan;
public Long getHouseId() {
return houseId;
}
public void setHouseId(Long houseId) {
this.houseId = houseId;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getXiaoQu() {
return xiaoQu;
}
public void setXiaoQu(String xiaoQu) {
this.xiaoQu = xiaoQu;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getJunJia() {
return junJia;
}
public void setJunJia(Integer junJia) {
this.junJia = junJia;
}
public String getJingJiRen() {
return jingJiRen;
}
public void setJingJiRen(String jingJiRen) {
this.jingJiRen = jingJiRen;
}
public String getHuXing() {
return huXing;
}
public void setHuXing(String huXing) {
this.huXing = huXing;
}
public String getLouCeng() {
return louCeng;
}
public void setLouCeng(String louCeng) {
this.louCeng = louCeng;
}
public Double getJianZhuMianJi() {
return jianZhuMianJi;
}
public void setJianZhuMianJi(Double jianZhuMianJi) {
this.jianZhuMianJi = jianZhuMianJi;
}
public String getHuXingJieGou() {
return huXingJieGou;
}
public void setHuXingJieGou(String huXingJieGou) {
this.huXingJieGou = huXingJieGou;
}
public Double getShiNeiMianJi() {
return shiNeiMianJi;
}
public void setShiNeiMianJi(Double shiNeiMianJi) {
this.shiNeiMianJi = shiNeiMianJi;
}
public String getJianZhuLeiXing() {
return jianZhuLeiXing;
}
public void setJianZhuLeiXing(String jianZhuLeiXing) {
this.jianZhuLeiXing = jianZhuLeiXing;
}
public String getChaoXiang() {
return chaoXiang;
}
public void setChaoXiang(String chaoXiang) {
this.chaoXiang = chaoXiang;
}
public String getJianZhuJieGou() {
return jianZhuJieGou;
}
public void setJianZhuJieGou(String jianZhuJieGou) {
this.jianZhuJieGou = jianZhuJieGou;
}
public String getZhuangXiu() {
return zhuangXiu;
}
public void setZhuangXiu(String zhuangXiu) {
this.zhuangXiu = zhuangXiu;
}
public String getTiHuBiLi() {
return tiHuBiLi;
}
public void setTiHuBiLi(String tiHuBiLi) {
this.tiHuBiLi = tiHuBiLi;
}
public String getGongNuanFangShi() {
return gongNuanFangShi;
}
public void setGongNuanFangShi(String gongNuanFangShi) {
this.gongNuanFangShi = gongNuanFangShi;
}
public String getDianTi() {
return dianTi;
}
public void setDianTi(String dianTi) {
this.dianTi = dianTi;
}
public String getChanQuan() {
return chanQuan;
}
public void setChanQuan(String chanQuan) {
this.chanQuan = chanQuan;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("House{");
sb.append("title='").append(title).append('\'');
sb.append(", xiaoQu='").append(xiaoQu).append('\'');
sb.append(", price=").append(price);
sb.append(", junJia=").append(junJia);
sb.append(", jingJiRen='").append(jingJiRen).append('\'');
sb.append(", huXing='").append(huXing).append('\'');
sb.append(", louCeng='").append(louCeng).append('\'');
sb.append(", jianZhuMianJi=").append(jianZhuMianJi);
sb.append(", huXingJieGou='").append(huXingJieGou).append('\'');
sb.append(", shiNeiMianJi=").append(shiNeiMianJi);
sb.append(", jianZhuLeiXing='").append(jianZhuLeiXing).append('\'');
sb.append(", chaoXiang='").append(chaoXiang).append('\'');
sb.append(", jianZhuJieGou='").append(jianZhuJieGou).append('\'');
sb.append(", zhuangXiu='").append(zhuangXiu).append('\'');
sb.append(", tiHuBiLi='").append(tiHuBiLi).append('\'');
sb.append(", gongNuanFangShi='").append(gongNuanFangShi).append('\'');
sb.append(", dianTi='").append(dianTi).append('\'');
sb.append(", chanQuan='").append(chanQuan).append('\'');
sb.append('}');
return sb.toString();
}
}<file_sep>/src/main/java/com/lee/learn/douban/MoviePage.java
package com.lee.learn.douban;
import java.util.List;
public class MoviePage {
private List<Movie> subjects;
public List<Movie> getSubjects() {
return subjects;
}
public void setSubjects(List<Movie> subjects) {
this.subjects = subjects;
}
}
<file_sep>/src/main/java/com/lee/learn/house/rabbit/demos/DeadLetterDemoSender.java
package com.lee.learn.house.rabbit.demos;
import com.lee.learn.RabbitMQConfig;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.support.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.UUID;
@Component
public class DeadLetterDemoSender {
@Autowired
RabbitTemplate rabbitTemplate;
public void sendDeadLetterMsg(String msg) {
CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
// 声明消息处理器 这个对消息进行处理 可以设置一些参数 对消息进行一些定制化处理
MessagePostProcessor messagePostProcessor = message -> {
org.springframework.amqp.core.MessageProperties messageProperties = message.getMessageProperties();
messageProperties.setContentEncoding("utf-8");
// 设置过期时间10*1000毫秒
// messageProperties.setExpiration("10000");
return message;
};
//向延迟队列发送消息
rabbitTemplate.convertAndSend(RabbitMQConfig.delayExchange
, RabbitMQConfig.delayRoutingKey, msg, messagePostProcessor, correlationData);
}
}
<file_sep>/src/main/java/com/lee/learn/house/rabbit/demos/transaction/BarService.java
package com.lee.learn.house.rabbit.demos.transaction;
import com.lee.learn.RabbitMQConfig;
import org.springframework.amqp.AmqpRejectAndDontRequeueException;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.UUID;
//模拟另一个机器上的服务
@Service
public class BarService {
@Autowired
private JdbcTemplate jdbcTemplate;//
@Autowired
private EventManager eventManager;
@Transactional
@RabbitListener(queues = RabbitMQConfig.TRAN_FOO_SUCC_QUEUE)
public void handleFooSuccEvent(Event event) {//监听队列对象直接转为java bean
String barId = UUID.randomUUID().toString();
String barName = "bar1";
try {
jdbcTemplate.update("INSERT INTO bar(id, name) values(?,?)", barId, barName);
//抛出异常,模拟分布式事务失败
throw new RuntimeException();
}catch (Exception e) {
eventManager.sendEventQueue(RabbitMQConfig.TRAN_BAR_FAIL_QUEUE,event);
throw new AmqpRejectAndDontRequeueException(e);
}
}
}
<file_sep>/src/main/java/com/lee/learn/AppStartEvent.java
package com.lee.learn;
import com.lee.learn.douban.DoubanMovieCrawler;
import com.lee.learn.house.crawler.LianjiaCrawler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
/**
* Created by Administrator on 2018/7/17.
*/
@Component
public class AppStartEvent implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private LianjiaCrawler lianjiaCrawler;
@Autowired
private DoubanMovieCrawler doubanMovieCrawler;
@Override
@Async
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext().getParent() == null) {
System.out.println("onApplicationEvent......");
// try {
// lianjiaCrawler.start(2);
// } catch (Exception e) {
// e.printStackTrace();
// }
}
new Thread(() -> {
try {
doubanMovieCrawler.start(3);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
}
}
<file_sep>/src/main/java/com/lee/learn/house/rabbit/demos/RabbitRpcClient.java
package com.lee.learn.house.rabbit.demos;
import com.lee.learn.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class RabbitRpcClient {
@Autowired
RabbitTemplate rabbitTemplate;
public String requestHello(String msg) {
return (String) rabbitTemplate.convertSendAndReceive(RabbitMQConfig.RPC_EXCHANGE,
RabbitMQConfig.RPC_ROUTINGKEY, msg);
}
}
<file_sep>/src/test/java/com/lee/learn/disruptor/DisruptorMain.java
package com.lee.learn.disruptor;
/**
* @description disruptor代码样例。每10ms向disruptor中插入一个元素,消费者读取数据,并打印到终端
*/
import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SleepingWaitStrategy;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.dsl.ProducerType;
import java.util.concurrent.ThreadFactory;
public class DisruptorMain {
static class ElementHandler implements WorkHandler<Element> {
// @Override
// public void onEvent(Element element, long l, boolean b) throws Exception {
// long threadId = Thread.currentThread().getId();
// System.out.println("Element: " + threadId + " " + element.get());
// }
@Override
public void onEvent(Element element) {
// System.out.println(element.get());
if (element.get() == 999998) {
System.out.println("999998 end:" + System.currentTimeMillis());
}
}
}
public static void main(String[] args) throws Exception {
ThreadFactory threadFactory = new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new Thread(r, "simpleThread");
}
};
// RingBuffer生产工厂,初始化RingBuffer的时候使用
EventFactory<Element> factory = new EventFactory<Element>() {
@Override
public Element newInstance() {
return new Element();
}
};
// 处理Event的handler
// EventHandler<Element> handler = new ElementHandler();
// 阻塞策略
SleepingWaitStrategy strategy = new SleepingWaitStrategy();
// 指定RingBuffer的大小
int bufferSize = 1024 * 1024;
// 创建disruptor,采用单生产者模式
Disruptor<Element> disruptor = new Disruptor(factory, bufferSize, threadFactory,
ProducerType.SINGLE, strategy);
// 设置EventHandler
ElementHandler[] handlers = new ElementHandler[10];
for (int i = 0; i < 10; i++) {
handlers[i] = new ElementHandler();
}
// disruptor.handleEventsWith(handlers);
disruptor.handleEventsWithWorkerPool(handlers);
// 启动disruptor的线程
disruptor.start();
RingBuffer<Element> ringBuffer = disruptor.getRingBuffer();
long start = System.currentTimeMillis();
System.out.println("start " + start);
for (int l = 0; l < 999999; l++) {
// 获取下一个可用位置的下标
long sequence = ringBuffer.next();
try {
// 返回可用位置的元素
Element event = ringBuffer.get(sequence);
// 设置该位置元素的值
event.set(l);
} finally {
ringBuffer.publish(sequence);
}
// Thread.sleep(1);
}
disruptor.shutdown();
System.in.read();
}
// 队列中的元素
static class Element {
private int value;
public int get() {
return value;
}
public void set(int value) {
this.value = value;
}
} // 生产者的线程工厂
}<file_sep>/src/main/java/com/lee/learn/house/rabbit/demos/transaction/EventManager.java
package com.lee.learn.house.rabbit.demos.transaction;
import com.lee.learn.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
public class EventManager {
private static final String INSERT_SQL = "insert into event(id,event_type,module_name,module_id,create_time) values(?,?,?,?,?)";
private static final String SELECT_SQL = "select model_id from event where event_id = ?";
private final JdbcTemplate jdbcTemplate;
private final RabbitTemplate rabbitTemplate;
public EventManager(JdbcTemplate jdbcTemplate, RabbitTemplate rabbitTemplate) {
this.jdbcTemplate = jdbcTemplate;
this.rabbitTemplate = rabbitTemplate;
}
public void insertEvent(Event event) {
jdbcTemplate.update(INSERT_SQL, event.getId(), event.getEventType(),
event.getModelName(), event.getModelId(), event.getCreateTime());
}
public String queryModelId(String eventId) {
return jdbcTemplate.queryForObject(SELECT_SQL, String.class, eventId);
}
public void sendEventQueue(String queue, Event event) {
this.rabbitTemplate.convertAndSend(queue, event);
}
}
<file_sep>/src/main/java/com/lee/learn/RabbitMQConfig.java
package com.lee.learn;
import com.lee.learn.house.rabbit.demos.transaction.EventManager;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.HashMap;
import java.util.Map;
//https://blog.csdn.net/m0_37867405/article/details/80793601
//https://blog.csdn.net/itguangit/article/details/80031595
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE = "boot-topic-exchange";
public static final String ROUTINGKEY1 = "boot-routing.update";
public static final String ROUTINGKEY_DELETE = "boot-routing.delete";
public static final String ROUTINGKEY_All = "boot-routing.#";
public static final String QUEUE1 = "spring-queue";
public static final String QUEUE_ALL = "spring-queue-all";
public static final String RPC_EXCHANGE = "rpc-exchange";
public static final String RPC_ROUTINGKEY = "rpc";
public static final String RPC_QUEUE = "rpc-queue";
@Bean
public TopicExchange topicExchange() {
return new TopicExchange(EXCHANGE);
}
@Bean
public Queue queue() {
return new Queue(QUEUE1, false);
}
@Bean
public Queue queueForAll() {
return new Queue(QUEUE_ALL, false);
}
@Bean
public Binding binding() {
return BindingBuilder.bind(queue()).to(topicExchange()).with(ROUTINGKEY1);
}
@Bean
public Binding bindingDel() {
return BindingBuilder.bind(queue()).to(topicExchange()).with(ROUTINGKEY_DELETE);
}
@Bean
public Binding bindingAll() {
return BindingBuilder.bind(queueForAll()).to(topicExchange()).with(ROUTINGKEY_All);
}
///////////////////////////////////Rpc 相关 start/////////////////////////////////////
@Bean
public DirectExchange rpcExchanger() {
return new DirectExchange(RPC_EXCHANGE);
}
@Bean
public Queue rpcQueue() {
return new Queue(RPC_QUEUE, false);
}
@Bean
public Binding rpcBinding() {
return BindingBuilder.bind(rpcQueue()).to(rpcExchanger()).with(RPC_ROUTINGKEY);
}
///////////////////////////////////Rpc 相关 end/////////////////////////////////////
///////////////////////////////////死信队列 相关 start/////////////////////////////////////
public static String delayQueue = "delay_queue";
public static String delayExchange = "delay_exchange";
public static String delayRoutingKey = "delay_routing_key";
public static final String deadLetterQueue = "dead_letter_queue";
public static String deadLetterExchange = "dead_letter_exchange";
public static String deadLetterRoutingKey = "dead_letter_routing_key";
@Bean
public DirectExchange delayExchange() {
DirectExchange ret = new DirectExchange(delayExchange, true, false);
ret.setInternal(false);
return ret;
}
@Bean
public DirectExchange deadLetterExchange() {
return new DirectExchange(deadLetterExchange, true, false);
}
/**
* 延迟队列没有consumer,只是作为向dead letter queue转发消息的存储中介
* 消息开始是发送给延迟队列,30s后被转发向死信队列,消费者监听死信队列收到消息,实现定时延迟消息。
*/
@Bean
public Queue delayQueue() {
Map<String, Object> arguments = new HashMap<String, Object>();
arguments.put("x-message-ttl", 30 * 1000); // Message TTL = 30s
arguments.put("x-max-length", 1000000); // Max length = 1million
// 死信路由到死信交换器DLX
arguments.put("x-dead-letter-exchange", deadLetterExchange);
arguments.put("x-dead-letter-routing-key", deadLetterRoutingKey);
return new Queue(delayQueue, true, false, false, arguments);
}
@Bean
public Queue deadLetterQueue() {
return new Queue(deadLetterQueue, true, false, false);
}
@Bean
public Binding bindingDelay() {
return BindingBuilder.bind(delayQueue()).to(delayExchange()).with(delayRoutingKey);
}
@Bean
public Binding bindingDeadLetter() {
return BindingBuilder.bind(deadLetterQueue()).to(deadLetterExchange()).with(deadLetterRoutingKey);
}
///////////////////////////////////死信队列 相关 end/////////////////////////////////////
////////////////////////////////分布式事务相关 start/////////////////////////////////
public static final String TRAN_FOO_SUCC_QUEUE = "foo-success-queue";
public static final String TRAN_BAR_FAIL_QUEUE = "bar-failure-queue";
@Bean
public Queue successQueue() {
return new Queue(TRAN_FOO_SUCC_QUEUE);
}
@Bean
public Queue failureQueue() {
return new Queue(TRAN_BAR_FAIL_QUEUE);
}
@Bean
public Jackson2JsonMessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public EventManager eventManager(JdbcTemplate jdbcTemplate, RabbitTemplate rabbitTemplate) {
return new EventManager(jdbcTemplate, rabbitTemplate);
}
////////////////////////////////分布式事务相关 end/////////////////////////////////
// @Bean
// public SimpleMessageListenerContainer messageContainer() {
// SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
// container.setQueues(queue());
// container.setExposeListenerChannel(true);
// container.setMaxConcurrentConsumers(1);
// container.setConcurrentConsumers(1);
// container.setAcknowledgeMode(AcknowledgeMode.MANUAL); //设置确认模式手工确认
// container.setMessageListener(new ChannelAwareMessageListener() {
// @Override
// public void onMessage(Message message, Channel channel) throws Exception {
// byte[] body = message.getBody();
// System.out.println("receive msg queue: " + new String(body));
// Thread.sleep(10000);
//
// channel.basicAck(message.getMessageProperties().getDeliveryTag(), false); //确认消息成功消费
//
// }
// });
// return container;
// }
}
<file_sep>/src/main/java/com/lee/learn/house/rabbit/demos/transaction/event.sql
CREATE TABLE event (
`id` char(36) NOT NULL DEFAULT '',
`event_type` varchar(100) DEFAULT NULL,
`model_name` varchar(100) DEFAULT NULL,
`model_id` char(36) DEFAULT NULL ,
`create_time` bigint(11) DEFAULT NULL ,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE foo (
`id` char(36) NOT NULL DEFAULT '',
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8
-- 在另一个库上执行
CREATE TABLE bar (
`id` char(36) NOT NULL DEFAULT '',
`name` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
)ENGINE=InnoDB DEFAULT CHARSET=utf8<file_sep>/src/test/java/com/lee/learn/house/HouseIndexOperatorTest.java
package com.lee.learn.house;
import com.lee.learn.house.crawler.LianjiaCrawler;
import com.lee.learn.house.domain.House;
import com.lee.learn.house.domain.HouseIndexTemplate;
import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* Created by Administrator on 2018/7/16.
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class HouseIndexOperatorTest extends TestCase {
@Autowired
HouseIndexOperator operator;
@Test
public void testCreateIndex() throws Exception {
HouseIndexTemplate house = new HouseIndexTemplate();
house.setHouseId(1L);
house.setJingJiRen("xiaowang");
house.setJunJia(42333);
house.setPrice(324.0);
house.setTitle("月季园 通透");
house.setXiaoQu("月季园");
house.setChanQuan("70年");
house.setChaoXiang("南 北");
house.setDianTi("有");
house.setGongNuanFangShi("地热");
house.setHuXing("连体一户");
house.setJianZhuJieGou("");
house.setJianZhuLeiXing("");
house.setJianZhuMianJi(40.0);
house.setShiNeiMianJi(20.0);
System.out.println(operator.createIndex(house));
}
} | 2ea361049dda1faea204a4017a02a1aa07b9ced0 | [
"Java",
"SQL"
] | 11 | Java | madwenoma/elasticsearch-demos | 4db396f9108e12da630215dcece8f70e79fa550f | 4d23a92d42280ba98151fe585e398619fae636ba | |
refs/heads/master | <repo_name>penguin-of-linux/PenguinsLib<file_sep>/Geometry/Objects/Ray.cs
namespace Geometry
{public struct Ray
{
public readonly Vector2 Begin;
public readonly Vector2 Vector;
public Ray(Vector2 begin, Vector2 vector)
{
Begin = begin;
Vector = vector;
}
public bool Equals(Ray other)
{
return Begin.Equals(other.Begin) && Vector.Equals(other.Vector);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Ray && Equals((Ray)obj);
}
public override int GetHashCode()
{
unchecked
{
return (Begin.GetHashCode() * 397) ^ Vector.GetHashCode();
}
}
}
}<file_sep>/Tests/GeometryTests.cs
using System;
using System.Collections.Generic;
using System.Security.Cryptography.X509Certificates;
using NUnit.Framework;
using Geometry;
using NUnit.Framework.Internal;
namespace Tests
{
public class GeometryTests
{
// Замечание: в большинстве тестов на пересечение проверяется только тип возвращаемого объекта,
//т.к. все пересечения основаны на пересечении прямых. Пересечение прямых и отрезков проверяется нормально.
[TestCase(0, 0, -1, 1, 2, 1, 0, 1, TestName = "Simple perpendicular")]
[TestCase(0, 0, 1, 1, 2, 1, 1, 1, TestName = "Left seg point")]
[TestCase(0, 0, -2, 1, 0, 1, 0, 1, TestName = "Right seg point")]
[TestCase(0, 0, -1, 0, 1, 0, 0, 0, TestName = "On segment")]
[TestCase(0, 0, 1, 0, 2, 0, 1, 0, TestName = "On seg line")]
public void GetNearestPointOfSegment_TestCase(double xp, double yp, double xs1, double ys1,
double xs2, double ys2, double expx, double expy)
{
var point = new Vector2(xp, yp);
var seg = new Segment(xs1, ys1, xs2, ys2);
var expPoint = new Vector2(expx, expy);
var intPoint = GeometryMethods.GetNearestPointOfSegment(point, seg);
Assert.True(intPoint.Equals(expPoint));
}
[TestCase(0, 0, 2, 2, 1, 1, 3, 3, ExpectedResult = true, TestName = "Simple 1")]
[TestCase(2, 2, 0, 0, 3, 3, 1, 1, ExpectedResult = true, TestName = "Somple 2")]
[TestCase(0, 0, 2, 2, 2, 0, 3, 2, ExpectedResult = true, TestName = "Common side")]
[TestCase(0, 0, 2, 2, 2, 2, 3, 3, ExpectedResult = true, TestName = "Common vertex")]
[TestCase(0, 0, 3, 3, 1, 1, 2, 2, ExpectedResult = true, TestName = "Inserted")]
[TestCase(0, 0, 0, 10, -1, 3, 1, 7, ExpectedResult = true, TestName = "One rect is segment! Proizvol! Hotya it works...")]
[TestCase(0, 0, 2, 2, 2, 0, 2, 2, ExpectedResult = true, TestName = "Another rect is segment")]
[TestCase(0, 0, 1, 1, 2, 2, 3, 3, ExpectedResult = false, TestName = "Simple false 1")]
[TestCase(1, 1, 0, 0, 3, 3, 2, 2, ExpectedResult = false, TestName = "Simple false 2")]
public bool IsSimplifiedRectanglesInterescting_TestCase(double x1, double y1, double x2, double y2,
double x3, double y3, double x4, double y4)
{
var rect1 = new SimplifiedRectangle(x1, y1, x2, y2);
var rect2 = new SimplifiedRectangle(x3, y3, x4, y4);
return GeometryMethods.IsSimplifiedRectanglesInterescting(rect1, rect2);
}
[TestCase(0, 0, 0, 2, -1, 1, 1, 1, ExpectedResult = IntersectionResult.Point, TestName = "Simple '+'")]
[TestCase(0, 0, 2, 0, 1, 0, 3, 0, ExpectedResult = IntersectionResult.Segment, TestName = "One common line")]
[TestCase(0, 0, 2, 0, 2, 0, 2, 2, ExpectedResult = IntersectionResult.Point, TestName = "One common vertex, on line")]
[TestCase(0, 0, 0, 2, 0, 2, 3, 3, ExpectedResult = IntersectionResult.Point, TestName = "One common vertex, off line")]
[TestCase(0, 0, 2, 0, 2, 2, 4, 2, ExpectedResult = IntersectionResult.None, TestName = "Parallel OX")]
[TestCase(0, 0, 0, 2, 1, 0, 1, 2, ExpectedResult = IntersectionResult.None, TestName = "Parallel OY")]
[TestCase(0, 2, 2, 0, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Point, TestName = "No simple '+'")]
[TestCase(0, 1, 1, 2, 0, 0, 42, -42, ExpectedResult = IntersectionResult.None, TestName = "Just NONE")]
public IntersectionResult GetSegmentsIntersection_TestCase(double x1, double y1, double x2, double y2,
double x3, double y3, double x4, double y4)
{
var seg1 = new Segment(x1, y1, x2, y2);
var seg2 = new Segment(x3, y3, x4, y4);
return GeometryMethods.GetSegmentsIntersection(seg1, seg2, out var result);
}
[TestCase(0, 0, 1, 0, 0, 1, 0, 0, ExpectedResult = IntersectionResult.Point, TestName = "+")]
[TestCase(0, 0, 1, 1, 0, 1, 1, 0, ExpectedResult = IntersectionResult.Point, TestName = "x")]
[TestCase(0, 0, 1, 0, 0, 1, 1, 1, ExpectedResult = IntersectionResult.None, TestName = "===")]
[TestCase(0, 0, 1, 0, -1, 0, 3, 0, ExpectedResult = IntersectionResult.Line, TestName = "----")]
[TestCase(0, 0, 0, 1, 1, 0, 1, 1, ExpectedResult = IntersectionResult.None, TestName = "||")]
[TestCase(0, 0, 0, 1, 0, 4, 0, 10, ExpectedResult = IntersectionResult.Line, TestName = "|")]
[TestCase(0, 0, 1, 1, 1, 0, 2, 1, ExpectedResult = IntersectionResult.None, TestName = "//")]
public IntersectionResult GetLinesIntersection_Type_TestCase(double x1, double y1, double x2, double y2,
double x3, double y3, double x4, double y4)
{
var line1 = new Line(x1, y1, x2, y2);
var line2 = new Line(x3, y3, x4, y4);
return GeometryMethods.GetLinesIntersection(line1, line2, out var result);
}
[TestCase(0, 0, 1, 0, 0, 1, 0, 0, 0, 0, TestName = "+")]
[TestCase(0, 0, 1, 1, -5, 3, -4, 2, -1, -1, TestName = @"\/")]
public void GetLinesIntersection_Value_TestCase(double x1, double y1, double x2, double y2,
double x3, double y3, double x4, double y4, double expx, double expy)
{
var line1 = new Line(x1, y1, x2, y2);
var line2 = new Line(x3, y3, x4, y4);
GeometryMethods.GetLinesIntersection(line1, line2, out var result);
Assert.AreEqual(new Vector2(expx, expy), (Vector2)result);
}
[TestCase(1, 0, 1, 0, ExpectedResult = true, TestName = "(1, 0) (1, 0)")]
[TestCase(1, 0, 2, 0, ExpectedResult = true, TestName = "(1, 0) (2, 0)")]
[TestCase(1, 0, 0, 1, ExpectedResult = false, TestName = "(1, 0) (0, 1)")]
public bool IsVectorCollinear_TestCase(double x1, double y1, double x2, double y2)
{
var v1 = new Vector2(x1, y1);
var v2 = new Vector2(x2, y2);
return GeometryMethods.IsVectorsCollinear(v1, v2);
}
[TestCase(false, 0, 2, 2, 2, 0, 0, 1, 1, ExpectedResult = IntersectionResult.None, TestName = "F, Not intersecting")]
[TestCase(true, 0, 2, 2, 2, 0, 0, 1, 1, ExpectedResult = IntersectionResult.None, TestName = "T, Not intersecting")]
[TestCase(false, -1, 0, 1, 2, 0, 0, 1, 1, ExpectedResult = IntersectionResult.Point, TestName = "F, Rect vertex")]
[TestCase(true, -1, 0, 1, 2, 0, 0, 1, 1, ExpectedResult = IntersectionResult.Point, TestName = "T, Rect vertex")]
[TestCase(false, 1, 3, 1, 1, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Point, TestName = "F, One side inter")]
[TestCase(true, 1, 3, 1, 1, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Segment, TestName = "T, One side inter")]
[TestCase(false, 1, 2, 1, 1, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Point, TestName = "F, Seg begin on rect side")]
[TestCase(true, 1, 3, 1, 1, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Segment, TestName = "T, Seg begin on rect side")]
[TestCase(false, 1, 1, 2, 1, 0, 0, 3, 3, ExpectedResult = IntersectionResult.None, TestName = "F, Seg full inside rect")]
[TestCase(true, 1, 1, 2, 1, 0, 0, 3, 3, ExpectedResult = IntersectionResult.Segment, TestName = "T, Seg full inside rect")]
[TestCase(false, 0, 0, 2, 2, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Points, TestName = "F, Seg vertexes on rect")]
[TestCase(true, 0, 0, 2, 2, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Segment, TestName = "T, Seg vertexes on rect")]
[TestCase(false, 0, 0, 2, 0, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Segment, TestName = "F, Seg on rect side")]
[TestCase(true, 0, 0, 2, 0, 0, 0, 2, 2, ExpectedResult = IntersectionResult.Segment, TestName = "T, Seg on rect side")]
[TestCase(true, 0, 0, 75, 75, 25, 25, 75, 75, ExpectedResult = IntersectionResult.Segment, TestName = "T, LALALA")]
public IntersectionResult GetSegmentSimplifiedRectangleIntersection_TestCase(bool filled, params double[] nums)
{
var seg = new Segment(nums[0], nums[1], nums[2], nums[3]);
var rect = new SimplifiedRectangle(nums[4], nums[5], nums[6], nums[7]);
return GeometryMethods.GetSegmentSimplifiedRectangleIntersection(seg, rect, out var result, filled);
}
[TestCase(Math.PI, Math.PI, TestName = "P -> P")]
[TestCase(3 * Math.PI, Math.PI, TestName = "3P -> P")]
[TestCase(-3 * Math.PI, Math.PI, TestName = "-3P -> P")]
[TestCase(3 * Math.PI + Math.PI / 2, 3 * Math.PI / 2, TestName = "3.5P -> 1.5P")]
[TestCase(-3 * Math.PI - Math.PI / 2, Math.PI / 2, TestName = "-3.5P -> P/2")]
[TestCase(1, 1, TestName = "1 -> 1")]
public void GetNormalizedAngle_TestCase(double angle, double expected)
{
var result = GeometryMethods.GetNormalizedAngle(angle);
Assert.AreEqual(expected, result, 0.01);
}
[TestCase(0, Math.PI, Math.PI, TestName = "0, P")]
[TestCase(0, Math.PI * 3/2d, -Math.PI / 2, TestName = "0, 3/2P")]
[TestCase(Math.PI, Math.PI * 3/2d, Math.PI / 2, TestName = "P, 3/2P")]
[TestCase(Math.PI * 3/2d, Math.PI, -Math.PI / 2, TestName = "3/2P, P")]
[TestCase(1, 1, 0, TestName = "1, 1")]
[TestCase(Math.PI / 4, -Math.PI / 4, -Math.PI / 2, TestName = "P/4, -P/4")]
public void GetAnglesDifference_TestCase(double a1, double a2, double expected)
{
var result = GeometryMethods.GetAnglesDifference(a1, a2);
Assert.AreEqual(expected, result, 0.01);
}
[TestCase(1, 0, 1, 1, Math.PI / 4, TestName = "(1, 0), (1, 1), P/4")]
[TestCase(1, 1, 1, 0, 2 * Math.PI - Math.PI / 4, TestName = "(1, 1), (1, 0), 7P/4")]
public void GetAngleBetweenVectorCww_TestCase(double x1, double y1, double x2, double y2, double exp)
{
var v1 = new Vector2(x1, y1);
var v2 = new Vector2(x2, y2);
var result = GeometryMethods.GetAngleBetweenVectorCww(v1, v2);
Assert.AreEqual(exp, result, 0.01);
}
[TestCase(0, 0, 1, 1, 0, 0, 3, ExpectedResult = IntersectionResult.Point, TestName = "Circle center is ray begin")]
public IntersectionResult GetRayCircleIntersection(double x1, double y1, double x2, double y2, double xc, double yc, double r)
{
var ray = new Ray(new Vector2(x1, y1), new Vector2(x2, y2));
var circle = new Circle(xc, yc, r);
return GeometryMethods.GetRayCircleIntersection(ray, circle, out var _);
}
[Test]
public void GetLineCircleIntersection_NoPoints()
{
var line = new Line(0, 2, 1, 2);
var circle = new Circle(0, 0, 1);
var inter = GeometryMethods.GetLineCircleIntersection(line, circle, out var result);
Assert.AreEqual(IntersectionResult.None, inter);
}
[Test]
public void GetLineCircleIntersection_OnePoint()
{
var line = new Line(0, 1, 1, 1);
var circle = new Circle(0, 0, 1);
var inter = GeometryMethods.GetLineCircleIntersection(line, circle, out var result);
Assert.AreEqual(new Vector2(0, 1), (Vector2) result);
}
}
}
<file_sep>/Geometry/Objects/IntVector2.cs
using System;
namespace Geometry
{
public struct IntVector2
{
public double Length => Math.Sqrt(X * X + Y * Y);
public readonly int X;
public readonly int Y;
public IntVector2(int x, int y)
{
X = x;
Y = y;
}
public static IntVector2 operator +(IntVector2 v1, IntVector2 v2)
{
return new IntVector2(v1.X + v2.X, v1.Y + v2.Y);
}
public static IntVector2 operator -(IntVector2 v1, IntVector2 v2)
{
return v1 + (-v2);
}
public static IntVector2 operator -(IntVector2 v)
{
return new IntVector2(-v.X, -v.Y);
}
public static IntVector2 operator *(IntVector2 v, int k)
{
return new IntVector2(v.X * k, v.Y * k);
}
public static IntVector2 operator *(int k, IntVector2 v)
{
return v * k;
}
public static implicit operator IntVector2(Vector2 vec)
{
return new IntVector2((int)vec.X, (int)vec.Y);
}
public IntVector2 GetNormalized()
{
if (Length.Equal(0))
return new IntVector2(0, 0);
var x = (int)(X / Length);
var y = (int)(Y / Length);
return new IntVector2(x, y);
}
public override string ToString()
{
return $"{X} {Y}";
}
public override bool Equals(object other)
{
if (other is IntVector2 vector2)
return Equals(vector2);
if (other is Vector2 vec)
return Equals(vec);
return false;
}
private bool Equals(IntVector2 other)
{
return X == other.X && Y == other.Y;
}
private bool Equals(Vector2 other)
{
IntVector2 vec = other;
return Equals(vec);
}
public override int GetHashCode()
{
unchecked
{
return X.GetHashCode() * 397 + Y.GetHashCode() * 7;
}
}
}
}<file_sep>/Geometry/Objects/Vector2.cs
using System;
namespace Geometry
{
public struct Vector2
{
public double Length => Math.Sqrt(X * X + Y * Y);
public readonly double X;
public readonly double Y;
public Vector2(double x, double y)
{
X = x;
Y = y;
}
public static Vector2 operator +(Vector2 v1, Vector2 v2)
{
return new Vector2(v1.X + v2.X, v1.Y + v2.Y);
}
public static Vector2 operator -(Vector2 v1, Vector2 v2)
{
return v1 + (-v2);
}
public static Vector2 operator -(Vector2 v)
{
return new Vector2(-v.X, -v.Y);
}
public static Vector2 operator *(Vector2 v, double k)
{
return new Vector2(v.X * k, v.Y * k);
}
public static Vector2 operator *(double k, Vector2 v)
{
return v * k;
}
public static implicit operator Vector2(IntVector2 vec)
{
return new Vector2(vec.X, vec.Y);
}
public Vector2 GetNormalized()
{
if (Length.Equal(0))
return new Vector2(0, 0);
var x = X / Length;
var y = Y / Length;
return new Vector2(x, y);
}
public override string ToString()
{
return $"{X} {Y}";
}
public override bool Equals(object other)
{
if (other is Vector2 vector2)
return Equals(vector2);
if (other is IntVector2 intVector2)
return Equals(intVector2);
return false;
}
private bool Equals(Vector2 other)
{
return X.Equal(other.X) && Y.Equal(other.Y);
}
private bool Equals(IntVector2 other)
{
Vector2 vec = other;
return Equals(vec);
}
public override int GetHashCode()
{
unchecked
{
return X.GetHashCode() * 397 + Y.GetHashCode() * 7;
}
}
}
}<file_sep>/Geometry/tie.py
import glob
import re
def short_using_string(str):
index = str.find('using')
if not index == -1:
return str[index:]
else:
return ""
if __name__ == "__main__":
body = ""
usings = set()
files = glob.glob('**/*.cs', recursive=True)
for filename in files:
if not filename.startswith('obj') and not filename.startswith('bin') and not filename.startswith('Properties'):
with open(filename, 'r') as file:
text = file.read()
start = text.index('{')
finish = text.rindex('}')
namespace_index = text.find('namespace')
for using in text[:namespace_index].splitlines():
usings.add(short_using_string(using))
body += text[start+1:finish]
with open('tie_result.txt', 'w') as file:
for using in usings:
if not using == "":
file.write(using + '\n')
file.write('\n\nnamespace FantasticBits {\n')
file.write(body)
file.write('\n}')<file_sep>/Geometry/DoubleExtensions.cs
namespace Geometry
{
public static class DoubleExtensions
{
public static bool Less(this double a, double b, double eps = 0.001)
{
return b - a > eps;
}
public static bool Greater(this double a, double b, double eps = 0.001)
{
return b.Less(a, eps);
}
public static bool Equal(this double a, double b, double eps = 0.001)
{
return !a.Less(b, eps) && !a.Greater(b, eps);
}
public static bool LessOrEqual(this double a, double b, double eps = 0.001)
{
return a.Less(b, eps) || a.Equal(b, eps);
}
public static bool GreaterOrEqual(this double a, double b, double eps = 0.001)
{
return a.Greater(b, eps) || a.Equal(b, eps);
}
}
}<file_sep>/Geometry/Objects/Segment.cs
namespace Geometry
{
public struct Segment
{
public readonly Vector2 Begin;
public readonly Vector2 End;
public Vector2[] Points => new[] { Begin, End };
public Segment(Vector2 begin, Vector2 end)
{
Begin = begin;
End = end;
}
public Segment(double x1, double y1, double x2, double y2)
: this(new Vector2(x1, y1), new Vector2(x2, y2))
{
}
public override string ToString()
{
return $"{Begin}, {End}";
}
public override int GetHashCode()
{
unchecked
{
return (Begin.GetHashCode() * 397) ^ End.GetHashCode();
}
}
public bool Equals(Segment other)
{
return Begin.Equals(other.Begin) && End.Equals(other.End);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Segment && Equals((Segment) obj);
}
}
}<file_sep>/Geometry/Objects/SimplifiedRectangle.cs
using System;
using System.Collections.Generic;
namespace Geometry
{
public struct SimplifiedRectangle
{
public readonly Vector2 V1;
public readonly Vector2 V2;
public readonly double Height;
public readonly double Width;
/// <summary>
/// Rectangle with parallel to axis OY OX sides
/// </summary>
public SimplifiedRectangle(Vector2 v1, Vector2 v2) : this(v1.X, v1.Y, v2.X, v2.Y)
{
}
/// <summary>
/// Rectangle with parallel to axis OY OX sides
/// </summary>
public SimplifiedRectangle(double x1, double y1, double x2, double y2)
{
V1 = new Vector2(x1, y1);
V2 = new Vector2(x2, y2);
Width = Math.Abs(x1 - x2);
Height = Math.Abs(y1 - y2);
}
/*public bool HasPoint(Vector2 point, bool withInsides = false)
{
if (withInsides) throw new NotImplementedException("I am so lazy");
if (point.Equals(V1)) return true;
if (point.Equals(V2)) return true;
if (point.Equals(new Vector2(V1.X, V2.Y))) return true;
if (point.Equals(new Vector2(V2.X, V1.Y))) return true;
return false;
}*/
public IEnumerable<Vector2> Vertexes => new[]
{
V1, V2, new Vector2(V1.X, V2.Y), new Vector2(V2.X, V1.Y)
};
/*public bool HasPoint(double x, double y, bool withInsides = false)
{
return HasPoint(new Vector2(x, y), withInsides);
}*/
public Segment[] Segments => new[]
{
new Segment(V1.X, V1.Y, V2.X, V1.Y),
new Segment(V1.X, V1.Y, V1.X, V2.Y),
new Segment(V2.X, V1.Y, V2.X, V2.Y),
new Segment(V1.X, V2.Y, V2.X, V2.Y)
};
public bool Equals(SimplifiedRectangle other)
{
return V1.Equals(other.V1) && V2.Equals(other.V2);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is SimplifiedRectangle && Equals((SimplifiedRectangle)obj);
}
public override int GetHashCode()
{
unchecked
{
return (V1.GetHashCode() * 397) ^ V2.GetHashCode();
}
}
}
}<file_sep>/Geometry/Objects/Circle.cs
namespace Geometry
{
public struct Circle
{
public readonly Vector2 Center;
public readonly double R;
public Circle(Vector2 center, double r)
{
Center = center;
R = r;
}
public Circle(double x, double y, double r) : this(new Vector2(x, y), r)
{
}
public bool Equals(Circle other)
{
return Center.Equals(other.Center) && R.Equal(other.R);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Circle && Equals((Circle) obj);
}
public override int GetHashCode()
{
unchecked
{
return (Center.GetHashCode() * 397) ^ R.GetHashCode();
}
}
}
}<file_sep>/Geometry/Objects/Line.cs
using System;
namespace Geometry
{
public struct Line
{
public readonly double A;
public readonly double B;
public readonly double C;
public Line(double a, double b, double c)
{
if (a.Equal(0) && b.Equal(0))
throw new ArgumentException("A and B are equal 0");
A = a;
B = b;
C = c;
}
public Line(double x1, double y1, double x2, double y2)
{
if (x1.Equal(x2) && y1.Equal(y2))
throw new ArgumentException("Equivalent points");
A = y1 - y2;
B = x2 - x1;
C = x1 * y2 - x2 * y1;
}
public Line(Vector2 v1, Vector2 v2) : this(v1.X, v1.Y, v2.X, v2.Y)
{
}
public Line(Vector2 vector, double x, double y)
{
if (vector.X.Equal(0) && vector.Y.Equal(0))
throw new ArgumentException($"Vector cannot be zero");
A = vector.Y;
B = -vector.X;
C = vector.X * y - vector.Y * x;
}
public Line(Ray ray) : this(ray.Vector, ray.Begin.X, ray.Begin.Y)
{
}
public Line(Segment seg) : this(seg.Begin, seg.End)
{
}
public bool Equals(Line other)
{
return A.Equal(other.A) && B.Equal(other.B) && C.Equal(other.C);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj)) return false;
return obj is Line && Equals((Line)obj);
}
public override int GetHashCode()
{
unchecked
{
var hashCode = A.GetHashCode();
hashCode = (hashCode * 397) ^ B.GetHashCode();
hashCode = (hashCode * 397) ^ C.GetHashCode();
return hashCode;
}
}
}
}<file_sep>/Geometry/IntersectionResult.cs
namespace Geometry
{
/// <summary>
/// Тип пересечения фигур. Point - Vector2, Points - Vector2[], None - null, остальные соответствуют классам
/// </summary>
public enum IntersectionResult
{
Point,
Points,
Line,
Segment,
Ray,
None
}
}<file_sep>/Geometry/GeometryMethods.cs
using System;
using System.Collections.Generic;
using System.Linq;
namespace Geometry
{
public static class GeometryMethods
{
/// <summary>
/// Returns angle between vectors counterclock-wise
/// </summary>
public static double GetAngleBetweenVectorCww(Vector2 v1, Vector2 v2)
{
var p = v1.X * v2.X + v1.Y * v2.Y;
var cos = p / (v1.Length * v2.Length);
var angle = Math.Acos(cos);
if (cos.Equal(1))
return 0;
if (cos.Equal(-1))
return Math.PI;
// векторное произведение векторов на плоскости в базисе [(1, 0), (0, 1)]
var c = new Vector3(0, 0, 1) * (v1.X * v2.Y - v2.X * v1.Y);
if (c.Z > 0)
return angle;
return 2 * Math.PI - angle;
}
/// <summary>
/// Angle difference, conterclock-wise. Those how much to add to a1 to get a2.
/// </summary>
/// <returns></returns>
public static double GetAnglesDifference(double a1, double a2)
{
a1 = GetNormalizedAngle(a1);
a2 = GetNormalizedAngle(a2);
if (a1 > a2)
{
var cw = a1 - a2; // clockwise
var ccw = 2 * Math.PI - cw; // counter cw
return cw < ccw ? -cw : ccw;
}
else
{
var ccw = a2 - a1;
var cw = 2 * Math.PI - ccw;
return cw < ccw ? -cw : ccw;
}
}
/// <summary>
/// Distance on plane.
/// </summary>
public static double GetDistance(Vector2 v1, Vector2 v2)
{
return Math.Sqrt((v1.X - v2.X) * (v1.X - v2.X) + (v1.Y - v2.Y) * (v1.Y - v2.Y));
}
/// <summary>
/// Distance from point to segment.
/// </summary>
public static double GetDistanceToSegment(Vector2 point, Segment segment)
{
var npoint = GetNearestPointOfSegment(point, segment);
return GetDistance(point, npoint);
}
/// <summary>
/// Line and circle intersection. Returns Point, Points, None
/// </summary>
public static IntersectionResult GetLineCircleIntersection(Line line, Circle circle, out object result)
{
var pline = new Line(new Vector2(line.A, line.B), circle.Center.X, circle.Center.Y);
GetLinesIntersection(line, pline, out var intres);
var ipoint = (Vector2) intres; // перпендикулярные прямые, всегда точка
var dist = GetDistance(circle.Center, ipoint);
if (dist.Greater(circle.R))
{
result = null;
return IntersectionResult.None;
}
if (dist.Equal(circle.R, 0.01)) // боюсь за точность тут
{
result = ipoint;
return IntersectionResult.Point;
}
var d = Math.Sqrt(circle.R * circle.R + dist * dist);
var a = Math.Sqrt(d * d / (line.A * line.A + line.B * line.B));
var v = new Vector2(a, a);
result = new[] { ipoint + v, ipoint - v };
return IntersectionResult.Points;
}
/// <summary>
/// Lines intersection. Returns Line, Point, None.
/// </summary>
public static IntersectionResult GetLinesIntersection(Line line1, Line line2, out object result)
{
/*// если прямые вертикальны
if (line1.B.Equal(0) && line2.B.Equal(0))
{
// A и B не могут быть одновременно нулями, см. конструкторы Line
if ((-line1.C / line1.A).Equal(-line2.C / line2.A))
{
// если x1 == x2, то прямые совпадают
result = line1;
return IntersectionResult.Line;
}
result = null;
return IntersectionResult.None;
}
if (line1.A.Equal(0) && line2.A.Equal(0))*/
var v1 = new Vector2(-line1.B, line1.A);
var v2 = new Vector2(-line2.B, line2.A);
if (IsVectorsCollinear(v1, v2))
{
if (v1.X.Equal(0)) // если прямые вертикальны
{
// A и B не могут быть одновременно нулями, см. конструкторы Line
if ((-line1.C / line1.A).Equal(-line2.C / line2.A))
{
// если x1 == x2, то прямые совпадают
result = line1;
return IntersectionResult.Line;
}
result = null;
return IntersectionResult.None;
}
else
{
if (line1.C.Equal(line2.C))
{
result = line1;
return IntersectionResult.Line;
}
else
{
result = null;
return IntersectionResult.None;
}
}
}
// вектора не коллинеарны
try
{
var x = (line1.C * line2.B - line2.C * line1.B) / (line2.A * line1.B - line1.A * line2.B);
var nonYLine = line1.B != 0 ? line1 : line2; // ищем прямую с B != 0
var y = -(nonYLine.C + nonYLine.A * x) / nonYLine.B;
if (double.IsNaN(x) || double.IsNaN(y))
{
// прямые совпадают
result = line1;
return IntersectionResult.Line;
}
result = new Vector2(x, y);
return IntersectionResult.Point;
}
catch (DivideByZeroException)
{
result = null;
return IntersectionResult.None;
}
}
/// <summary>
/// Returns value of function that define by line. If line is vertical then returns null;
/// </summary>
public static double? GetLineFunctionValue(Line line, double arg)
{
if (line.B.Equal(0))
return null;
return (-line.C - line.A * arg) / line.B;
}
/// <summary>
/// Line and segment intersection. Returns Segment, Point, None.
/// </summary>
public static IntersectionResult GetLineSegmentIntersection(Line line, Segment segment, out object result)
{
var segmentLine = new Line(segment.Begin.X, segment.Begin.Y, segment.End.X, segment.End.Y);
var intersection = GetLinesIntersection(line, segmentLine, out var intres);
if (intersection == IntersectionResult.Line)
{
result = segment;
return IntersectionResult.Segment;
}
var iPoint = (Vector2) intres; // intersection point
if (HasSegmentPoint(segment, iPoint))
{
result = iPoint;
return IntersectionResult.Point;
}
else
{
result = null;
return IntersectionResult.None;
}
}
/// <summary>
/// Nearest point of segment to given point.
/// </summary>
public static Vector2 GetNearestPointOfSegment(Vector2 point, Segment segment)
{
var segmentLine = new Line(segment.Begin.X, segment.Begin.Y, segment.End.X, segment.End.Y);
var pVector = new Vector2(segmentLine.A, segmentLine.B); // perpendicular vector
var pLine = new Line(pVector, point.X, point.Y); // perpendicular point
var intersection = GetLineSegmentIntersection(pLine, segment, out var intres); // только Point
if (intersection == IntersectionResult.Point)
return (Vector2) intres;
var distToBegin = GetDistance(point, segment.Begin);
var distToEnd = GetDistance(point, segment.End);
return distToBegin < distToEnd ? segment.Begin : segment.End;
}
/// <summary>
/// Returns angle int range [0, 2P) that equals given
/// </summary>
public static double GetNormalizedAngle(double a)
{
return a - Math.Floor(a / (2 * Math.PI)) * 2 * Math.PI;
}
/// <summary>
/// Ray and circle intersection. Returns Point, Point, None
/// </summary>
public static IntersectionResult GetRayCircleIntersection(Ray ray, Circle circle, out object result)
{
var line = new Line(ray);
var intersection = GetLineCircleIntersection(line, circle, out var intres);
if (intersection == IntersectionResult.None)
{
result = intres;
return intersection;
}
if (intersection == IntersectionResult.Point)
{
var p = (Vector2) intres;
if (HasRayPoint(ray, p))
{
result = intres;
return IntersectionResult.Points;
}
else
{
result = null;
return IntersectionResult.None;
}
}
// intersection = Points
var points = (Vector2[]) intres;
var firstInRay = HasRayPoint(ray, points[0]);
var secondInRay = HasRayPoint(ray, points[1]);
if (firstInRay && secondInRay)
{
result = intres;
return IntersectionResult.Points;
}
else if (firstInRay)
{
result = points[0];
return IntersectionResult.Point;
}
else if (secondInRay)
{
result = points[1];
return IntersectionResult.Point;
}
else
{
result = null;
return IntersectionResult.None;
}
}
/// <summary>
/// Ray and line intersection. Return Ray, Point, None
/// </summary>
public static IntersectionResult GetRayLineIntersection(Ray ray, Line line, out object result)
{
var rayLine = new Line(ray.Vector, ray.Begin.X, ray.Begin.Y);
var intersection = GetLinesIntersection(line, rayLine, out var intres);
switch (intersection)
{
case IntersectionResult.Line:
result = ray;
return IntersectionResult.Ray;
case IntersectionResult.None:
result = null;
return IntersectionResult.None;
case IntersectionResult.Point:
if (HasRayPoint(ray, (Vector2)intres))
{
result = intres;
return IntersectionResult.Point;
}
else
{
result = null;
return IntersectionResult.None;
}
}
throw new Exception($"Internal error. GetLinesIntersection returned {intersection}");
}
/// <summary>
/// Ray and segment intersection. Returns Segment, Point None.
/// </summary>
public static IntersectionResult GetRaySegmentIntersection(Ray ray, Segment segment, out object result)
{
var sline = new Line(segment.Begin.X, segment.Begin.Y, segment.End.X, segment.End.Y);
var intersection = GetRayLineIntersection(ray, sline, out var intres);
switch (intersection)
{
case IntersectionResult.Ray:
result = ray;
return IntersectionResult.Ray;
case IntersectionResult.None:
result = null;
return IntersectionResult.None;
case IntersectionResult.Point:
if (HasRayPoint(ray, (Vector2)intres))
{
result = intres;
return IntersectionResult.Point;
}
else
{
result = null;
return IntersectionResult.None;
}
}
throw new Exception($"Internal error. GetRaySegmentIntersection returned {intersection}");
}
/// <summary>
/// Segments intersection. Returns Segment, Point, None
/// </summary>
public static IntersectionResult GetSegmentsIntersection(Segment seg1, Segment seg2, out object result)
{
var intersection = GetLinesIntersection(new Line(seg1), new Line(seg2), out var intres);
if (intersection == IntersectionResult.None)
{
result = null;
return IntersectionResult.None;
}
if (intersection == IntersectionResult.Point)
{
var iPoint = (Vector2) intres;
if (HasSegmentPoint(seg1, iPoint) && HasSegmentPoint(seg2, iPoint))
{
/*if (!includeBorders)
if (seg1.Begin.Equals(iPoint) || seg2.Begin.Equals(iPoint)
|| seg1.End.Equals(iPoint) || seg2.End.Equals(iPoint))
return null;*/
result = intres;
return IntersectionResult.Point;
}
result = null;
return IntersectionResult.None;
}
// отрезки лежат на одной прямой
return GetSegmentsOnLineIntersection(seg1, seg2, out result);
}
public static IntersectionResult GetSegmentSimplifiedRectangleIntersection(Segment seg,
SimplifiedRectangle rect, out object result, bool filledRectangle = false)
{
var points = new List<Vector2>();
foreach (var s in rect.Segments)
{
var intersection = GetSegmentsIntersection(seg, s, out var intres);
switch (intersection)
{
case IntersectionResult.Segment:
result = intres;
return IntersectionResult.Segment;
case IntersectionResult.Point:
points.Add((Vector2)intres);
break;
case IntersectionResult.None:
continue;
}
}
points = points.Distinct().ToList(); // ох ужас
// если точек пересечения нет, то вернем None
// если точка пересечения одна, то она либо вершина прямоугольника и тогда мы вернем ее,
// либо точка пересечения является вершиной отрезка, и тогда мы вернем ее, если not filledRectangle,
// иначе вернем отрезок,
// если точек пересечения две, то вернем либо отрезок, либо 2 точки в зависимости от filledRectangle
var beginInRect = IsPointInsideSimplifiedRectangle(seg.Begin, rect);
var endInRect = IsPointInsideSimplifiedRectangle(seg.End, rect);
if (points.Count == 0)
{
if (beginInRect && endInRect && filledRectangle)
{
result = seg;
return IntersectionResult.Segment;
}
else
{
result = null;
return IntersectionResult.None;
}
}
if (points.Count == 1)
{
var point = points[0];
if (filledRectangle)
{
if (!beginInRect && !endInRect)
{
result = point;
return IntersectionResult.Point;
}
if (beginInRect && endInRect)
{
result = seg;
return IntersectionResult.Segment;
}
var pointInRect = beginInRect ? seg.Begin : seg.End;
if (pointInRect.Equals(point))
{
result = point;
return IntersectionResult.Point;
}
else
{
result = new Segment(pointInRect, point);
return IntersectionResult.Segment;
}
}
else
{
result = points[0];
return IntersectionResult.Point;
}
}
// точки две
if (filledRectangle)
{
result = new Segment(points[0], points[1]);
return IntersectionResult.Segment;
}
else
{
result = new[] { points[0], points[1] };
return IntersectionResult.Points;
}
}
/// <summary>
/// Intersection of segments that lie on one line. Returns Segment, Point, None
/// </summary>
public static IntersectionResult GetSegmentsOnLineIntersection(Segment seg1, Segment seg2, out object result)
{
var axisChanged = false;
if (seg1.Begin.X.Equal(seg1.End.X)) // если отрезки вертикальны
{
seg1 = new Segment(seg1.Begin.Y, seg1.Begin.X, seg1.End.Y, seg1.End.X);
seg2 = new Segment(seg2.Begin.Y, seg2.Begin.X, seg2.End.Y, seg2.End.X);
axisChanged = true;
}
var minx2 = Math.Min(seg2.Begin.X, seg2.End.X);
var maxx2 = Math.Max(seg2.Begin.X, seg2.End.X);
var minx1 = Math.Min(seg1.Begin.X, seg1.End.X);
var maxx1 = Math.Max(seg1.Begin.X, seg1.End.X);
if (minx1.Greater(maxx2) || minx2.Greater(maxx1)) // не пересекаются
{
result = null;
return IntersectionResult.None;
}
var x1 = Math.Max(minx1, minx2);
var x2 = Math.Min(maxx1, maxx2);
var line = new Line(seg1);
// решарпер не знает, что line не вертикальная, т.к. мы отразили отрезки в начале функции. Глупый решарпер.
var y1 = GetLineFunctionValue(line, x1).Value;
var y2 = GetLineFunctionValue(line, x2).Value;
var seg = axisChanged ? new Segment(y1, x1, y2, x2) : new Segment(x1, y1, x2, y2);
if (x1.Equal(x2))
{
result = new Vector2(x1, y1);
return IntersectionResult.Point;
}
else
{
result = seg;
return IntersectionResult.Segment;
}
}
/// <summary>
/// Проверяет, лежит ли точка на луче. Точка point лежит на линии луча.
/// </summary>
public static bool HasRayPoint(Ray ray, Vector2 point)
{
if (point.Equals(ray.Begin))
return true;
if (!ray.Vector.X.Equal(0))
{
if (ray.Vector.X.Greater(0))
{
if (point.X.GreaterOrEqual(ray.Begin.X)) return true;
else return false;
}
else
{
if (point.X.LessOrEqual(ray.Begin.X)) return true;
else return false;
}
}
else
{
if (ray.Vector.Y.Greater(0))
{
if (point.Y.GreaterOrEqual(ray.Begin.Y)) return true;
else return false;
}
else
{
if (point.Y.LessOrEqual(ray.Begin.Y)) return true;
else return false;
}
}
}
/// <summary>
/// Проверяет, лежит ли точка в отрезке. Точка point - точка, лежащая на линии отрезка
/// </summary>
public static bool HasSegmentPoint(Segment segment, Vector2 point)
{
var rspoint = segment.Begin.X.Greater(segment.End.X) ? segment.Begin : segment.End; // right segment point
var lspoint = rspoint.Equals(segment.Begin) ? segment.End : segment.Begin; // left segment point
var tspoint = segment.Begin.Y.Greater(segment.End.Y) ? segment.Begin : segment.End; // top segment point
var bspoint = tspoint.Equals(segment.Begin) ? segment.End : segment.Begin; // bottom segment point
return point.X.GreaterOrEqual(lspoint.X) && point.X.LessOrEqual(rspoint.X) &&
point.Y.GreaterOrEqual(bspoint.Y) && point.Y.LessOrEqual(tspoint.Y);
}
public static bool IsPointInsideSimplifiedRectangle(Vector2 point, SimplifiedRectangle rect)
{
return IsSimplifiedRectanglesInterescting(rect, new SimplifiedRectangle(point, point)); // :P смекалочка
}
public static bool IsSimplifiedRectanglesInterescting(SimplifiedRectangle rect1, SimplifiedRectangle rect2)
{
var minx1 = Math.Min(rect1.V1.X, rect1.V2.X);
var maxx1 = Math.Max(rect1.V1.X, rect1.V2.X);
var miny1 = Math.Min(rect1.V1.Y, rect1.V2.Y);
var maxy1 = Math.Max(rect1.V1.Y, rect1.V2.Y);
var minx2 = Math.Min(rect2.V1.X, rect2.V2.X);
var maxx2 = Math.Max(rect2.V1.X, rect2.V2.X);
var miny2 = Math.Min(rect2.V1.Y, rect2.V2.Y);
var maxy2 = Math.Max(rect2.V1.Y, rect2.V2.Y);
return (minx1 >= minx2 && minx1 <= maxx2 || maxx1 >= minx2 && maxx1 <= maxx2 || minx2 >= minx1 && maxx2 <= maxx1) &&
(miny1 >= miny2 && miny1 <= maxy2 || maxy1 >= miny2 && maxy1 <= maxy2 || miny2 >= miny1 && maxy2 <= maxy1);
}
public static bool IsVectorsCollinear(Vector2 v1, Vector2 v2)
{
var len1 = v1.Length;
var len2 = v2.Length;
if (len1.Equal(0) || len2.Equal(0))
return true;
var p = v1.X * v2.X + v1.Y * v2.Y;
var cos = p / len1 / len2;
return Math.Abs(cos).Equal(1);
}
}
}<file_sep>/Geometry/Objects/Vector3.cs
using System;
namespace Geometry
{
public struct Vector3
{
public double Length => Math.Sqrt(X * X + Y * Y + Z * Z);
public readonly double X;
public readonly double Y;
public readonly double Z;
public Vector3(double x, double y, double z)
{
X = x;
Y = y;
Z = z;
}
public static Vector3 operator +(Vector3 v1, Vector3 v2)
{
return new Vector3(v1.X + v2.X, v1.Y + v2.Y, v1.Z + v2.Z);
}
public static Vector3 operator -(Vector3 v1, Vector3 v2)
{
return v1 + (-v2);
}
public static Vector3 operator -(Vector3 v)
{
return new Vector3(-v.X, -v.Y, -v.Z);
}
public static Vector3 operator *(Vector3 v, double k)
{
return new Vector3(v.X * k, v.Y * k, v.Z * k);
}
public static Vector3 operator *(double k, Vector3 v)
{
return v * k;
}
public Vector3 GetNormalized()
{
if (Length.Equal(0))
return new Vector3(0, 0, 0);
var x = X / Length;
var y = Y / Length;
var z = Z / Length;
return new Vector3(x, y, z);
}
public override string ToString()
{
return $"{X} {Y} {Z}";
}
public override bool Equals(object other)
{
if (other is Vector3 vector3)
return Equals(vector3);
return false;
}
private bool Equals(Vector3 other)
{
return X.Equal(other.X) && Y.Equal(other.Y) && Z.Equal(other.Z);
}
public override int GetHashCode()
{
unchecked
{
return X.GetHashCode() * 397 + Y.GetHashCode() * 7 + Z.GetHashCode() * 13;
}
}
}
}<file_sep>/Tests/Algorithms_FindPathAmongRectanglesTests.cs
using Algorithms;
using Geometry;
using NUnit.Framework;
namespace Tests
{
public class Algorithms_FindPathAmongRectanglesTests
{
[Test]
public void WithoutBarriers()
{
var rectangles = new SimplifiedRectangle[0];
var start = new Vector2(0, 0);
var finish = new Vector2(10, 10);
var path = AlgorithmsMethods.FindPathAmongRectangles(start, finish, rectangles);
Assert.AreEqual(1, path.Length);
Assert.AreEqual(finish, path[0]);
}
[Test]
public void OneBarrier()
{
var rectangles = new SimplifiedRectangle[] {new SimplifiedRectangle(25, 25, 75, 75), };
var start = new Vector2(0, 0);
var finish = new Vector2(100, 100);
var path = AlgorithmsMethods.FindPathAmongRectangles(start, finish, rectangles);
Assert.AreEqual(2, path.Length);
Assert.AreEqual(finish, path[1]);
}
[Test]
public void DifficultTest()
{
/*
11 x 11
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 * * * *
0 0 0 0 0 0 0 * * * *
* * * 0 0 0 0 0 0 0 0
* * * 0 0 0 * * * * *
* * * 0 0 0 * * * * *
0 0 * * * 0 * * * * *
0 0 * * * 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
*/
var rectangles = new SimplifiedRectangle[]
{
new SimplifiedRectangle(0, 4, 2, 6),
new SimplifiedRectangle(2, 2, 4, 3),
new SimplifiedRectangle(6, 3, 10, 5),
new SimplifiedRectangle(7, 7, 10, 8),
};
var start = new Vector2(0, 0);
var finish = new Vector2(10, 10);
var path = AlgorithmsMethods.FindPathAmongRectangles(start, finish, rectangles);
// результат непредсказуем, т.к. юзаем бфс :)
;
//Assert.AreEqual(4, path.Length);
}
[Test]
public void PathToRectMiddleFromItsVertext()
{
var rectangles = new SimplifiedRectangle[]
{
new SimplifiedRectangle(0, 0, 20, 20)
};
var start = new Vector2(0, 0);
var finish = new Vector2(10, 10);
var path = AlgorithmsMethods.FindPathAmongRectangles(start, finish, rectangles);
Assert.IsEmpty(path);
}
}
}<file_sep>/Algorithms/Algorithms.cs
using System.Collections.Generic;
using System.Linq;
using Geometry;
namespace Algorithms
{
public static class AlgorithmsMethods
{
/// <summary>
/// Юзаем бфс :)
/// </summary>
public static Vector2[] FindPathAmongRectangles(Vector2 start, Vector2 finish, params SimplifiedRectangle[] rectangles)
{
//var begInRect = GeometryMethods.IsPointInsideSimplifiedRectangle(start, rect);
//var endInRect = GeometryMethods.IsPointInsideSimplifiedRectangle(finish, rect);
//if (begInRect && !endInRect || !begInRect && endInRect)
// return new Vector2[0];
if (rectangles.Length == 0)
return new Vector2[] { finish };
var searchRect = new SimplifiedRectangle(start, finish);
rectangles = rectangles
.Where(e => GeometryMethods.IsSimplifiedRectanglesInterescting(searchRect, e))
.ToArray();
var queue = new Queue<Vector2>();
queue.Enqueue(start);
var visited = new HashSet<Vector2> {start};
var parent = new Dictionary<Vector2, Vector2?>();
while (queue.Count > 0)
{
var current = queue.Dequeue();
var seg = new Segment(current, finish);
if (!rectangles.Any(r => IsSegmentIntersectingRectangle(seg, r)))
{
parent[finish] = current;
break;
}
foreach (var n in GetNeighbors(current, rectangles, visited))
{
parent[n] = current;
visited.Add(n);
queue.Enqueue(n);
// проверка на visited в GetNeighbors - для ускорения
}
}
var result = new LinkedList<Vector2>();
var a = finish;
while (parent.ContainsKey(a))
{
result.AddFirst(a);
a = parent[a].Value;
}
return result.ToArray();
}
private static IEnumerable<Vector2> GetNeighbors(Vector2 point, SimplifiedRectangle[] rectangles, HashSet<Vector2> visited)
{
// очень медленно :C
var result = new List<Vector2>();
foreach (var rect in rectangles)
{
var hasPoint = rect.Vertexes.Contains(point);
foreach (var v in rect.Vertexes)
{
if (visited.Contains(v)) // для скорости запихал сюда
continue;
if (hasPoint)
{
if (v.X.Equal(point.X) && !v.Y.Equal(point.Y) || !v.X.Equal(point.X) && v.Y.Equal(point.Y))
result.Add(v);
}
else
{
var seg = new Segment(point, v);
if (rectangles.Any(r => IsSegmentIntersectingRectangle(seg, r)))
continue;
result.Add(v);
}
}
}
return result;
}
private static bool IsSegmentIntersectingRectangle(Segment seg, SimplifiedRectangle rect)
{
var intersection =
GeometryMethods.GetSegmentSimplifiedRectangleIntersection(seg, rect, out var intres, true);
if (intersection == IntersectionResult.None)
{
return false;
}
if (intersection == IntersectionResult.Point)
{
if (intres.Equals(seg.Begin) || intres.Equals(seg.End))
return false;
}
if (intersection == IntersectionResult.Points)
{
var points = (Vector2[])intres;
if (seg.Begin.Equals(points[0]) && seg.End.Equals(points[1]) ||
seg.Begin.Equals(points[1]) && seg.End.Equals(points[0]))
return false;
}
return true;
}
}
}
| d8ab880aa8aa5f5111eefdd787718a7be6d8c530 | [
"C#",
"Python"
] | 15 | C# | penguin-of-linux/PenguinsLib | ec436318c7d02d8de85eb24a6d9f2a038a6141fc | 77d2dd97efd53f99c5dd10c2b9a1ed6224a4353d |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.