Апробация мобильного приложения

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

Рубрика Программирование, компьютеры и кибернетика
Вид дипломная работа
Язык русский
Дата добавления 30.08.2016
Размер файла 1,1 M

Отправить свою хорошую работу в базу знаний просто. Используйте форму, расположенную ниже

Студенты, аспиранты, молодые ученые, использующие базу знаний в своей учебе и работе, будут вам очень благодарны.

13. Beyond Words: How Humans Communicate Through Sound. [Электронный ресурс] / Nina Kraus - URL: http://www.annualreviews.org/doi/abs/10.1146/annurev-psych-122414-033318

14. Mohammed J. Zaki, Wagner Meira, Jr. Data Mining and Analysis: Fundamental Concepts and Algorithms // Cambridge University Press. 2014

15. Episodic Memory and Beyond: The Hippocampus and Neocortex in Transformation. [Электронный ресурс] / Morris Moscovitch - URL: http://www.annualreviews.org/doi/abs/10.1146/annurev-psych-113011-143733

16. Five Biggest Education Issues Of 2015. [Электронный ресурс] / Blake Neff - URL: http://dailycaller.com/2015/01/01/these-will-be-the-five-biggest-education-issues-of-2015/ (Дата обращений 18.04.2016)

17. French plan to become tourist friendly. [Электронный ресурс] / http://www.news.com.au - URL: http://www.news.com.au/travel/travel-updates/french-plan-to-become-tourist-friendly/story-e6frfq80-1226681690799 (Дата обращения 15.04.2016).

18. In Pursuit of Three Theories: Authoritarianism, Relative Deprivation, and Intergroup Contact. [Электронный ресурс] / Thomas F. Pettigrew - URL: http://www.annualreviews.org/doi/abs/10.1146/annurev-psych-122414-033327

19. Warren Bennos. On Becoming A Leader // Cover Source. 1989

20. Sun Tzu. The Art of War // SoHo Books. 2013

21. E. Christakis. The importance of being little : what preschoolers really need from grownups. // New York, New York : Viking, an imprint of Penguin Random House LLC

22. The real 21st-century problem in public education. [Электронный ресурс] / https://www.washingtonpost.com - URL: https://www.washingtonpost.com/news/answer-sheet/wp/2013/10/26/the-real-21st-century-problem-in-public-education/ (Дата обрщения 10.05.2016)

23. Stephen M .R. Covey. The Speed of Trust: The One Thing That Changes Everything // CM New York. 2009

24. The 25 Most Used Mobile Apps In Education. [Электронный ресурс] / Jeff Dunn - URL: http://www.edudemic.com/most-used-mobile-apps-education/ (Дата обращения 19.04.2016)

Приложение 1

namespace JSON_writer

{

static class Program

{

/// <summary>

/// The main entry point for the application.

/// </summary>

[STAThread]

static void Main()

{

Application.EnableVisualStyles();

Application.SetCompatibleTextRenderingDefault(false);

Application.Run(new MainWindow());

}

}

}

class Language

{

private String _name;

public String name

{

get { return _name; }

set { _name = value; }

}

public Language(String name)

{

this._name = name;

}

public Language(JToken json)

{

if (json["name"]!=null)

{

this._name = json["name"].ToString();

}

}

}

public partial class MainWindow : Form

{

List<string> behavioralTalentsLabels = new List<string> { "Activity points", "Pacivity points" };

List<string> worldviewlTalentsLabels = new List<string> { "Goodness points", "Evil points" };

List<string> classTalentsLabels = new List<string> { "Wisdom", "Resourcefulness", "Horizon", "Edurance", "Courage", "Knowledge", "Politeness", "Taste" };

int rowIndex = 0;

DataGridView gridView;

List<ExcursionPoint> points = new List<ExcursionPoint>();

JSON_writer.Talents.TalentsArray talents;

Excursion excursion;

public MainWindow()

{

InitializeComponent();

this.setDataGridView();

soundComboBox.SelectedIndex = 0;

}

private void writeButton_Click(object sender, EventArgs e)

{

List<Language> languages = new List<Language>();

for (int i = 0; i < languagesDataGridView.Rows.Count; i++ )

{

if (i != languagesDataGridView.Rows.Count - 1)

{

Language lang = new Language(languagesDataGridView.Rows[i].Cells[0].Value.ToString());

languages.Add(lang);

}

}

Excursion ex = new Excursion(nameTextBox.Text, this.ConvertStringArrayToString(descriptionRichTextBox.Lines.ToArray()), this.points, bundleIdTextBox.Text, categoryTextBox.Text, this.ConvertStringArrayToString(shortAnnotationRichTextBox.Lines), filenameTextBox.Text, authorTextBox.Text, int.Parse(durationTextBox.Text), soundComboBox.Text, genreTextBox.Text, placeTextBox.Text, languages, this.talents, int.Parse(maxAgeTextBox.Text), sizeTextBox.Text, this.ConvertStringArrayToString(mainTaskRichTextBox.Lines));

//logTextBox.AppendText(Environment.NewLine + ex.description);

JsonSerializer ser = new JsonSerializer();

ser.NullValueHandling = NullValueHandling.Ignore;

ser.Formatting = Formatting.Indented;

String path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "/" + ex.filename + ".json";

using (StreamWriter sw = new StreamWriter(@path))

using (JsonWriter writer = new JsonTextWriter(sw))

{

ser.Serialize(writer, ex);

}

MessageBox.Show("File is saved successgully!");

//string json = JsonConvert.SerializeObject(ex, Formatting.Indented);

//System.IO.File.WriteAllText(@"C:\Users\Патутинский Федор\Desktop\excursion.json", json);

}

private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)

{

}

private void setDataGridView()

{

talentsGridView.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(talentsGridView_EditingControlShowing);

// languagesDataGridView.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(talentsGridView_EditingControlShowing);

}

private void talentsGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)

{

ComboBox combo = e.Control as ComboBox;

if (combo != null)

{

combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);

combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);

}

}

private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)

{

ComboBox cb = (ComboBox)sender;

string item = cb.Text;

if (item != null)

{

int index = talentsGridView.CurrentCell.RowIndex;

string type = cb.Text;

switch (type)

{

case "WorldView":

DataGridViewComboBoxCell combo = this.talentsGridView[1, index] as DataGridViewComboBoxCell;

combo.DataSource = this.worldviewlTalentsLabels;

break;

case "Behavioral":

DataGridViewComboBoxCell combo2 = this.talentsGridView[1, index] as DataGridViewComboBoxCell;

combo2.DataSource = this.behavioralTalentsLabels;

break;

case "Class":

DataGridViewComboBoxCell combo3 = this.talentsGridView[1, index] as DataGridViewComboBoxCell;

combo3.DataSource = this.classTalentsLabels;

break;

default:

break;

}

}

}

private void deleteToolStripMenuItem_Click(object sender, EventArgs e)

{

if (this.gridView == talentsGridView)

{

if (this.rowIndex != this.talentsGridView.Rows.Count-1)

{

this.talentsGridView.Rows.RemoveAt(this.rowIndex);

}

}

else if (this.gridView == languagesDataGridView)

{

if (this.rowIndex != this.languagesDataGridView.Rows.Count - 1)

{

this.languagesDataGridView.Rows.RemoveAt(this.rowIndex);

}

}

else if (this.gridView == pointsGridView)

{

if (this.rowIndex != this.pointsGridView.Rows.Count - 1)

{

if (this.rowIndex < this.points.Count)

{

this.points.RemoveAt(this.rowIndex);

}

// this.pointsGridView.Rows.RemoveAt(this.rowIndex);

this.setPointGridView(this.points);

List<String> list = new List<String>();

for (int i = 0; i < points.Count(); i++)

{

list.Add(i.ToString());

}

pointIndexesComboBox.DataSource = new List<String>(list);

dialogsStepIndexesComboBox.DataSource = new List<String>(list);

if (list.Count != 0)

{

pointIndexesComboBox.SelectedIndex = 0;

dialogsStepIndexesComboBox.SelectedIndex = 0;

// this.points[rowIndex].dialogs.dialogs = null;

// this.points[rowIndex].task = null;

this.SetDialogsDataGridView(0);

this.SetTaskDataGridView();

}

}

}

else if (this.gridView == taskDataGridView)

{

this.points[this.rowIndex].task = null;

this.taskDataGridView.Rows.RemoveAt(this.rowIndex);

this.SetTaskDataGridView();

}

else if (this.gridView == dialogDataGridView)

{

// this.points[int.Parse(dialogsStepIndexesComboBox.Text)].dialogs.dialogs[this.rowIndex] = null;

this.points[int.Parse(dialogsStepIndexesComboBox.Text)].dialogs.dialogs.RemoveAt(this.rowIndex);

//this.dialogDataGridView.Rows.RemoveAt(this.rowIndex);

this.SetDialogsDataGridView(int.Parse(dialogsStepIndexesComboBox.Text));

}

else

{

//MessageBox.Show(sender.GetType().ToString());

}

}

private void talentsGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)

{

if (e.Button == MouseButtons.Right)

{

this.talentsGridView.Rows[e.RowIndex].Selected = true;

this.gridView = talentsGridView;

this.rowIndex = e.RowIndex;

this.talentsGridView.CurrentCell = this.talentsGridView.Rows[e.RowIndex].Cells[1];

this.contextMenuStrip1.Show(this.talentsGridView, e.Location);

contextMenuStrip1.Show(Cursor.Position);

}

}

private void groupBox1_Enter(object sender, EventArgs e)

{

}

private void MainWindow_Load(object sender, EventArgs e)

{

}

private void addOrChangeTaskButton_Click(object sender, EventArgs e)

{

List<string> ls = new List<string>();

ls.Add(caseCorrectAnswerTextView.Text);

ls.Add(caseIncorrectAnswerTextView.Text);

if (string.IsNullOrWhiteSpace(textOfTheTaskTextView.Text) == false)

{

if (TypeOfTaskComboBox.Text == "Empty task")

{

ls.Clear();

ls.Add(correctAnswerTextView.Text);

if (this.checkIfNumber(ls) != false)

{

JSON_writer.Tasks.EmptyTask task = new JSON_writer.Tasks.EmptyTask(textOfTheTaskTextView.Text, "Empty task", int.Parse(correctAnswerTextView.Text));

this.points[int.Parse(pointIndexesComboBox.Text)].task = task;

this.SetTaskDataGridView();

MessageBox.Show("Task is saved");

return;

}

else

{

return;

}

}

}

else

{

MessageBox.Show("Fill in the text of the task");

return;

}

if (string.IsNullOrWhiteSpace(TypeOfTaskComboBox.Text) || string.IsNullOrWhiteSpace(textOfTheTaskTextView.Text) || string.IsNullOrWhiteSpace(answersRichTextBox.Text) || string.IsNullOrWhiteSpace(caseCorrectAnswerTextView.Text) || string.IsNullOrWhiteSpace(caseIncorrectAnswerTextView.Text))

{

MessageBox.Show("Wrong data!");

return;

}

else if (this.checkIfNumber(ls) == false)

{

return;

}

else

{

if (TypeOfTaskComboBox.Text == "Multiple choice")

{

ls.Clear();

ls.Add(correctAnswerTextView.Text);

if (string.IsNullOrWhiteSpace(correctAnswerTextView.Text))

{

MessageBox.Show("Fill in correct answer index");

return;

}

else if (this.checkIfNumber(ls) == false)

{

return;

}

else

{

JSON_writer.Tasks.MultipleChoiceTask task = new JSON_writer.Tasks.MultipleChoiceTask(textOfTheTaskTextView.Text, "Multiple choice", answersRichTextBox.Lines, int.Parse(correctAnswerTextView.Text), int.Parse(caseCorrectAnswerTextView.Text), int.Parse(caseIncorrectAnswerTextView.Text));

this.points[int.Parse(pointIndexesComboBox.Text)].task = task;

this.SetTaskDataGridView();

MessageBox.Show("Task is saved");

}

}

else if (TypeOfTaskComboBox.Text == "Text answer")

{

JSON_writer.Tasks.TextTask task = new JSON_writer.Tasks.TextTask(textOfTheTaskTextView.Text, "Text question", answersRichTextBox.Lines[0], int.Parse(caseCorrectAnswerTextView.Text), int.Parse(caseIncorrectAnswerTextView.Text));

this.points[int.Parse(pointIndexesComboBox.Text)].task = task;

this.SetTaskDataGridView();

MessageBox.Show("Task is saved");

}

}

}

private void savePoints_Click(object sender, EventArgs e)

{

bool successfulSafe = true;

for (int i = 0; i < pointsGridView.Rows.Count; i++)

{

String name = "";

String image = "";

String description = "";

if (pointsGridView.Rows[i].Cells[1].Value != null && pointsGridView.Rows[i].Cells[2].Value != null && pointsGridView.Rows[i].Cells[3].Value != null)

{

name = pointsGridView.Rows[i].Cells[1].Value.ToString();

image = pointsGridView.Rows[i].Cells[2].Value.ToString();

description = pointsGridView.Rows[i].Cells[3].Value.ToString();

}

else

{

if (i != pointsGridView.Rows.Count - 1)

{

successfulSafe = false;

MessageBox.Show("Error in line " + i);

}

break;

}

Double latitude = 0;

Double longitude = 0;

if (pointsGridView.Rows[i].Cells[4].Value != null && pointsGridView.Rows[i].Cells[5].Value != null)

{

Double.TryParse(pointsGridView.Rows[i].Cells[4].Value.ToString(), out latitude);

Double.TryParse(pointsGridView.Rows[i].Cells[5].Value.ToString(), out longitude);

}

Coordinate coord = new Coordinate(latitude, longitude);

if (coord.latitude == 0 || coord.longitude == 0)

{

coord = null;

}

if (i < this.points.Count())

{

this.points[i].coordinate = coord;

this.points[i].description = description;

this.points[i].name = name;

this.points[i].image = image;

}

else

{

ExcursionPoint ep = new ExcursionPoint(coord, description, name, null, null, image);

this.points.Add(ep);

}

}

List<string> indexes = new List<string>();

for (int i = 0; i < pointsGridView.Rows.Count; i++)

{

if (i != pointsGridView.Rows.Count - 1)

{

pointsGridView.Rows[i].Cells[0].Value = i.ToString();

indexes.Add(i.ToString());

}

}

pointIndexesComboBox.DataSource = new List<string>(indexes);

dialogsStepIndexesComboBox.DataSource = new List<string>(indexes);

pointIndexesComboBox.SelectedIndex = 0;

dialogsStepIndexesComboBox.SelectedIndex = 0;

if (successfulSafe == true)

{

MessageBox.Show("Saved successfully");

}

}

private void pointsGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)

{

List<string> indexes = new List<string>();

for (int i = 0; i < pointsGridView.Rows.Count; i++)

{

if (i != pointsGridView.Rows.Count - 1)

{

pointsGridView.Rows[i].Cells[0].Value = i.ToString();

}

}

}

private void talentsGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)

{

}

private void saveTalents_Click(object sender, EventArgs e)

{

JSON_writer.Talents.BehavioralTalents bt = null;

JSON_writer.Talents.WorldViewTalents wwt = null;

List<JSON_writer.ClassTalent> ctList = new List<ClassTalent>() ;

for (int i = 0; i < talentsGridView.Rows.Count; i++ )

{

if (i != talentsGridView.Rows.Count-1)

{

switch (talentsGridView.Rows[i].Cells[0].Value.ToString())

{

case "WorldView":

//JSON_writer.Talents.WorldViewTalents talents = new

switch (talentsGridView.Rows[i].Cells[1].Value.ToString())

{

case "Goodness points":

if (wwt == null)

{

wwt = new Talents.WorldViewTalents(0, 0);

}

wwt.goodnessPoints = int.Parse(talentsGridView.Rows[i].Cells[2].Value.ToString());

break;

case "Evil points":

if (wwt == null)

{

wwt = new Talents.WorldViewTalents(0, 0);

}

wwt.evilPoints = int.Parse(talentsGridView.Rows[i].Cells[2].Value.ToString());

break;

default:

break;

}

break;

case "Behavioral":

switch (talentsGridView.Rows[i].Cells[1].Value.ToString())

{

case "Activity points":

if (bt == null)

{

bt = new Talents.BehavioralTalents(0, 0);

}

bt.activityPoints = int.Parse(talentsGridView.Rows[i].Cells[2].Value.ToString());

break;

case "Pacivity points":

if (bt == null)

{

bt = new Talents.BehavioralTalents(0, 0);

}

bt.pacivityPoints = int.Parse(talentsGridView.Rows[i].Cells[2].Value.ToString());

break;

default:

break;

}

break;

case "Class":

ClassTalent ct = new ClassTalent(talentsGridView.Rows[i].Cells[1].Value.ToString(), int.Parse(talentsGridView.Rows[i].Cells[2].Value.ToString()));

ctList = this.addClassTalentToList(ctList,ct);

this.talents = new Talents.TalentsArray(bt,wwt,ctList);

break;

default:

break;

}

}

}

MessageBox.Show("Talents saved successfully.");

}

private String ConvertStringArrayToString(string [] array)

{

String returnString = "";

for (int i = 0; i < array.Length; i++)

{

if (i == 0)

{

returnString = array[i];

}

else

{

returnString = returnString + "***" + array[i];

}

}

return returnString;

}

private void SetTaskDataGridView()

{

int numberOfNotNullTasks = 0;

for (int i = 0; i < this.points.Count; i++)

{

if (this.points[i].task != null)

{

numberOfNotNullTasks++;

DataGridViewRow row = this.getNecRow(i, taskDataGridView);

row.Cells[0].Value = i.ToString();

row.Cells[1].Value = this.points[i].task.type;

row.Cells[2].Value = this.points[i].task.task;

if (this.points[i].task is JSON_writer.Tasks.MultipleChoiceTask)

{

JSON_writer.Tasks.MultipleChoiceTask t = (JSON_writer.Tasks.MultipleChoiceTask)this.points[i].task;

row.Cells[3].Value = this.ConvertStringArrayToString(t.answers);

row.Cells[4].Value = t.case_correct;

row.Cells[5].Value = t.case_incorrect;

row.Cells[6].Value = t.correctAnswerIndex;

}

else if (this.points[i].task is JSON_writer.Tasks.TextTask)

{

JSON_writer.Tasks.TextTask t = (JSON_writer.Tasks.TextTask)this.points[i].task;

row.Cells[3].Value = t.answer;

row.Cells[4].Value = t.case_correct;

row.Cells[5].Value = t.case_incorrect;

}

else if (this.points[i].task is JSON_writer.Tasks.EmptyTask)

{

JSON_writer.Tasks.EmptyTask t = (JSON_writer.Tasks.EmptyTask)this.points[i].task;

row.Cells[6].Value = t.nextStep.ToString();

}

}

}

if (numberOfNotNullTasks < taskDataGridView.Rows.Count)

{

int count = taskDataGridView.Rows.Count;

for (int i = numberOfNotNullTasks; i < count; i++ )

{

taskDataGridView.Rows.RemoveAt(i);

count--;

}

}

}

private DataGridViewRow getNecRow(int index, DataGridView table)

{

bool isExists = false;

DataGridViewRow returnRow = new DataGridViewRow();

for (int i = 0; i < table.Rows.Count; i++ )

{

if (index == int.Parse(table.Rows[i].Cells[0].Value.ToString()))

{

isExists = true;

returnRow = table.Rows[i];

break;

}

}

if (isExists == false)

{

table.Rows.Add();

returnRow = table.Rows[table.Rows.Count-1];

}

return returnRow;

}

private List<ClassTalent> addClassTalentToList(List<ClassTalent> list, ClassTalent talent)

{

if (list.Count == 0)

{

list.Add(talent);

return list;

}

for (var i = 0; i < list.Count; i++ )

{

if (list[i].name == talent.name)

{

list[i] = talent;

return list;

}

}

list.Add(talent);

return list;

}

private void saveDialogButton_Click(object sender, EventArgs e)

{

if (string.IsNullOrWhiteSpace(dialogsStepIndexesComboBox.Text) || string.IsNullOrWhiteSpace(dialogIndexTextBox.Text) || string.IsNullOrWhiteSpace(characterTextBox.Text) || string.IsNullOrWhiteSpace(dialogTexttextBox.Text) || string.IsNullOrWhiteSpace(mainCharacterTextBox.Text) || string.IsNullOrWhiteSpace(dialogsStepIndexesComboBox.Text))

{

MessageBox.Show("Wrong data!");

return;

}

else

{

ExcursionPoint point = this.points[int.Parse(dialogsStepIndexesComboBox.Text)];

int dialogIndex = int.Parse(dialogIndexTextBox.Text);

String character = characterTextBox.Text;

String dialogText = dialogTexttextBox.Text;

String mainCharacter = mainCharacterTextBox.Text;

Dialog dialog = new Dialog(character, dialogText);

if (point.dialogs == null)

{

List<Dialog> list = new List<Dialog>();

list.Add(dialog);

point.dialogs = new Dialogs(list, mainCharacter);

}

else

{

bool isThereAnyIndex = false;

for (int i = 0; i < point.dialogs.dialogs.Count;i++ )

{

if (i == dialogIndex)

{

isThereAnyIndex = true;

point.dialogs.dialogs[i] = dialog;

break;

}

}

if (isThereAnyIndex == false)

{

point.dialogs.dialogs.Add(dialog);

}

}

this.SetDialogsDataGridView(int.Parse(dialogsStepIndexesComboBox.Text));

MessageBox.Show("Dialog saved successfully!");

}

}

private void SetDialogsDataGridView(int index)

{

if (this.points.Count != 0)

{

if (this.points[index].dialogs != null)

{

int numberOfDialogs = 0;

for (int i = 0; i < this.points[index].dialogs.dialogs.Count; i++)

{

if (this.points[index].dialogs.dialogs[i] != null)

{

numberOfDialogs++;

Dialog dialog = this.points[index].dialogs.dialogs[i];

DataGridViewRow row = this.getNecRow(i, dialogDataGridView);

// MessageBox.Show(i.ToString());

row.Cells[0].Value = i.ToString();

row.Cells[1].Value = dialog.name;

row.Cells[2].Value = dialog.text;

}

}

dialogDataGridView.Refresh();

if (numberOfDialogs < dialogDataGridView.Rows.Count)

{

int count = dialogDataGridView.Rows.Count;

for (int i = numberOfDialogs; i < count; i++)

{

dialogDataGridView.Rows.RemoveAt(i);

count--;

}

}

}

else

{

dialogDataGridView.Rows.Clear();

dialogDataGridView.Refresh();

/*for (int i = 0; i < dialogDataGridView.Rows.Count; i++ )

{

dialogDataGridView.Rows.RemoveAt(0);

}*/

}

}

}

private void dialogsStepIndexesComboBox_SelectedIndexChanged(object sender, EventArgs e)

{

this.SetDialogsDataGridView(int.Parse(dialogsStepIndexesComboBox.Text));

if (this.points[int.Parse(dialogsStepIndexesComboBox.Text)].dialogs != null)

{

dialogIndexTextBox.Text = "0";

characterTextBox.Text = this.points[int.Parse(dialogsStepIndexesComboBox.Text)].dialogs.dialogs[0].name;

dialogTexttextBox.Text = this.points[int.Parse(dialogsStepIndexesComboBox.Text)].dialogs.dialogs[0].text;

mainCharacterTextBox.Text = this.points[int.Parse(dialogsStepIndexesComboBox.Text)].dialogs.mainCharacter;

}

}

private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)

{

}

private void label27_Click(object sender, EventArgs e)

{

}

private void characterTextBox_TextChanged(object sender, EventArgs e)

{

}

private void label29_Click(object sender, EventArgs e)

{

}

private void dialogTexttextBox_TextChanged(object sender, EventArgs e)

{

}

private void Character_Click(object sender, EventArgs e)

{

}

private void label28_Click(object sender, EventArgs e)

{

}

private void mainCharacterTextBox_TextChanged(object sender, EventArgs e)

{

}

private void dialogIndexComboBox_SelectedIndexChanged(object sender, EventArgs e)

{

}

private void loadButtonPressed_Click(object sender, EventArgs e)

{

OpenFileDialog openFileDialog1 = new OpenFileDialog();

openFileDialog1.Title = "Select an excursion file";

// Show the Dialog.

// If the user clicked OK in the dialog and

// a .CUR file was selected, open it.

if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)

{

//System.IO.StreamReader sr = new System.IO.StreamReader(openFileDialog1.FileName);

using (StreamReader file = File.OpenText(openFileDialog1.FileName))

{

JsonSerializer serializer = new JsonSerializer();

JToken ob = (JToken)serializer.Deserialize(file, typeof(JToken));

this.excursion = null;

this.excursion = new Excursion(ob);

this.setViewElements(this.excursion);

}

}

}

private void setViewElements(Excursion ex)

{

this.points = excursion.points;

this.talents = excursion.talents;

nameTextBox.Text = ex.name;

bundleIdTextBox.Text = ex.bundleId;

authorTextBox.Text = ex.author;

durationTextBox.Text = ex.duration.ToString();

soundComboBox.SelectedItem = ex.sound;

filenameTextBox.Text = ex.filename;

genreTextBox.Text = ex.genre;

placeTextBox.Text = ex.place;

categoryTextBox.Text = ex.category;

maxAgeTextBox.Text = ex.maxAge.ToString();

sizeTextBox.Text = ex.size;

this.setLanguagesGridView(ex.languages);

mainTaskRichTextBox.Text = ex.mainTask;

shortAnnotationRichTextBox.Text = ex.shortAnnotation;

descriptionRichTextBox.Text = ex.description;

this.setTalentsGridView(ex.talents);

this.setPointGridView(ex.points);

}

private void setLanguagesGridView(List<Language> languages)

{

this.clearRowasForDatagridViewWithAdditionalRow(languagesDataGridView);

//languagesDataGridView.DataSource = languages;

for (int i = 0; i < languages.Count(); i++)

{

if (languages.Count() > languagesDataGridView.Rows.Count - 1)

{

languagesDataGridView.Rows.Add();

}

languagesDataGridView.Rows[i].Cells[0].Value = languages[i].name;

}

}

private void setTalentsGridView(JSON_writer.Talents.TalentsArray talents)

{

this.clearRowasForDatagridViewWithAdditionalRow(talentsGridView);

int talentsCount = talents.getNumberOfTalents();

if (talents.behavioral != null)

{

if (talents.behavioral.activityPoints != null)

{

if (talentsCount > talentsGridView.Rows.Count - 1)

{

talentsGridView.Rows.Add();

}

DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count-2].Cells[0];

cell.Value = "Behavioral";

DataGridViewComboBoxCell cell2 = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[1];

cell2.DataSource = this.behavioralTalentsLabels;

cell2.Value = this.behavioralTalentsLabels[0];

talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[2].Value = talents.behavioral.activityPoints.ToString();

}

if (talents.behavioral.pacivityPoints != null)

{

if (talentsCount > talentsGridView.Rows.Count - 1)

{

talentsGridView.Rows.Add();

}

DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count-2].Cells[0];

cell.Value = "Behavioral";

DataGridViewComboBoxCell cell2 = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[1];

cell2.DataSource = this.behavioralTalentsLabels;

cell2.Value = this.behavioralTalentsLabels[1];

talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[2].Value = talents.behavioral.pacivityPoints.ToString();

}

}

if (talents.worldview != null)

{

if (talents.worldview.goodnessPoints != null)

{

if (talentsCount > talentsGridView.Rows.Count - 1)

{

talentsGridView.Rows.Add();

}

DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count-2].Cells[0];

cell.Value = "Worldview";

DataGridViewComboBoxCell cell2 = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[1];

cell2.DataSource = this.worldviewlTalentsLabels;

cell2.Value = this.worldviewlTalentsLabels[0];

talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[2].Value = talents.worldview.goodnessPoints.ToString();

}

if (talents.worldview.evilPoints != null)

{

if (talentsCount > talentsGridView.Rows.Count - 1)

{

talentsGridView.Rows.Add();

}

DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count-2].Cells[0];

cell.Value = "Worldview";

DataGridViewComboBoxCell cell2 = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[1];

cell2.DataSource = this.worldviewlTalentsLabels;

cell2.Value = this.worldviewlTalentsLabels[1];

talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[2].Value = talents.worldview.evilPoints.ToString();

}

}

if (talents.@class != null)

{

for (int i = 0; i < talents.@class.Count(); i++)

{

if (talentsCount > talentsGridView.Rows.Count - 1)

{

talentsGridView.Rows.Add();

}

DataGridViewComboBoxCell cell = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count-2].Cells[0];

cell.Value = "Class";

DataGridViewComboBoxCell cell2 = (DataGridViewComboBoxCell)talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[1];

cell2.DataSource = this.classTalentsLabels;

cell2.Value = talents.@class[i].name;

talentsGridView.Rows[talentsGridView.Rows.Count - 2].Cells[2].Value = talents.@class[i].points.ToString();

}

}

}

private void setPointGridView(List<JSON_writer.ExcursionPoint> points)

{

//pointsGridView.DataSource = points;

List<String> list = new List<String>();

this.clearRowasForDatagridViewWithAdditionalRow(pointsGridView);

for (int i = 0; i < points.Count(); i++)

{

if (points.Count() > pointsGridView.Rows.Count - 1)

{

pointsGridView.Rows.Add();

}

pointsGridView.Rows[i].Cells[0].Value = i.ToString();

pointsGridView.Rows[i].Cells[1].Value = points[i].name;

if (points[i].image != null)

{

pointsGridView.Rows[i].Cells[2].Value = points[i].image;

}

else

{

pointsGridView.Rows[i].Cells[2].Value = "";

}

pointsGridView.Rows[i].Cells[3].Value = points[i].description;

if (points[i].coordinate != null)

{

pointsGridView.Rows[i].Cells[4].Value = points[i].coordinate.latitude.ToString();

pointsGridView.Rows[i].Cells[5].Value = points[i].coordinate.longitude.ToString();

}

else

{

pointsGridView.Rows[i].Cells[4].Value = "";

pointsGridView.Rows[i].Cells[5].Value = "";

}

list.Add(i.ToString());

}

pointIndexesComboBox.DataSource = new List<String>(list);

dialogsStepIndexesComboBox.DataSource = new List<String>(list);

if (list.Count != 0)

{

pointIndexesComboBox.SelectedIndex = 0;

dialogsStepIndexesComboBox.SelectedIndex = 0;

this.SetDialogsDataGridView(0);

this.SetTaskDataGridView();

}

}

private void clearRowasForDatagridViewWithAdditionalRow(DataGridView table)

{

if (table.Rows.Count > 1)

{

for (int i = 0; i < table.Rows.Count; i++)

{

table.Rows.RemoveAt(0);

}

// MessageBox.Show(table.Rows.Count.ToString());

}

}

private void pointIndexesComboBox_SelectedIndexChanged(object sender, EventArgs e)

{

int index = int.Parse(pointIndexesComboBox.Text);

if (this.points[index].task != null)

{

switch (this.points[index].task.type)

{

case "Text question":

JSON_writer.Tasks.TextTask task = (JSON_writer.Tasks.TextTask)points[index].task;

TypeOfTaskComboBox.SelectedIndex = 1;

textOfTheTaskTextView.Text = task.task;

answersRichTextBox.Text = task.answer;

caseCorrectAnswerTextView.Text = task.case_correct.ToString();

caseIncorrectAnswerTextView.Text = task.case_incorrect.ToString();

correctAnswerTextView.Text = "";

break;

case "Multiple choice":

JSON_writer.Tasks.MultipleChoiceTask task2 = (JSON_writer.Tasks.MultipleChoiceTask)points[index].task;

TypeOfTaskComboBox.SelectedIndex = 0;

textOfTheTaskTextView.Text = task2.task;

answersRichTextBox.Lines = task2.answers;

caseCorrectAnswerTextView.Text = task2.case_correct.ToString();

caseIncorrectAnswerTextView.Text = task2.case_incorrect.ToString();

correctAnswerTextView.Text = task2.correctAnswerIndex.ToString();

break;

case "Empty task":

JSON_writer.Tasks.EmptyTask task3 = (JSON_writer.Tasks.EmptyTask)points[index].task;

TypeOfTaskComboBox.SelectedIndex = 2;

textOfTheTaskTextView.Text = task3.task;

answersRichTextBox.Text = "";;

caseCorrectAnswerTextView.Text = "";

caseIncorrectAnswerTextView.Text = "";

correctAnswerTextView.Text = task3.nextStep.ToString();

break;

default:

break;

}

}

else

{

textOfTheTaskTextView.Text = ""; ;

answersRichTextBox.Text = "";

caseCorrectAnswerTextView.Text = "";

caseIncorrectAnswerTextView.Text = "";

correctAnswerTextView.Text = "";

}

}

private void languagesDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)

{

if (e.Button == MouseButtons.Right)

{

this.languagesDataGridView.Rows[e.RowIndex].Selected = true;

this.rowIndex = e.RowIndex;

this.gridView = languagesDataGridView;

this.languagesDataGridView.CurrentCell = this.languagesDataGridView.Rows[e.RowIndex].Cells[0];

this.contextMenuStrip1.Show(this.languagesDataGridView, e.Location);

contextMenuStrip1.Show(Cursor.Position);

}

}

private void pointsGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)

{

if (e.Button == MouseButtons.Right)

{

this.pointsGridView.Rows[e.RowIndex].Selected = true;

this.rowIndex = e.RowIndex;

this.gridView = pointsGridView;

this.pointsGridView.CurrentCell = this.pointsGridView.Rows[e.RowIndex].Cells[0];

this.contextMenuStrip1.Show(this.pointsGridView, e.Location);

contextMenuStrip1.Show(Cursor.Position);

}

}

private void dialogDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)

{

if (e.Button == MouseButtons.Right)

{

this.dialogDataGridView.Rows[e.RowIndex].Selected = true;

this.rowIndex = e.RowIndex;

this.gridView = dialogDataGridView;

this.dialogDataGridView.CurrentCell = this.dialogDataGridView.Rows[e.RowIndex].Cells[0];

this.contextMenuStrip1.Show(this.dialogDataGridView, e.Location);

contextMenuStrip1.Show(Cursor.Position);

}

}

private void taskDataGridView_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)

{

if (e.Button == MouseButtons.Right)

{

this.taskDataGridView.Rows[e.RowIndex].Selected = true;

this.rowIndex = e.RowIndex;

this.gridView = taskDataGridView;

this.taskDataGridView.CurrentCell = this.taskDataGridView.Rows[e.RowIndex].Cells[0];

this.contextMenuStrip1.Show(this.taskDataGridView, e.Location);

contextMenuStrip1.Show(Cursor.Position);

}

}

private bool checkIfNumber(List<string> array)

{

for (int i = 0; i < array.Count; i++)

{

int result = 0;

if (!int.TryParse(array[i], out result))

{

MessageBox.Show("Error: " + array[i] + " is not a number!");

return false;

}

}

return true;

}

}

class Excursion

{

private string _name;

private string _description;

private List<ExcursionPoint> _points;

private String _bundleId;

private String _category;

private String _shortAnnotation;

private String _filename;

private String _author;

private int _duration;

private String _sound;

private String _genre;

private String _place;

private List<Language> _languages;

private JSON_writer.Talents.TalentsArray _talents;

private int _maxAge;

private String _size;

private String _mainTask;

public string name

{

get { return _name; }

set { _name = value; }

}

public string description

{

get { return _description; }

set { _description = value; }

}

public List<ExcursionPoint> points

{

get { return _points; }

set { _points = value; }

}

public string bundleId

{

get { return _bundleId; }

set { _bundleId = value; }

}

public string category

{

get { return _category; }

set { _category = value; }

}

public string author

{

get { return _author; }

set { _author = value; }

}

public int duration

{

get { return _duration; }

set { _duration = value; }

}

public String sound

{

get { return _sound; }

set { _sound = value; }

}

public string genre

{

get { return _genre; }

set { _genre = value; }

}

public string place

{

get { return _place; }

set { _place = value; }

}

public String filename

{

get { return _filename; }

set { _filename = value; }

}

public List<Language> languages

{

get { return _languages; }

set { _languages = value; }

}

public JSON_writer.Talents.TalentsArray talents

{

get { return _talents; }

set { _talents = value; }

}

public int maxAge

{

get { return _maxAge; }

set { _maxAge = value; }

}

public string size

{

get { return _size; }

set { _size = value; }

}

public string mainTask

{

get { return _mainTask; }

set { _mainTask = value; }

}

public String shortAnnotation

{

get { return _shortAnnotation; }

set { _shortAnnotation = value; }

}

public Excursion(string name, string description, List<ExcursionPoint> points, String bundleId, String category, String shortAnnotation, String filename, String author, int duration, String sound, String genre, String place, List<Language> languages, JSON_writer.Talents.TalentsArray talents, int maxAge, String size, String mainTask)

{

this._name = name;

this._description = description;

this._points = points;

this._bundleId = bundleId;

this._category = category;

this._shortAnnotation = shortAnnotation;

this._filename = filename;

this._author = author;

this._duration = duration;

this._sound = sound;

this._genre = genre;

this._place = place;

this._languages = languages;

this._talents = talents;

this._maxAge = maxAge;

this._size = size;

this._mainTask = mainTask;

}

public Excursion(JToken json)

{

if (json["name"] != null)

{

this._name = json["name"].ToString();

}

if (json["description"] != null)

{

this._description = json["description"].ToString();

}

if (json["shortAnnotation"] != null)

{

this._shortAnnotation = json["shortAnnotation"].ToString();

}

if (json["filename"] != null)

{

this._filename = json["filename"].ToString();

}

if (json["points"] != null)

{

JArray points = (JArray)json["points"];

List<ExcursionPoint> ps = new List<ExcursionPoint>();

for (int i = 0; i < points.Count(); i++ )

{

ExcursionPoint point = new ExcursionPoint(points[i]);

ps.Add(point);

}

this._points = ps;

}

if (json["bundleId"] != null)

{

this._bundleId = json["bundleId"].ToString();

}

if (json["category"] != null)

{

this._category = json["category"].ToString();

}

if (json["author"] != null)

{

this._author = json["author"].ToString();

}

if (json["duration"] != null)

{

this._duration = int.Parse(json["duration"].ToString());

}

if (json["sound"] != null)

{

this._sound = json["sound"].ToString();

}

if (json["genre"] != null)

{

this._genre = json["genre"].ToString();

}

if (json["place"] != null)

{

this._place = json["place"].ToString();

}

if (json["filename"] != null)

{

this._filename = json["filename"].ToString();

}

if (json["languages"] != null)

{

JArray languages = (JArray)json["languages"];

this._languages = new List<Language>();

for (int i = 0; i < languages.Count; i++ )

{

this._languages.Add(new Language(languages[i]));

}

}

if (json["talents"] != null)

{

this._talents = new Talents.TalentsArray(json["talents"]);

}

if (json["maxAge"] != null)

{

this._maxAge = int.Parse(json["maxAge"].ToString());

}

if (json["size"] != null)

{

this._size = json["size"].ToString();

}

if (json["mainTask"] != null)

{

this._mainTask = json["mainTask"].ToString();

}

if (json["mainTask"] != null)

{

this._mainTask = json["mainTask"].ToString();

}

}

class Dialog

{

private String _name;

private String _text;

public String name

{

get { return _name; }

set { _name = value; }

}

public String text

{

get { return _text; }

set { _text = value; }

}

public Dialog(string name, string text)

{

this._name = name;

this._text = text;

}

public Dialog(JToken json)

{

if (json["name"]!=null)

{

this._name = json["name"].ToString();

}

if (json["text"] != null)

{

this._text = json["text"].ToString();

}

}

}

class Dialogs

{

private String _mainCharacter;

public String mainCharacter

{

get { return _mainCharacter; }

set { _mainCharacter = value; }

}

private List<Dialog> _dialogs;

public List<Dialog> dialogs

{

get { return _dialogs; }

set { _dialogs = value; }

}

public Dialogs(List<Dialog> dialogs, String mainCharacter)

{

this._dialogs = dialogs;

this._mainCharacter = mainCharacter;

}

public Dialogs(JToken json)

{

if (json["dialogs"] != null)

{

this._dialogs = new List<Dialog>();

JArray diags = (JArray)json["dialogs"];

for (int i = 0; i < diags.Count; i++)

{

this._dialogs.Add(new Dialog(diags[i]));

}

}

if (json["mainCharacter"] != null)

{

this._mainCharacter = json["mainCharacter"].ToString();

}

}

}

class Coordinate

{

Double _latitude;

Double _longitude;

public Double longitude

{

get { return _longitude; }

set { _longitude = value; }

}

public Double latitude

{

get { return _latitude; }

set { _latitude = value; }

}

public Coordinate(Double latitude, Double longitude)

{

this._latitude = latitude;

this._longitude = longitude;

}

public Coordinate(JToken json)

{

if (json["longitude"] != null)

{

this._longitude = (Double)json["longitude"];

}

if (json["latitude"] != null)

{

this._latitude = (Double)json["latitude"];

}

}

}

Приложение 2

//

// PaymentTransactionObserver.swift

// Owley_quest

//

// Created by Филатов СС on 25.08.15.

// Copyright (c) 2015 Sergey Filatov. All rights reserved.

//

import Foundation

import StoreKitlet IAPTransactionInProgress = "IAPTransactionInProgress"

let IAPTransactionFailed = "IAPTransactionFailed"

let IAPTransactionComplete = "IAPTransactionComplete"

let IAPTransactionRestore = "IAPTransactionRestore"let IAPDownloadWaiting = "IAPDownloadWaiting"

let IAPDownloadActive = "IAPDownloadActive"

let IAPDownloadFinished = "IAPDownloadFinished"

let IAPDownloadFailed = "IAPDownloadFailed"

class PaymentTransactionObserver : NSObject, SKPaymentTransactionObserver {

var wereThereAnyTransactions = false;

func paymentQueueRestoreCompletedTransactionsFinished(queue: SKPaymentQueue) {

print("restore finished");

// NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadFinished, object: nil);

if self.wereThereAnyTransactions == false{

NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadFinished, object: nil);

}

self.wereThereAnyTransactions = false;

}

func paymentQueue(queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: NSError) {

print(error);

if self.wereThereAnyTransactions == false{

NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadFinished, object: nil);

}

self.wereThereAnyTransactions = false;

}func paymentQueue(queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {

self.wereThereAnyTransactions = true;

// print(transactions);

// print(transactions.count);

for transaction in transactions { if let trans: SKPaymentTransaction = transaction {

switch (trans.transactionState) {

case .Purchasing:

showTransactionAsInProgress(false)

case .Deferred:

showTransactionAsInProgress(true)

case .Failed:

failedTransaction(trans)

case .Purchased:

completeTransaction(trans)

case .Restored:

restoreTransaction(trans)

}

}

}

}func paymentQueue(queue: SKPaymentQueue, updatedDownloads downloads: [SKDownload]) {for d in downloads {

if let download: SKDownload = d{

switch (download.downloadState) {

case .Waiting:

waitingDownload(download)

case .Active:

activeDownload(download)

case .Finished:

finishedDownload(download)

case .Failed:

failedDownload(download)

case .Cancelled:

cancelledDownload(download)

case .Paused:

pausedDownload(download)

}

}

}

}//MARK: Payment transaction related methods

func showTransactionAsInProgress(deferred: Bool) {NSNotificationCenter.defaultCenter().postNotificationName(IAPTransactionInProgress, object: deferred)

}func failedTransaction(transaction: SKPaymentTransaction) {NSNotificationCenter.defaultCenter().postNotificationName(IAPTransactionFailed, object: transaction.error)SKPaymentQueue.defaultQueue().finishTransaction(transaction)

}func completeTransaction(transaction: SKPaymentTransaction) {print("id \(transaction.transactionIdentifier)", terminator: "")NSNotificationCenter.defaultCenter().postNotificationName(IAPTransactionComplete, object: transaction)

if let downloads: [SKDownload] = transaction.downloads {

if downloads.count > 0{

SKPaymentQueue.defaultQueue().startDownloads(downloads)

}

else{

SKPaymentQueue.defaultQueue().finishTransaction(transaction)

}

}else{

SKPaymentQueue.defaultQueue().finishTransaction(transaction)

}

}func restoreTransaction(transaction: SKPaymentTransaction) { NSNotificationCenter.defaultCenter().postNotificationName(IAPTransactionRestore, object: transaction)

if let downloads: [SKDownload] = transaction.downloads {

if downloads.count > 0{

SKPaymentQueue.defaultQueue().startDownloads(downloads)

}

else{

SKPaymentQueue.defaultQueue().finishTransaction(transaction)

}

}

else{

SKPaymentQueue.defaultQueue().finishTransaction(transaction)

}}//MARK: Download related methodsfunc waitingDownload(download: SKDownload) {

NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadWaiting, object: download)

}func activeDownload(download: SKDownload) {

NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadActive, object: download)

}func finishedDownload(download: SKDownload) {

// print(download);moveDownloadedFiles(download)NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadFinished, object: download)SKPaymentQueue.defaultQueue().finishTransaction(download.transaction)

}func failedDownload(download: SKDownload) {NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadFailed, object: download)SKPaymentQueue.defaultQueue().finishTransaction(download.transaction)

}func cancelledDownload(download: SKDownload) {//nothing to do right now

}func pausedDownload(download: SKDownload) {

//won't implement at this time

}//MARK: Helper method to move filesfunc moveDownloadedFiles(download: SKDownload)

{

//move files to Documents folder print(download.transaction.payment.productIdentifier);

let fileManager = NSFileManager.defaultManager()let url = download.contentURL!.URLByAppendingPathComponent("Contents");

let path = url.path!;

var path2: String = "";

if let files: [String] = (try? fileManager.contentsOfDirectoryAtPath(path)) {

for el in files{ path2 = url.URLByAppendingPathComponent(el).path!;

let directoryForSave = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] ;

do {

let ur = NSURL(fileURLWithPath: directoryForSave);

try fileManager.copyItemAtPath(path2, toPath: ur.URLByAppendingPathComponent(el).path!)

} catch _ {

}

print(directoryForSave);

}

}

}}

//

// TransactionsMerger.swift

// Practica

//

// Created by Патутинский Федор on 23.01.16.

// Copyright © 2016 Fedor Patutinski. All rights reserved.

//import Foundation

import SwiftyJSON;class TransactionsMerger{func addMissingItemsToServer(jsonFile: JSON?, serverArray:NSArray){

if let dictionary = jsonFile!["history"].array{

for d in dictionary{

let time = d["time"].double!;

let coins = d["coins"].int!;

if (!doesServerContainObject(time, coins: coins, serverArray: serverArray)){

let transaction = NSMutableDictionary();

transaction["iu"] = userId

transaction["c"] = coins;

transaction["ts"] = time;

let sh = ServerHelper();

sh.saveTransaction(coins, time: time, bundleId: nil, handler: {

(success) in

print("Save result \(success)")

});

}

}

}

}func addMissingItemsToJSON(jsonFile: JSON?, serverArray:NSArray){

for p in serverArray{

let time = Double(p["timestamp"] as! String);

let coins = Int(p["coins"] as! String);

if (!doesJSONContainObject(time!, coins: coins!, jsonFile: jsonFile!)){

JSONHelper.saveUserCoins(coins!, masterFileName: "Transactions", time: time!)

}

}

}func doesServerContainObject(time: Double, coins: Int, serverArray:NSArray)->Bool{

for el in serverArray{

if ((el["coins"] as! Int == coins)&&(el["timestamp"] as! Double) == time){

return true;

}

}

return false;

}func doesJSONContainObject(time: Double, coins: Int, jsonFile:JSON)->Bool{

for el in jsonFile["history"].array!{

if ((el["coins"].int == coins)&&(el["time"].double == time)){

return true;

}

}

return false;

}

}

//

// DirectionsChecker.swift

// Owley_quest

//

// Created by Патутинский Федор on 30.08.15.

// Copyright (c) 2015 Fedor Patutinski. All rights reserved.

//import Foundation

import GoogleMaps;let inAreaNotification = "inAreaNotification";class DirectionsChecker: NSObject, CLLocationManagerDelegate, GMSMapViewDelegate {var mapView: GMSMapView!;

var locationManager: CLLocationManager!;var stepLocation: CLLocation!;var timer: NSTimer = NSTimer();

var isFirstLocationUpdate = false;var currentLocation: CLLocation!;init(stepLocation: CLLocation){

super.init();

self.locationManager = CLLocationManager();

self.locationManager.delegate = self;

self.locationManager.requestWhenInUseAuthorization();

locationManager.startUpdatingLocation();

self.stepLocation = stepLocation;

}func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {self.currentLocation = manager.location;

if self.isFirstLocationUpdate == false {

self.isFirstLocationUpdate = true;

self.mapView.myLocationEnabled = true;

self.timer = NSTimer.scheduledTimerWithTimeInterval(5.0, target: self, selector: #selector(DirectionsChecker.checkArea), userInfo: nil, repeats: true);

}}

func checkArea() {

let userLocation = self.currentLocation if DirectionsCounter.checkArea(self.stepLocation.coordinate, userLocation: userLocation.coordinate) {

NSNotificationCenter.defaultCenter().postNotificationName(inAreaNotification, object: true);

self.timer.invalidate();

self.locationManager.stopUpdatingLocation();

self.locationManager = nil;

NSNotificationCenter.defaultCenter().removeObserver(self);

self.mapView = nil;

self.currentLocation = nil; }

}}

//

// UnzipArchiveFromUrl.swift

// Practica

//

// Created by Патутинский Федор on 03.01.16.

// Copyright © 2016 Fedor Patutinski. All rights reserved.

//import Foundation

import SSZipArchiveclass UnzipArchiveFromUrl: NSObject, NSURLSessionDownloadDelegate {

var productId = "";func downloadWithURL(url: NSURL, productId: String) {

self.productId = productId;

let config = NSURLSessionConfiguration.defaultSessionConfiguration()

let session = NSURLSession(configuration: config, delegate: self, delegateQueue: NSOperationQueue.mainQueue())let downloadTask = session.downloadTaskWithURL(url)

downloadTask.resume()}func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {

let directoryForSave = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0] ;

//

let a = SSZipArchive.unzipFileAtPath(location.path!, toDestination: directoryForSave)

print("UNZip success result is \(a)");

NSNotificationCenter.defaultCenter().postNotificationName(IAPDownloadFinished, object: productId);

}func URLSession(session: NSURLSession, didBecomeInvalidWithError error: NSError?) {

print(error);

}func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {

print(error)

}

func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, ...


Подобные документы

  • Обзор мобильной операционной системы ios: Архитектура ОС iOS; уровень библиотек; среды разработки приложения (Xcode, Xamarin). Доступ к информации колледжа "Угреша". Требования к мобильному приложению. Подготовка среды разработки. Тестирование приложения.

    дипломная работа [5,6 M], добавлен 10.07.2014

  • Основные инструменты построения Web-приложения. Язык сценариев PHP. Системный анализ предметной области базы данных. Коды SQL запросов на создание таблиц. Разработка Web-приложения. Описание функциональности модулей. Система управления содержимым статей.

    курсовая работа [4,8 M], добавлен 28.04.2014

  • Современное состояние рынка мобильных приложений. Основные подходы к разработке мобильных приложений. Обоснование выбора целевой группы потребителей приложения. Этапы проектирования и разработки мобильного приложения для операционной системы Android.

    курсовая работа [987,1 K], добавлен 27.06.2019

  • Разработка приложений для смартфонов на ОС Android для сети аптек "Фармация". Архитектура операционной системы Android. Архитектура и реализация приложения. Его функциональность. Описание работы мобильного приложения. Расчет затрат на создание продукта.

    дипломная работа [1,6 M], добавлен 17.06.2017

  • Общая характеристика и структурная схема приложения, требования к нему и функциональные особенности, сферы практического применения. Обоснование выбора языка программирования. Описание интерфейса и инструкция пользователя. Проведение листинга программы.

    дипломная работа [1,0 M], добавлен 10.07.2017

  • Анализ российского рынка мобильных приложений. Мобильное приложение как новый канал коммуникации с целевой аудиторией. Этапы создания мобильного приложения. План продвижения мобильного приложения в сети Интернет. Бесплатные инструменты продвижения.

    дипломная работа [1,6 M], добавлен 23.06.2016

  • Разработка приложения для проверки использования времен глаголов в английском языке. Создание базы данных. Анализ используемых средств для реализации автоматического разбора текста. Проектирование мобильного приложения с помощью диаграмм деятельности.

    дипломная работа [2,6 M], добавлен 13.09.2017

  • Основы Web-программирования. Сервер баз данных MySQL. Язык сценариев PHP. Язык гипертекстовой разметки HTML. Назначение и цели разработки сайта. Форма входа и регистрации, обратная связь интернет–магазина. Требования к структуре сайта, описание контента.

    курсовая работа [754,5 K], добавлен 02.06.2014

  • Область применения и требования создаваемого Web-приложения. Требования к техническому и программному обеспечению. Разработка структуры Web-приложения и выбор средств программной реализации. Программная реализация Web-приложения. Структура базы данных.

    дипломная работа [1,4 M], добавлен 03.06.2014

  • Изучение языков программирования PHP, SQL, C++, HTML. Рассмотрение правил запуска и использования локального сервера Denwer. Составление технического задания по разработке программного продукта. Описание создаваемого мобильного и веб-приложения.

    курсовая работа [212,4 K], добавлен 07.04.2015

  • Обработка информации в электронных таблицах Excel или списках, основные понятия и требования к спискам, экономико-математические приложения Excel. Решение уравнений и задач оптимизации: подбор параметров, команда "Поиск решения", диспетчер сценариев.

    реферат [704,3 K], добавлен 08.11.2010

  • Создание многоуровневого приложения с Web-интерфейсом выставления оценки фильму и просмотра оценок других пользователей. Клиентская часть приложения. Разработка многопользовательского веб-приложения на ASP.NET MVC 3 с разграничением доступа к данным.

    курсовая работа [949,7 K], добавлен 22.02.2015

  • Общая схема работы приложения Android. Разработка обучающего приложения для операционной системы Android, назначение которого - развитие речи посредством произнесения скороговорок. Описание компонентов разработанного приложения, его тестирование.

    дипломная работа [1,2 M], добавлен 04.02.2016

  • Разработка средствами языка PHP и Фреймворка Yii системы регистрации и аутентификации пользователей на сайте. Проектирование приложения с помощью языка UML, построение диаграммы прецедентов. База данных приложения. Страница регистрации пользователей.

    отчет по практике [1,1 M], добавлен 15.09.2014

  • Общая характеристика и анализ требований к разрабатываемому приложению, функциональные особенности и сферы практического применения. Проектирование базы данных и выбор системы управления ею. Тестирование приложения и выбор языка программирования.

    дипломная работа [791,8 K], добавлен 10.07.2017

  • Требования к операционной системе Linux, встраиваемые приложения. Предсказуемость поведения, свойства ОС реального времени. Структура ядра; системные вызовы; работа с файлами. Стандартные устройства; обзор программирования; компилирование и линковка.

    лекция [112,2 K], добавлен 29.07.2012

  • Анализ популярных игровых приложений. Жанр – аркады с геймплеем Runner. Получение продукта, ориентированного на людей, использующих мобильные устройства на базе Android, и предназначенный для развлечения пользователей. Визуальная составляющая приложения.

    дипломная работа [742,7 K], добавлен 10.07.2017

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

    курсовая работа [395,4 K], добавлен 28.04.2015

  • Разработка программы-приложения для создания композиции кривых второго порядка в полярных координатах. Описание используемых констант, переменных, компонентов, процедур и функций. Источники входной и выходной информации. Требования к программе и системе.

    реферат [125,2 K], добавлен 28.05.2014

  • Базовый синтаксис языка сценариев JavaScript. Создание страниц, включающих в себя программы, которые взаимодействуют с пользователем, управляют браузером и динамически создают HTML-содержимое. Работа с объектами, которые инкапсулируют данные и поведение.

    лабораторная работа [58,6 K], добавлен 25.05.2016

Работы в архивах красиво оформлены согласно требованиям ВУЗов и содержат рисунки, диаграммы, формулы и т.д.
PPT, PPTX и PDF-файлы представлены только в архивах.
Рекомендуем скачать работу.